[ARM] Match fminnan/fmaxnan for vector vmin/vmax 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   if (Subtarget->hasNEON()) {
961     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
962     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
963     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
964     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
965   }
966
967   // We have target-specific dag combine patterns for the following nodes:
968   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
969   setTargetDAGCombine(ISD::ADD);
970   setTargetDAGCombine(ISD::SUB);
971   setTargetDAGCombine(ISD::MUL);
972   setTargetDAGCombine(ISD::AND);
973   setTargetDAGCombine(ISD::OR);
974   setTargetDAGCombine(ISD::XOR);
975
976   if (Subtarget->hasV6Ops())
977     setTargetDAGCombine(ISD::SRL);
978
979   setStackPointerRegisterToSaveRestore(ARM::SP);
980
981   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
982       !Subtarget->hasVFP2())
983     setSchedulingPreference(Sched::RegPressure);
984   else
985     setSchedulingPreference(Sched::Hybrid);
986
987   //// temporary - rewrite interface to use type
988   MaxStoresPerMemset = 8;
989   MaxStoresPerMemsetOptSize = 4;
990   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
991   MaxStoresPerMemcpyOptSize = 2;
992   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
993   MaxStoresPerMemmoveOptSize = 2;
994
995   // On ARM arguments smaller than 4 bytes are extended, so all arguments
996   // are at least 4 bytes aligned.
997   setMinStackArgumentAlignment(4);
998
999   // Prefer likely predicted branches to selects on out-of-order cores.
1000   PredictableSelectIsExpensive = Subtarget->isLikeA9();
1001
1002   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1003 }
1004
1005 bool ARMTargetLowering::useSoftFloat() const {
1006   return Subtarget->useSoftFloat();
1007 }
1008
1009 // FIXME: It might make sense to define the representative register class as the
1010 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1011 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1012 // SPR's representative would be DPR_VFP2. This should work well if register
1013 // pressure tracking were modified such that a register use would increment the
1014 // pressure of the register class's representative and all of it's super
1015 // classes' representatives transitively. We have not implemented this because
1016 // of the difficulty prior to coalescing of modeling operand register classes
1017 // due to the common occurrence of cross class copies and subregister insertions
1018 // and extractions.
1019 std::pair<const TargetRegisterClass *, uint8_t>
1020 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1021                                            MVT VT) const {
1022   const TargetRegisterClass *RRC = nullptr;
1023   uint8_t Cost = 1;
1024   switch (VT.SimpleTy) {
1025   default:
1026     return TargetLowering::findRepresentativeClass(TRI, VT);
1027   // Use DPR as representative register class for all floating point
1028   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1029   // the cost is 1 for both f32 and f64.
1030   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1031   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1032     RRC = &ARM::DPRRegClass;
1033     // When NEON is used for SP, only half of the register file is available
1034     // because operations that define both SP and DP results will be constrained
1035     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1036     // coalescing by double-counting the SP regs. See the FIXME above.
1037     if (Subtarget->useNEONForSinglePrecisionFP())
1038       Cost = 2;
1039     break;
1040   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1041   case MVT::v4f32: case MVT::v2f64:
1042     RRC = &ARM::DPRRegClass;
1043     Cost = 2;
1044     break;
1045   case MVT::v4i64:
1046     RRC = &ARM::DPRRegClass;
1047     Cost = 4;
1048     break;
1049   case MVT::v8i64:
1050     RRC = &ARM::DPRRegClass;
1051     Cost = 8;
1052     break;
1053   }
1054   return std::make_pair(RRC, Cost);
1055 }
1056
1057 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1058   switch ((ARMISD::NodeType)Opcode) {
1059   case ARMISD::FIRST_NUMBER:  break;
1060   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1061   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1062   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1063   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1064   case ARMISD::CALL:          return "ARMISD::CALL";
1065   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1066   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1067   case ARMISD::tCALL:         return "ARMISD::tCALL";
1068   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1069   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1070   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1071   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1072   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1073   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1074   case ARMISD::CMP:           return "ARMISD::CMP";
1075   case ARMISD::CMN:           return "ARMISD::CMN";
1076   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1077   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1078   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1079   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1080   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1081
1082   case ARMISD::CMOV:          return "ARMISD::CMOV";
1083
1084   case ARMISD::RBIT:          return "ARMISD::RBIT";
1085
1086   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1087   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1088   case ARMISD::RRX:           return "ARMISD::RRX";
1089
1090   case ARMISD::ADDC:          return "ARMISD::ADDC";
1091   case ARMISD::ADDE:          return "ARMISD::ADDE";
1092   case ARMISD::SUBC:          return "ARMISD::SUBC";
1093   case ARMISD::SUBE:          return "ARMISD::SUBE";
1094
1095   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1096   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1097
1098   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1099   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1100   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1101
1102   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1103
1104   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1105
1106   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1107
1108   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1109
1110   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1111
1112   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1113
1114   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1115   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1116   case ARMISD::VCGE:          return "ARMISD::VCGE";
1117   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1118   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1119   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1120   case ARMISD::VCGT:          return "ARMISD::VCGT";
1121   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1122   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1123   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1124   case ARMISD::VTST:          return "ARMISD::VTST";
1125
1126   case ARMISD::VSHL:          return "ARMISD::VSHL";
1127   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1128   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1129   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1130   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1131   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1132   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1133   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1134   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1135   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1136   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1137   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1138   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1139   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1140   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1141   case ARMISD::VSLI:          return "ARMISD::VSLI";
1142   case ARMISD::VSRI:          return "ARMISD::VSRI";
1143   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1144   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1145   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1146   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1147   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1148   case ARMISD::VDUP:          return "ARMISD::VDUP";
1149   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1150   case ARMISD::VEXT:          return "ARMISD::VEXT";
1151   case ARMISD::VREV64:        return "ARMISD::VREV64";
1152   case ARMISD::VREV32:        return "ARMISD::VREV32";
1153   case ARMISD::VREV16:        return "ARMISD::VREV16";
1154   case ARMISD::VZIP:          return "ARMISD::VZIP";
1155   case ARMISD::VUZP:          return "ARMISD::VUZP";
1156   case ARMISD::VTRN:          return "ARMISD::VTRN";
1157   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1158   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1159   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1160   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1161   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1162   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1163   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1164   case ARMISD::BFI:           return "ARMISD::BFI";
1165   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1166   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1167   case ARMISD::VBSL:          return "ARMISD::VBSL";
1168   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1169   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1170   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1171   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1172   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1173   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1174   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1175   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1176   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1177   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1178   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1179   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1180   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1181   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1182   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1183   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1184   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1185   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1186   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1187   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1188   }
1189   return nullptr;
1190 }
1191
1192 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1193                                           EVT VT) const {
1194   if (!VT.isVector())
1195     return getPointerTy(DL);
1196   return VT.changeVectorElementTypeToInteger();
1197 }
1198
1199 /// getRegClassFor - Return the register class that should be used for the
1200 /// specified value type.
1201 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1202   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1203   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1204   // load / store 4 to 8 consecutive D registers.
1205   if (Subtarget->hasNEON()) {
1206     if (VT == MVT::v4i64)
1207       return &ARM::QQPRRegClass;
1208     if (VT == MVT::v8i64)
1209       return &ARM::QQQQPRRegClass;
1210   }
1211   return TargetLowering::getRegClassFor(VT);
1212 }
1213
1214 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1215 // source/dest is aligned and the copy size is large enough. We therefore want
1216 // to align such objects passed to memory intrinsics.
1217 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1218                                                unsigned &PrefAlign) const {
1219   if (!isa<MemIntrinsic>(CI))
1220     return false;
1221   MinSize = 8;
1222   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1223   // cycle faster than 4-byte aligned LDM.
1224   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1225   return true;
1226 }
1227
1228 // Create a fast isel object.
1229 FastISel *
1230 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1231                                   const TargetLibraryInfo *libInfo) const {
1232   return ARM::createFastISel(funcInfo, libInfo);
1233 }
1234
1235 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1236   unsigned NumVals = N->getNumValues();
1237   if (!NumVals)
1238     return Sched::RegPressure;
1239
1240   for (unsigned i = 0; i != NumVals; ++i) {
1241     EVT VT = N->getValueType(i);
1242     if (VT == MVT::Glue || VT == MVT::Other)
1243       continue;
1244     if (VT.isFloatingPoint() || VT.isVector())
1245       return Sched::ILP;
1246   }
1247
1248   if (!N->isMachineOpcode())
1249     return Sched::RegPressure;
1250
1251   // Load are scheduled for latency even if there instruction itinerary
1252   // is not available.
1253   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1254   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1255
1256   if (MCID.getNumDefs() == 0)
1257     return Sched::RegPressure;
1258   if (!Itins->isEmpty() &&
1259       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1260     return Sched::ILP;
1261
1262   return Sched::RegPressure;
1263 }
1264
1265 //===----------------------------------------------------------------------===//
1266 // Lowering Code
1267 //===----------------------------------------------------------------------===//
1268
1269 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1270 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1271   switch (CC) {
1272   default: llvm_unreachable("Unknown condition code!");
1273   case ISD::SETNE:  return ARMCC::NE;
1274   case ISD::SETEQ:  return ARMCC::EQ;
1275   case ISD::SETGT:  return ARMCC::GT;
1276   case ISD::SETGE:  return ARMCC::GE;
1277   case ISD::SETLT:  return ARMCC::LT;
1278   case ISD::SETLE:  return ARMCC::LE;
1279   case ISD::SETUGT: return ARMCC::HI;
1280   case ISD::SETUGE: return ARMCC::HS;
1281   case ISD::SETULT: return ARMCC::LO;
1282   case ISD::SETULE: return ARMCC::LS;
1283   }
1284 }
1285
1286 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1287 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1288                         ARMCC::CondCodes &CondCode2) {
1289   CondCode2 = ARMCC::AL;
1290   switch (CC) {
1291   default: llvm_unreachable("Unknown FP condition!");
1292   case ISD::SETEQ:
1293   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1294   case ISD::SETGT:
1295   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1296   case ISD::SETGE:
1297   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1298   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1299   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1300   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1301   case ISD::SETO:   CondCode = ARMCC::VC; break;
1302   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1303   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1304   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1305   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1306   case ISD::SETLT:
1307   case ISD::SETULT: CondCode = ARMCC::LT; break;
1308   case ISD::SETLE:
1309   case ISD::SETULE: CondCode = ARMCC::LE; break;
1310   case ISD::SETNE:
1311   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1312   }
1313 }
1314
1315 //===----------------------------------------------------------------------===//
1316 //                      Calling Convention Implementation
1317 //===----------------------------------------------------------------------===//
1318
1319 #include "ARMGenCallingConv.inc"
1320
1321 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1322 /// account presence of floating point hardware and calling convention
1323 /// limitations, such as support for variadic functions.
1324 CallingConv::ID
1325 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1326                                            bool isVarArg) const {
1327   switch (CC) {
1328   default:
1329     llvm_unreachable("Unsupported calling convention");
1330   case CallingConv::ARM_AAPCS:
1331   case CallingConv::ARM_APCS:
1332   case CallingConv::GHC:
1333     return CC;
1334   case CallingConv::ARM_AAPCS_VFP:
1335     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1336   case CallingConv::C:
1337     if (!Subtarget->isAAPCS_ABI())
1338       return CallingConv::ARM_APCS;
1339     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1340              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1341              !isVarArg)
1342       return CallingConv::ARM_AAPCS_VFP;
1343     else
1344       return CallingConv::ARM_AAPCS;
1345   case CallingConv::Fast:
1346     if (!Subtarget->isAAPCS_ABI()) {
1347       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1348         return CallingConv::Fast;
1349       return CallingConv::ARM_APCS;
1350     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1351       return CallingConv::ARM_AAPCS_VFP;
1352     else
1353       return CallingConv::ARM_AAPCS;
1354   }
1355 }
1356
1357 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1358 /// CallingConvention.
1359 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1360                                                  bool Return,
1361                                                  bool isVarArg) const {
1362   switch (getEffectiveCallingConv(CC, isVarArg)) {
1363   default:
1364     llvm_unreachable("Unsupported calling convention");
1365   case CallingConv::ARM_APCS:
1366     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1367   case CallingConv::ARM_AAPCS:
1368     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1369   case CallingConv::ARM_AAPCS_VFP:
1370     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1371   case CallingConv::Fast:
1372     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1373   case CallingConv::GHC:
1374     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1375   }
1376 }
1377
1378 /// LowerCallResult - Lower the result values of a call into the
1379 /// appropriate copies out of appropriate physical registers.
1380 SDValue
1381 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1382                                    CallingConv::ID CallConv, bool isVarArg,
1383                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1384                                    SDLoc dl, SelectionDAG &DAG,
1385                                    SmallVectorImpl<SDValue> &InVals,
1386                                    bool isThisReturn, SDValue ThisVal) const {
1387
1388   // Assign locations to each value returned by this call.
1389   SmallVector<CCValAssign, 16> RVLocs;
1390   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1391                     *DAG.getContext(), Call);
1392   CCInfo.AnalyzeCallResult(Ins,
1393                            CCAssignFnForNode(CallConv, /* Return*/ true,
1394                                              isVarArg));
1395
1396   // Copy all of the result registers out of their specified physreg.
1397   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1398     CCValAssign VA = RVLocs[i];
1399
1400     // Pass 'this' value directly from the argument to return value, to avoid
1401     // reg unit interference
1402     if (i == 0 && isThisReturn) {
1403       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1404              "unexpected return calling convention register assignment");
1405       InVals.push_back(ThisVal);
1406       continue;
1407     }
1408
1409     SDValue Val;
1410     if (VA.needsCustom()) {
1411       // Handle f64 or half of a v2f64.
1412       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1413                                       InFlag);
1414       Chain = Lo.getValue(1);
1415       InFlag = Lo.getValue(2);
1416       VA = RVLocs[++i]; // skip ahead to next loc
1417       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1418                                       InFlag);
1419       Chain = Hi.getValue(1);
1420       InFlag = Hi.getValue(2);
1421       if (!Subtarget->isLittle())
1422         std::swap (Lo, Hi);
1423       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1424
1425       if (VA.getLocVT() == MVT::v2f64) {
1426         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1427         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1428                           DAG.getConstant(0, dl, MVT::i32));
1429
1430         VA = RVLocs[++i]; // skip ahead to next loc
1431         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1432         Chain = Lo.getValue(1);
1433         InFlag = Lo.getValue(2);
1434         VA = RVLocs[++i]; // skip ahead to next loc
1435         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1436         Chain = Hi.getValue(1);
1437         InFlag = Hi.getValue(2);
1438         if (!Subtarget->isLittle())
1439           std::swap (Lo, Hi);
1440         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1441         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1442                           DAG.getConstant(1, dl, MVT::i32));
1443       }
1444     } else {
1445       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1446                                InFlag);
1447       Chain = Val.getValue(1);
1448       InFlag = Val.getValue(2);
1449     }
1450
1451     switch (VA.getLocInfo()) {
1452     default: llvm_unreachable("Unknown loc info!");
1453     case CCValAssign::Full: break;
1454     case CCValAssign::BCvt:
1455       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1456       break;
1457     }
1458
1459     InVals.push_back(Val);
1460   }
1461
1462   return Chain;
1463 }
1464
1465 /// LowerMemOpCallTo - Store the argument to the stack.
1466 SDValue
1467 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1468                                     SDValue StackPtr, SDValue Arg,
1469                                     SDLoc dl, SelectionDAG &DAG,
1470                                     const CCValAssign &VA,
1471                                     ISD::ArgFlagsTy Flags) const {
1472   unsigned LocMemOffset = VA.getLocMemOffset();
1473   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1474   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1475                        StackPtr, PtrOff);
1476   return DAG.getStore(Chain, dl, Arg, PtrOff,
1477                       MachinePointerInfo::getStack(LocMemOffset),
1478                       false, false, 0);
1479 }
1480
1481 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1482                                          SDValue Chain, SDValue &Arg,
1483                                          RegsToPassVector &RegsToPass,
1484                                          CCValAssign &VA, CCValAssign &NextVA,
1485                                          SDValue &StackPtr,
1486                                          SmallVectorImpl<SDValue> &MemOpChains,
1487                                          ISD::ArgFlagsTy Flags) const {
1488
1489   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1490                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1491   unsigned id = Subtarget->isLittle() ? 0 : 1;
1492   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1493
1494   if (NextVA.isRegLoc())
1495     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1496   else {
1497     assert(NextVA.isMemLoc());
1498     if (!StackPtr.getNode())
1499       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1500                                     getPointerTy(DAG.getDataLayout()));
1501
1502     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1503                                            dl, DAG, NextVA,
1504                                            Flags));
1505   }
1506 }
1507
1508 /// LowerCall - Lowering a call into a callseq_start <-
1509 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1510 /// nodes.
1511 SDValue
1512 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1513                              SmallVectorImpl<SDValue> &InVals) const {
1514   SelectionDAG &DAG                     = CLI.DAG;
1515   SDLoc &dl                             = CLI.DL;
1516   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1517   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1518   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1519   SDValue Chain                         = CLI.Chain;
1520   SDValue Callee                        = CLI.Callee;
1521   bool &isTailCall                      = CLI.IsTailCall;
1522   CallingConv::ID CallConv              = CLI.CallConv;
1523   bool doesNotRet                       = CLI.DoesNotReturn;
1524   bool isVarArg                         = CLI.IsVarArg;
1525
1526   MachineFunction &MF = DAG.getMachineFunction();
1527   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1528   bool isThisReturn   = false;
1529   bool isSibCall      = false;
1530   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1531
1532   // Disable tail calls if they're not supported.
1533   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1534     isTailCall = false;
1535
1536   if (isTailCall) {
1537     // Check if it's really possible to do a tail call.
1538     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1539                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1540                                                    Outs, OutVals, Ins, DAG);
1541     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1542       report_fatal_error("failed to perform tail call elimination on a call "
1543                          "site marked musttail");
1544     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1545     // detected sibcalls.
1546     if (isTailCall) {
1547       ++NumTailCalls;
1548       isSibCall = true;
1549     }
1550   }
1551
1552   // Analyze operands of the call, assigning locations to each operand.
1553   SmallVector<CCValAssign, 16> ArgLocs;
1554   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1555                     *DAG.getContext(), Call);
1556   CCInfo.AnalyzeCallOperands(Outs,
1557                              CCAssignFnForNode(CallConv, /* Return*/ false,
1558                                                isVarArg));
1559
1560   // Get a count of how many bytes are to be pushed on the stack.
1561   unsigned NumBytes = CCInfo.getNextStackOffset();
1562
1563   // For tail calls, memory operands are available in our caller's stack.
1564   if (isSibCall)
1565     NumBytes = 0;
1566
1567   // Adjust the stack pointer for the new arguments...
1568   // These operations are automatically eliminated by the prolog/epilog pass
1569   if (!isSibCall)
1570     Chain = DAG.getCALLSEQ_START(Chain,
1571                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1572
1573   SDValue StackPtr =
1574       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1575
1576   RegsToPassVector RegsToPass;
1577   SmallVector<SDValue, 8> MemOpChains;
1578
1579   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1580   // of tail call optimization, arguments are handled later.
1581   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1582        i != e;
1583        ++i, ++realArgIdx) {
1584     CCValAssign &VA = ArgLocs[i];
1585     SDValue Arg = OutVals[realArgIdx];
1586     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1587     bool isByVal = Flags.isByVal();
1588
1589     // Promote the value if needed.
1590     switch (VA.getLocInfo()) {
1591     default: llvm_unreachable("Unknown loc info!");
1592     case CCValAssign::Full: break;
1593     case CCValAssign::SExt:
1594       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1595       break;
1596     case CCValAssign::ZExt:
1597       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1598       break;
1599     case CCValAssign::AExt:
1600       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1601       break;
1602     case CCValAssign::BCvt:
1603       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1604       break;
1605     }
1606
1607     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1608     if (VA.needsCustom()) {
1609       if (VA.getLocVT() == MVT::v2f64) {
1610         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1611                                   DAG.getConstant(0, dl, MVT::i32));
1612         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1613                                   DAG.getConstant(1, dl, MVT::i32));
1614
1615         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1616                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1617
1618         VA = ArgLocs[++i]; // skip ahead to next loc
1619         if (VA.isRegLoc()) {
1620           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1621                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1622         } else {
1623           assert(VA.isMemLoc());
1624
1625           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1626                                                  dl, DAG, VA, Flags));
1627         }
1628       } else {
1629         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1630                          StackPtr, MemOpChains, Flags);
1631       }
1632     } else if (VA.isRegLoc()) {
1633       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1634         assert(VA.getLocVT() == MVT::i32 &&
1635                "unexpected calling convention register assignment");
1636         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1637                "unexpected use of 'returned'");
1638         isThisReturn = true;
1639       }
1640       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1641     } else if (isByVal) {
1642       assert(VA.isMemLoc());
1643       unsigned offset = 0;
1644
1645       // True if this byval aggregate will be split between registers
1646       // and memory.
1647       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1648       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1649
1650       if (CurByValIdx < ByValArgsCount) {
1651
1652         unsigned RegBegin, RegEnd;
1653         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1654
1655         EVT PtrVT =
1656             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1657         unsigned int i, j;
1658         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1659           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1660           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1661           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1662                                      MachinePointerInfo(),
1663                                      false, false, false,
1664                                      DAG.InferPtrAlignment(AddArg));
1665           MemOpChains.push_back(Load.getValue(1));
1666           RegsToPass.push_back(std::make_pair(j, Load));
1667         }
1668
1669         // If parameter size outsides register area, "offset" value
1670         // helps us to calculate stack slot for remained part properly.
1671         offset = RegEnd - RegBegin;
1672
1673         CCInfo.nextInRegsParam();
1674       }
1675
1676       if (Flags.getByValSize() > 4*offset) {
1677         auto PtrVT = getPointerTy(DAG.getDataLayout());
1678         unsigned LocMemOffset = VA.getLocMemOffset();
1679         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1680         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1681         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1682         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1683         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1684                                            MVT::i32);
1685         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1686                                             MVT::i32);
1687
1688         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1689         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1690         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1691                                           Ops));
1692       }
1693     } else if (!isSibCall) {
1694       assert(VA.isMemLoc());
1695
1696       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1697                                              dl, DAG, VA, Flags));
1698     }
1699   }
1700
1701   if (!MemOpChains.empty())
1702     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1703
1704   // Build a sequence of copy-to-reg nodes chained together with token chain
1705   // and flag operands which copy the outgoing args into the appropriate regs.
1706   SDValue InFlag;
1707   // Tail call byval lowering might overwrite argument registers so in case of
1708   // tail call optimization the copies to registers are lowered later.
1709   if (!isTailCall)
1710     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1711       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1712                                RegsToPass[i].second, InFlag);
1713       InFlag = Chain.getValue(1);
1714     }
1715
1716   // For tail calls lower the arguments to the 'real' stack slot.
1717   if (isTailCall) {
1718     // Force all the incoming stack arguments to be loaded from the stack
1719     // before any new outgoing arguments are stored to the stack, because the
1720     // outgoing stack slots may alias the incoming argument stack slots, and
1721     // the alias isn't otherwise explicit. This is slightly more conservative
1722     // than necessary, because it means that each store effectively depends
1723     // on every argument instead of just those arguments it would clobber.
1724
1725     // Do not flag preceding copytoreg stuff together with the following stuff.
1726     InFlag = SDValue();
1727     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1728       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1729                                RegsToPass[i].second, InFlag);
1730       InFlag = Chain.getValue(1);
1731     }
1732     InFlag = SDValue();
1733   }
1734
1735   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1736   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1737   // node so that legalize doesn't hack it.
1738   bool isDirect = false;
1739   bool isARMFunc = false;
1740   bool isLocalARMFunc = false;
1741   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1742   auto PtrVt = getPointerTy(DAG.getDataLayout());
1743
1744   if (Subtarget->genLongCalls()) {
1745     assert((Subtarget->isTargetWindows() ||
1746             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1747            "long-calls with non-static relocation model!");
1748     // Handle a global address or an external symbol. If it's not one of
1749     // those, the target's already in a register, so we don't need to do
1750     // anything extra.
1751     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1752       const GlobalValue *GV = G->getGlobal();
1753       // Create a constant pool entry for the callee address
1754       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1755       ARMConstantPoolValue *CPV =
1756         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1757
1758       // Get the address of the callee into a register
1759       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1760       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1761       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1762                            MachinePointerInfo::getConstantPool(), false, false,
1763                            false, 0);
1764     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1765       const char *Sym = S->getSymbol();
1766
1767       // Create a constant pool entry for the callee address
1768       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1769       ARMConstantPoolValue *CPV =
1770         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1771                                       ARMPCLabelIndex, 0);
1772       // Get the address of the callee into a register
1773       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1774       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1775       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1776                            MachinePointerInfo::getConstantPool(), false, false,
1777                            false, 0);
1778     }
1779   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1780     const GlobalValue *GV = G->getGlobal();
1781     isDirect = true;
1782     bool isDef = GV->isStrongDefinitionForLinker();
1783     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1784                    getTargetMachine().getRelocationModel() != Reloc::Static;
1785     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1786     // ARM call to a local ARM function is predicable.
1787     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1788     // tBX takes a register source operand.
1789     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1790       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1791       Callee = DAG.getNode(
1792           ARMISD::WrapperPIC, dl, PtrVt,
1793           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1794       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1795                            MachinePointerInfo::getGOT(), false, false, true, 0);
1796     } else if (Subtarget->isTargetCOFF()) {
1797       assert(Subtarget->isTargetWindows() &&
1798              "Windows is the only supported COFF target");
1799       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1800                                  ? ARMII::MO_DLLIMPORT
1801                                  : ARMII::MO_NO_FLAG;
1802       Callee =
1803           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1804       if (GV->hasDLLImportStorageClass())
1805         Callee =
1806             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1807                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1808                         MachinePointerInfo::getGOT(), false, false, false, 0);
1809     } else {
1810       // On ELF targets for PIC code, direct calls should go through the PLT
1811       unsigned OpFlags = 0;
1812       if (Subtarget->isTargetELF() &&
1813           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1814         OpFlags = ARMII::MO_PLT;
1815       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1816     }
1817   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1818     isDirect = true;
1819     bool isStub = Subtarget->isTargetMachO() &&
1820                   getTargetMachine().getRelocationModel() != Reloc::Static;
1821     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1822     // tBX takes a register source operand.
1823     const char *Sym = S->getSymbol();
1824     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1825       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1826       ARMConstantPoolValue *CPV =
1827         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1828                                       ARMPCLabelIndex, 4);
1829       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1830       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1831       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1832                            MachinePointerInfo::getConstantPool(), false, false,
1833                            false, 0);
1834       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1835       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1836     } else {
1837       unsigned OpFlags = 0;
1838       // On ELF targets for PIC code, direct calls should go through the PLT
1839       if (Subtarget->isTargetELF() &&
1840                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1841         OpFlags = ARMII::MO_PLT;
1842       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1843     }
1844   }
1845
1846   // FIXME: handle tail calls differently.
1847   unsigned CallOpc;
1848   if (Subtarget->isThumb()) {
1849     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1850       CallOpc = ARMISD::CALL_NOLINK;
1851     else
1852       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1853   } else {
1854     if (!isDirect && !Subtarget->hasV5TOps())
1855       CallOpc = ARMISD::CALL_NOLINK;
1856     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1857              // Emit regular call when code size is the priority
1858              !MF.getFunction()->optForMinSize())
1859       // "mov lr, pc; b _foo" to avoid confusing the RSP
1860       CallOpc = ARMISD::CALL_NOLINK;
1861     else
1862       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1863   }
1864
1865   std::vector<SDValue> Ops;
1866   Ops.push_back(Chain);
1867   Ops.push_back(Callee);
1868
1869   // Add argument registers to the end of the list so that they are known live
1870   // into the call.
1871   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1872     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1873                                   RegsToPass[i].second.getValueType()));
1874
1875   // Add a register mask operand representing the call-preserved registers.
1876   if (!isTailCall) {
1877     const uint32_t *Mask;
1878     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1879     if (isThisReturn) {
1880       // For 'this' returns, use the R0-preserving mask if applicable
1881       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1882       if (!Mask) {
1883         // Set isThisReturn to false if the calling convention is not one that
1884         // allows 'returned' to be modeled in this way, so LowerCallResult does
1885         // not try to pass 'this' straight through
1886         isThisReturn = false;
1887         Mask = ARI->getCallPreservedMask(MF, CallConv);
1888       }
1889     } else
1890       Mask = ARI->getCallPreservedMask(MF, CallConv);
1891
1892     assert(Mask && "Missing call preserved mask for calling convention");
1893     Ops.push_back(DAG.getRegisterMask(Mask));
1894   }
1895
1896   if (InFlag.getNode())
1897     Ops.push_back(InFlag);
1898
1899   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1900   if (isTailCall) {
1901     MF.getFrameInfo()->setHasTailCall();
1902     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1903   }
1904
1905   // Returns a chain and a flag for retval copy to use.
1906   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1907   InFlag = Chain.getValue(1);
1908
1909   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1910                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1911   if (!Ins.empty())
1912     InFlag = Chain.getValue(1);
1913
1914   // Handle result values, copying them out of physregs into vregs that we
1915   // return.
1916   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1917                          InVals, isThisReturn,
1918                          isThisReturn ? OutVals[0] : SDValue());
1919 }
1920
1921 /// HandleByVal - Every parameter *after* a byval parameter is passed
1922 /// on the stack.  Remember the next parameter register to allocate,
1923 /// and then confiscate the rest of the parameter registers to insure
1924 /// this.
1925 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1926                                     unsigned Align) const {
1927   assert((State->getCallOrPrologue() == Prologue ||
1928           State->getCallOrPrologue() == Call) &&
1929          "unhandled ParmContext");
1930
1931   // Byval (as with any stack) slots are always at least 4 byte aligned.
1932   Align = std::max(Align, 4U);
1933
1934   unsigned Reg = State->AllocateReg(GPRArgRegs);
1935   if (!Reg)
1936     return;
1937
1938   unsigned AlignInRegs = Align / 4;
1939   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1940   for (unsigned i = 0; i < Waste; ++i)
1941     Reg = State->AllocateReg(GPRArgRegs);
1942
1943   if (!Reg)
1944     return;
1945
1946   unsigned Excess = 4 * (ARM::R4 - Reg);
1947
1948   // Special case when NSAA != SP and parameter size greater than size of
1949   // all remained GPR regs. In that case we can't split parameter, we must
1950   // send it to stack. We also must set NCRN to R4, so waste all
1951   // remained registers.
1952   const unsigned NSAAOffset = State->getNextStackOffset();
1953   if (NSAAOffset != 0 && Size > Excess) {
1954     while (State->AllocateReg(GPRArgRegs))
1955       ;
1956     return;
1957   }
1958
1959   // First register for byval parameter is the first register that wasn't
1960   // allocated before this method call, so it would be "reg".
1961   // If parameter is small enough to be saved in range [reg, r4), then
1962   // the end (first after last) register would be reg + param-size-in-regs,
1963   // else parameter would be splitted between registers and stack,
1964   // end register would be r4 in this case.
1965   unsigned ByValRegBegin = Reg;
1966   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1967   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1968   // Note, first register is allocated in the beginning of function already,
1969   // allocate remained amount of registers we need.
1970   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1971     State->AllocateReg(GPRArgRegs);
1972   // A byval parameter that is split between registers and memory needs its
1973   // size truncated here.
1974   // In the case where the entire structure fits in registers, we set the
1975   // size in memory to zero.
1976   Size = std::max<int>(Size - Excess, 0);
1977 }
1978
1979 /// MatchingStackOffset - Return true if the given stack call argument is
1980 /// already available in the same position (relatively) of the caller's
1981 /// incoming argument stack.
1982 static
1983 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1984                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1985                          const TargetInstrInfo *TII) {
1986   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1987   int FI = INT_MAX;
1988   if (Arg.getOpcode() == ISD::CopyFromReg) {
1989     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1990     if (!TargetRegisterInfo::isVirtualRegister(VR))
1991       return false;
1992     MachineInstr *Def = MRI->getVRegDef(VR);
1993     if (!Def)
1994       return false;
1995     if (!Flags.isByVal()) {
1996       if (!TII->isLoadFromStackSlot(Def, FI))
1997         return false;
1998     } else {
1999       return false;
2000     }
2001   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2002     if (Flags.isByVal())
2003       // ByVal argument is passed in as a pointer but it's now being
2004       // dereferenced. e.g.
2005       // define @foo(%struct.X* %A) {
2006       //   tail call @bar(%struct.X* byval %A)
2007       // }
2008       return false;
2009     SDValue Ptr = Ld->getBasePtr();
2010     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2011     if (!FINode)
2012       return false;
2013     FI = FINode->getIndex();
2014   } else
2015     return false;
2016
2017   assert(FI != INT_MAX);
2018   if (!MFI->isFixedObjectIndex(FI))
2019     return false;
2020   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2021 }
2022
2023 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2024 /// for tail call optimization. Targets which want to do tail call
2025 /// optimization should implement this function.
2026 bool
2027 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2028                                                      CallingConv::ID CalleeCC,
2029                                                      bool isVarArg,
2030                                                      bool isCalleeStructRet,
2031                                                      bool isCallerStructRet,
2032                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2033                                     const SmallVectorImpl<SDValue> &OutVals,
2034                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2035                                                      SelectionDAG& DAG) const {
2036   const Function *CallerF = DAG.getMachineFunction().getFunction();
2037   CallingConv::ID CallerCC = CallerF->getCallingConv();
2038   bool CCMatch = CallerCC == CalleeCC;
2039
2040   // Look for obvious safe cases to perform tail call optimization that do not
2041   // require ABI changes. This is what gcc calls sibcall.
2042
2043   // Do not sibcall optimize vararg calls unless the call site is not passing
2044   // any arguments.
2045   if (isVarArg && !Outs.empty())
2046     return false;
2047
2048   // Exception-handling functions need a special set of instructions to indicate
2049   // a return to the hardware. Tail-calling another function would probably
2050   // break this.
2051   if (CallerF->hasFnAttribute("interrupt"))
2052     return false;
2053
2054   // Also avoid sibcall optimization if either caller or callee uses struct
2055   // return semantics.
2056   if (isCalleeStructRet || isCallerStructRet)
2057     return false;
2058
2059   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2060   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2061   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2062   // support in the assembler and linker to be used. This would need to be
2063   // fixed to fully support tail calls in Thumb1.
2064   //
2065   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2066   // LR.  This means if we need to reload LR, it takes an extra instructions,
2067   // which outweighs the value of the tail call; but here we don't know yet
2068   // whether LR is going to be used.  Probably the right approach is to
2069   // generate the tail call here and turn it back into CALL/RET in
2070   // emitEpilogue if LR is used.
2071
2072   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2073   // but we need to make sure there are enough registers; the only valid
2074   // registers are the 4 used for parameters.  We don't currently do this
2075   // case.
2076   if (Subtarget->isThumb1Only())
2077     return false;
2078
2079   // Externally-defined functions with weak linkage should not be
2080   // tail-called on ARM when the OS does not support dynamic
2081   // pre-emption of symbols, as the AAELF spec requires normal calls
2082   // to undefined weak functions to be replaced with a NOP or jump to the
2083   // next instruction. The behaviour of branch instructions in this
2084   // situation (as used for tail calls) is implementation-defined, so we
2085   // cannot rely on the linker replacing the tail call with a return.
2086   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2087     const GlobalValue *GV = G->getGlobal();
2088     const Triple &TT = getTargetMachine().getTargetTriple();
2089     if (GV->hasExternalWeakLinkage() &&
2090         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2091       return false;
2092   }
2093
2094   // If the calling conventions do not match, then we'd better make sure the
2095   // results are returned in the same way as what the caller expects.
2096   if (!CCMatch) {
2097     SmallVector<CCValAssign, 16> RVLocs1;
2098     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2099                        *DAG.getContext(), Call);
2100     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2101
2102     SmallVector<CCValAssign, 16> RVLocs2;
2103     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2104                        *DAG.getContext(), Call);
2105     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2106
2107     if (RVLocs1.size() != RVLocs2.size())
2108       return false;
2109     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2110       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2111         return false;
2112       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2113         return false;
2114       if (RVLocs1[i].isRegLoc()) {
2115         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2116           return false;
2117       } else {
2118         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2119           return false;
2120       }
2121     }
2122   }
2123
2124   // If Caller's vararg or byval argument has been split between registers and
2125   // stack, do not perform tail call, since part of the argument is in caller's
2126   // local frame.
2127   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2128                                       getInfo<ARMFunctionInfo>();
2129   if (AFI_Caller->getArgRegsSaveSize())
2130     return false;
2131
2132   // If the callee takes no arguments then go on to check the results of the
2133   // call.
2134   if (!Outs.empty()) {
2135     // Check if stack adjustment is needed. For now, do not do this if any
2136     // argument is passed on the stack.
2137     SmallVector<CCValAssign, 16> ArgLocs;
2138     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2139                       *DAG.getContext(), Call);
2140     CCInfo.AnalyzeCallOperands(Outs,
2141                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2142     if (CCInfo.getNextStackOffset()) {
2143       MachineFunction &MF = DAG.getMachineFunction();
2144
2145       // Check if the arguments are already laid out in the right way as
2146       // the caller's fixed stack objects.
2147       MachineFrameInfo *MFI = MF.getFrameInfo();
2148       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2149       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2150       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2151            i != e;
2152            ++i, ++realArgIdx) {
2153         CCValAssign &VA = ArgLocs[i];
2154         EVT RegVT = VA.getLocVT();
2155         SDValue Arg = OutVals[realArgIdx];
2156         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2157         if (VA.getLocInfo() == CCValAssign::Indirect)
2158           return false;
2159         if (VA.needsCustom()) {
2160           // f64 and vector types are split into multiple registers or
2161           // register/stack-slot combinations.  The types will not match
2162           // the registers; give up on memory f64 refs until we figure
2163           // out what to do about this.
2164           if (!VA.isRegLoc())
2165             return false;
2166           if (!ArgLocs[++i].isRegLoc())
2167             return false;
2168           if (RegVT == MVT::v2f64) {
2169             if (!ArgLocs[++i].isRegLoc())
2170               return false;
2171             if (!ArgLocs[++i].isRegLoc())
2172               return false;
2173           }
2174         } else if (!VA.isRegLoc()) {
2175           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2176                                    MFI, MRI, TII))
2177             return false;
2178         }
2179       }
2180     }
2181   }
2182
2183   return true;
2184 }
2185
2186 bool
2187 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2188                                   MachineFunction &MF, bool isVarArg,
2189                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2190                                   LLVMContext &Context) const {
2191   SmallVector<CCValAssign, 16> RVLocs;
2192   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2193   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2194                                                     isVarArg));
2195 }
2196
2197 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2198                                     SDLoc DL, SelectionDAG &DAG) {
2199   const MachineFunction &MF = DAG.getMachineFunction();
2200   const Function *F = MF.getFunction();
2201
2202   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2203
2204   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2205   // version of the "preferred return address". These offsets affect the return
2206   // instruction if this is a return from PL1 without hypervisor extensions.
2207   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2208   //    SWI:     0      "subs pc, lr, #0"
2209   //    ABORT:   +4     "subs pc, lr, #4"
2210   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2211   // UNDEF varies depending on where the exception came from ARM or Thumb
2212   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2213
2214   int64_t LROffset;
2215   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2216       IntKind == "ABORT")
2217     LROffset = 4;
2218   else if (IntKind == "SWI" || IntKind == "UNDEF")
2219     LROffset = 0;
2220   else
2221     report_fatal_error("Unsupported interrupt attribute. If present, value "
2222                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2223
2224   RetOps.insert(RetOps.begin() + 1,
2225                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2226
2227   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2228 }
2229
2230 SDValue
2231 ARMTargetLowering::LowerReturn(SDValue Chain,
2232                                CallingConv::ID CallConv, bool isVarArg,
2233                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2234                                const SmallVectorImpl<SDValue> &OutVals,
2235                                SDLoc dl, SelectionDAG &DAG) const {
2236
2237   // CCValAssign - represent the assignment of the return value to a location.
2238   SmallVector<CCValAssign, 16> RVLocs;
2239
2240   // CCState - Info about the registers and stack slots.
2241   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2242                     *DAG.getContext(), Call);
2243
2244   // Analyze outgoing return values.
2245   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2246                                                isVarArg));
2247
2248   SDValue Flag;
2249   SmallVector<SDValue, 4> RetOps;
2250   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2251   bool isLittleEndian = Subtarget->isLittle();
2252
2253   MachineFunction &MF = DAG.getMachineFunction();
2254   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2255   AFI->setReturnRegsCount(RVLocs.size());
2256
2257   // Copy the result values into the output registers.
2258   for (unsigned i = 0, realRVLocIdx = 0;
2259        i != RVLocs.size();
2260        ++i, ++realRVLocIdx) {
2261     CCValAssign &VA = RVLocs[i];
2262     assert(VA.isRegLoc() && "Can only return in registers!");
2263
2264     SDValue Arg = OutVals[realRVLocIdx];
2265
2266     switch (VA.getLocInfo()) {
2267     default: llvm_unreachable("Unknown loc info!");
2268     case CCValAssign::Full: break;
2269     case CCValAssign::BCvt:
2270       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2271       break;
2272     }
2273
2274     if (VA.needsCustom()) {
2275       if (VA.getLocVT() == MVT::v2f64) {
2276         // Extract the first half and return it in two registers.
2277         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2278                                    DAG.getConstant(0, dl, MVT::i32));
2279         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2280                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2281
2282         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2283                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
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         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2289                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2290                                  Flag);
2291         Flag = Chain.getValue(1);
2292         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2293         VA = RVLocs[++i]; // skip ahead to next loc
2294
2295         // Extract the 2nd half and fall through to handle it as an f64 value.
2296         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2297                           DAG.getConstant(1, dl, MVT::i32));
2298       }
2299       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2300       // available.
2301       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2302                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2303       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2304                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2305                                Flag);
2306       Flag = Chain.getValue(1);
2307       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2308       VA = RVLocs[++i]; // skip ahead to next loc
2309       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2310                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2311                                Flag);
2312     } else
2313       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2314
2315     // Guarantee that all emitted copies are
2316     // stuck together, avoiding something bad.
2317     Flag = Chain.getValue(1);
2318     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2319   }
2320
2321   // Update chain and glue.
2322   RetOps[0] = Chain;
2323   if (Flag.getNode())
2324     RetOps.push_back(Flag);
2325
2326   // CPUs which aren't M-class use a special sequence to return from
2327   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2328   // though we use "subs pc, lr, #N").
2329   //
2330   // M-class CPUs actually use a normal return sequence with a special
2331   // (hardware-provided) value in LR, so the normal code path works.
2332   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2333       !Subtarget->isMClass()) {
2334     if (Subtarget->isThumb1Only())
2335       report_fatal_error("interrupt attribute is not supported in Thumb1");
2336     return LowerInterruptReturn(RetOps, dl, DAG);
2337   }
2338
2339   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2340 }
2341
2342 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2343   if (N->getNumValues() != 1)
2344     return false;
2345   if (!N->hasNUsesOfValue(1, 0))
2346     return false;
2347
2348   SDValue TCChain = Chain;
2349   SDNode *Copy = *N->use_begin();
2350   if (Copy->getOpcode() == ISD::CopyToReg) {
2351     // If the copy has a glue operand, we conservatively assume it isn't safe to
2352     // perform a tail call.
2353     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2354       return false;
2355     TCChain = Copy->getOperand(0);
2356   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2357     SDNode *VMov = Copy;
2358     // f64 returned in a pair of GPRs.
2359     SmallPtrSet<SDNode*, 2> Copies;
2360     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2361          UI != UE; ++UI) {
2362       if (UI->getOpcode() != ISD::CopyToReg)
2363         return false;
2364       Copies.insert(*UI);
2365     }
2366     if (Copies.size() > 2)
2367       return false;
2368
2369     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2370          UI != UE; ++UI) {
2371       SDValue UseChain = UI->getOperand(0);
2372       if (Copies.count(UseChain.getNode()))
2373         // Second CopyToReg
2374         Copy = *UI;
2375       else {
2376         // We are at the top of this chain.
2377         // If the copy has a glue operand, we conservatively assume it
2378         // isn't safe to perform a tail call.
2379         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2380           return false;
2381         // First CopyToReg
2382         TCChain = UseChain;
2383       }
2384     }
2385   } else if (Copy->getOpcode() == ISD::BITCAST) {
2386     // f32 returned in a single GPR.
2387     if (!Copy->hasOneUse())
2388       return false;
2389     Copy = *Copy->use_begin();
2390     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2391       return false;
2392     // If the copy has a glue operand, we conservatively assume it isn't safe to
2393     // perform a tail call.
2394     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2395       return false;
2396     TCChain = Copy->getOperand(0);
2397   } else {
2398     return false;
2399   }
2400
2401   bool HasRet = false;
2402   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2403        UI != UE; ++UI) {
2404     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2405         UI->getOpcode() != ARMISD::INTRET_FLAG)
2406       return false;
2407     HasRet = true;
2408   }
2409
2410   if (!HasRet)
2411     return false;
2412
2413   Chain = TCChain;
2414   return true;
2415 }
2416
2417 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2418   if (!Subtarget->supportsTailCall())
2419     return false;
2420
2421   auto Attr =
2422       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2423   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2424     return false;
2425
2426   return !Subtarget->isThumb1Only();
2427 }
2428
2429 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2430 // and pass the lower and high parts through.
2431 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2432   SDLoc DL(Op);
2433   SDValue WriteValue = Op->getOperand(2);
2434
2435   // This function is only supposed to be called for i64 type argument.
2436   assert(WriteValue.getValueType() == MVT::i64
2437           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2438
2439   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2440                            DAG.getConstant(0, DL, MVT::i32));
2441   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2442                            DAG.getConstant(1, DL, MVT::i32));
2443   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2444   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2445 }
2446
2447 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2448 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2449 // one of the above mentioned nodes. It has to be wrapped because otherwise
2450 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2451 // be used to form addressing mode. These wrapped nodes will be selected
2452 // into MOVi.
2453 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2454   EVT PtrVT = Op.getValueType();
2455   // FIXME there is no actual debug info here
2456   SDLoc dl(Op);
2457   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2458   SDValue Res;
2459   if (CP->isMachineConstantPoolEntry())
2460     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2461                                     CP->getAlignment());
2462   else
2463     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2464                                     CP->getAlignment());
2465   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2466 }
2467
2468 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2469   return MachineJumpTableInfo::EK_Inline;
2470 }
2471
2472 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2473                                              SelectionDAG &DAG) const {
2474   MachineFunction &MF = DAG.getMachineFunction();
2475   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2476   unsigned ARMPCLabelIndex = 0;
2477   SDLoc DL(Op);
2478   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2479   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2480   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2481   SDValue CPAddr;
2482   if (RelocM == Reloc::Static) {
2483     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2484   } else {
2485     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2486     ARMPCLabelIndex = AFI->createPICLabelUId();
2487     ARMConstantPoolValue *CPV =
2488       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2489                                       ARMCP::CPBlockAddress, PCAdj);
2490     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2491   }
2492   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2493   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2494                                MachinePointerInfo::getConstantPool(),
2495                                false, false, false, 0);
2496   if (RelocM == Reloc::Static)
2497     return Result;
2498   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2499   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2500 }
2501
2502 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2503 SDValue
2504 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2505                                                  SelectionDAG &DAG) const {
2506   SDLoc dl(GA);
2507   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2508   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2509   MachineFunction &MF = DAG.getMachineFunction();
2510   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2511   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2512   ARMConstantPoolValue *CPV =
2513     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2514                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2515   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2516   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2517   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2518                          MachinePointerInfo::getConstantPool(),
2519                          false, false, false, 0);
2520   SDValue Chain = Argument.getValue(1);
2521
2522   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2523   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2524
2525   // call __tls_get_addr.
2526   ArgListTy Args;
2527   ArgListEntry Entry;
2528   Entry.Node = Argument;
2529   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2530   Args.push_back(Entry);
2531
2532   // FIXME: is there useful debug info available here?
2533   TargetLowering::CallLoweringInfo CLI(DAG);
2534   CLI.setDebugLoc(dl).setChain(Chain)
2535     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2536                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2537                0);
2538
2539   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2540   return CallResult.first;
2541 }
2542
2543 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2544 // "local exec" model.
2545 SDValue
2546 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2547                                         SelectionDAG &DAG,
2548                                         TLSModel::Model model) const {
2549   const GlobalValue *GV = GA->getGlobal();
2550   SDLoc dl(GA);
2551   SDValue Offset;
2552   SDValue Chain = DAG.getEntryNode();
2553   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2554   // Get the Thread Pointer
2555   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2556
2557   if (model == TLSModel::InitialExec) {
2558     MachineFunction &MF = DAG.getMachineFunction();
2559     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2560     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2561     // Initial exec model.
2562     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2563     ARMConstantPoolValue *CPV =
2564       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2565                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2566                                       true);
2567     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2568     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2569     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2570                          MachinePointerInfo::getConstantPool(),
2571                          false, false, false, 0);
2572     Chain = Offset.getValue(1);
2573
2574     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2575     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2576
2577     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2578                          MachinePointerInfo::getConstantPool(),
2579                          false, false, false, 0);
2580   } else {
2581     // local exec model
2582     assert(model == TLSModel::LocalExec);
2583     ARMConstantPoolValue *CPV =
2584       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2585     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2586     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2587     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2588                          MachinePointerInfo::getConstantPool(),
2589                          false, false, false, 0);
2590   }
2591
2592   // The address of the thread local variable is the add of the thread
2593   // pointer with the offset of the variable.
2594   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2595 }
2596
2597 SDValue
2598 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2599   // TODO: implement the "local dynamic" model
2600   assert(Subtarget->isTargetELF() &&
2601          "TLS not implemented for non-ELF targets");
2602   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2603   if (DAG.getTarget().Options.EmulatedTLS)
2604     return LowerToTLSEmulatedModel(GA, DAG);
2605
2606   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2607
2608   switch (model) {
2609     case TLSModel::GeneralDynamic:
2610     case TLSModel::LocalDynamic:
2611       return LowerToTLSGeneralDynamicModel(GA, DAG);
2612     case TLSModel::InitialExec:
2613     case TLSModel::LocalExec:
2614       return LowerToTLSExecModels(GA, DAG, model);
2615   }
2616   llvm_unreachable("bogus TLS model");
2617 }
2618
2619 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2620                                                  SelectionDAG &DAG) const {
2621   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2622   SDLoc dl(Op);
2623   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2624   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2625     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2626     ARMConstantPoolValue *CPV =
2627       ARMConstantPoolConstant::Create(GV,
2628                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2629     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2630     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2631     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2632                                  CPAddr,
2633                                  MachinePointerInfo::getConstantPool(),
2634                                  false, false, false, 0);
2635     SDValue Chain = Result.getValue(1);
2636     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2637     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2638     if (!UseGOTOFF)
2639       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2640                            MachinePointerInfo::getGOT(),
2641                            false, false, false, 0);
2642     return Result;
2643   }
2644
2645   // If we have T2 ops, we can materialize the address directly via movt/movw
2646   // pair. This is always cheaper.
2647   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2648     ++NumMovwMovt;
2649     // FIXME: Once remat is capable of dealing with instructions with register
2650     // operands, expand this into two nodes.
2651     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2652                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2653   } else {
2654     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2655     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2656     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2657                        MachinePointerInfo::getConstantPool(),
2658                        false, false, false, 0);
2659   }
2660 }
2661
2662 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2663                                                     SelectionDAG &DAG) const {
2664   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2665   SDLoc dl(Op);
2666   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2667   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2668
2669   if (Subtarget->useMovt(DAG.getMachineFunction()))
2670     ++NumMovwMovt;
2671
2672   // FIXME: Once remat is capable of dealing with instructions with register
2673   // operands, expand this into multiple nodes
2674   unsigned Wrapper =
2675       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2676
2677   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2678   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2679
2680   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2681     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2682                          MachinePointerInfo::getGOT(), false, false, false, 0);
2683   return Result;
2684 }
2685
2686 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2687                                                      SelectionDAG &DAG) const {
2688   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2689   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2690          "Windows on ARM expects to use movw/movt");
2691
2692   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2693   const ARMII::TOF TargetFlags =
2694     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2695   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2696   SDValue Result;
2697   SDLoc DL(Op);
2698
2699   ++NumMovwMovt;
2700
2701   // FIXME: Once remat is capable of dealing with instructions with register
2702   // operands, expand this into two nodes.
2703   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2704                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2705                                                   TargetFlags));
2706   if (GV->hasDLLImportStorageClass())
2707     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2708                          MachinePointerInfo::getGOT(), false, false, false, 0);
2709   return Result;
2710 }
2711
2712 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2713                                                     SelectionDAG &DAG) const {
2714   assert(Subtarget->isTargetELF() &&
2715          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2716   MachineFunction &MF = DAG.getMachineFunction();
2717   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2718   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2719   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2720   SDLoc dl(Op);
2721   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2722   ARMConstantPoolValue *CPV =
2723     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2724                                   ARMPCLabelIndex, PCAdj);
2725   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2726   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2727   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2728                                MachinePointerInfo::getConstantPool(),
2729                                false, false, false, 0);
2730   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2731   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2732 }
2733
2734 SDValue
2735 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2736   SDLoc dl(Op);
2737   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2738   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2739                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2740                      Op.getOperand(1), Val);
2741 }
2742
2743 SDValue
2744 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2745   SDLoc dl(Op);
2746   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2747                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2748 }
2749
2750 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2751                                                       SelectionDAG &DAG) const {
2752   SDLoc dl(Op);
2753   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2754                      Op.getOperand(0));
2755 }
2756
2757 SDValue
2758 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2759                                           const ARMSubtarget *Subtarget) const {
2760   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2761   SDLoc dl(Op);
2762   switch (IntNo) {
2763   default: return SDValue();    // Don't custom lower most intrinsics.
2764   case Intrinsic::arm_rbit: {
2765     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2766            "RBIT intrinsic must have i32 type!");
2767     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2768   }
2769   case Intrinsic::arm_thread_pointer: {
2770     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2771     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2772   }
2773   case Intrinsic::eh_sjlj_lsda: {
2774     MachineFunction &MF = DAG.getMachineFunction();
2775     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2776     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2777     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2778     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2779     SDValue CPAddr;
2780     unsigned PCAdj = (RelocM != Reloc::PIC_)
2781       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2782     ARMConstantPoolValue *CPV =
2783       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2784                                       ARMCP::CPLSDA, PCAdj);
2785     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2786     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2787     SDValue Result =
2788       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2789                   MachinePointerInfo::getConstantPool(),
2790                   false, false, false, 0);
2791
2792     if (RelocM == Reloc::PIC_) {
2793       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2794       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2795     }
2796     return Result;
2797   }
2798   case Intrinsic::arm_neon_vmulls:
2799   case Intrinsic::arm_neon_vmullu: {
2800     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2801       ? ARMISD::VMULLs : ARMISD::VMULLu;
2802     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2803                        Op.getOperand(1), Op.getOperand(2));
2804   }
2805   case Intrinsic::arm_neon_vminnm:
2806   case Intrinsic::arm_neon_vmaxnm: {
2807     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2808       ? ISD::FMINNUM : ISD::FMAXNUM;
2809     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2810                        Op.getOperand(1), Op.getOperand(2));
2811   }
2812   case Intrinsic::arm_neon_vmins:
2813   case Intrinsic::arm_neon_vmaxs: {
2814     // v{min,max}s is overloaded between signed integers and floats.
2815     if (!Op.getValueType().isFloatingPoint())
2816       return SDValue();
2817     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2818       ? ISD::FMINNAN : ISD::FMAXNAN;
2819     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2820                        Op.getOperand(1), Op.getOperand(2));
2821   }
2822   }
2823 }
2824
2825 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2826                                  const ARMSubtarget *Subtarget) {
2827   // FIXME: handle "fence singlethread" more efficiently.
2828   SDLoc dl(Op);
2829   if (!Subtarget->hasDataBarrier()) {
2830     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2831     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2832     // here.
2833     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2834            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2835     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2836                        DAG.getConstant(0, dl, MVT::i32));
2837   }
2838
2839   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2840   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2841   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2842   if (Subtarget->isMClass()) {
2843     // Only a full system barrier exists in the M-class architectures.
2844     Domain = ARM_MB::SY;
2845   } else if (Subtarget->isSwift() && Ord == Release) {
2846     // Swift happens to implement ISHST barriers in a way that's compatible with
2847     // Release semantics but weaker than ISH so we'd be fools not to use
2848     // it. Beware: other processors probably don't!
2849     Domain = ARM_MB::ISHST;
2850   }
2851
2852   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2853                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2854                      DAG.getConstant(Domain, dl, MVT::i32));
2855 }
2856
2857 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2858                              const ARMSubtarget *Subtarget) {
2859   // ARM pre v5TE and Thumb1 does not have preload instructions.
2860   if (!(Subtarget->isThumb2() ||
2861         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2862     // Just preserve the chain.
2863     return Op.getOperand(0);
2864
2865   SDLoc dl(Op);
2866   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2867   if (!isRead &&
2868       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2869     // ARMv7 with MP extension has PLDW.
2870     return Op.getOperand(0);
2871
2872   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2873   if (Subtarget->isThumb()) {
2874     // Invert the bits.
2875     isRead = ~isRead & 1;
2876     isData = ~isData & 1;
2877   }
2878
2879   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2880                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2881                      DAG.getConstant(isData, dl, MVT::i32));
2882 }
2883
2884 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2885   MachineFunction &MF = DAG.getMachineFunction();
2886   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2887
2888   // vastart just stores the address of the VarArgsFrameIndex slot into the
2889   // memory location argument.
2890   SDLoc dl(Op);
2891   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2892   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2893   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2894   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2895                       MachinePointerInfo(SV), false, false, 0);
2896 }
2897
2898 SDValue
2899 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2900                                         SDValue &Root, SelectionDAG &DAG,
2901                                         SDLoc dl) const {
2902   MachineFunction &MF = DAG.getMachineFunction();
2903   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2904
2905   const TargetRegisterClass *RC;
2906   if (AFI->isThumb1OnlyFunction())
2907     RC = &ARM::tGPRRegClass;
2908   else
2909     RC = &ARM::GPRRegClass;
2910
2911   // Transform the arguments stored in physical registers into virtual ones.
2912   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2913   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2914
2915   SDValue ArgValue2;
2916   if (NextVA.isMemLoc()) {
2917     MachineFrameInfo *MFI = MF.getFrameInfo();
2918     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2919
2920     // Create load node to retrieve arguments from the stack.
2921     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2922     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2923                             MachinePointerInfo::getFixedStack(FI),
2924                             false, false, false, 0);
2925   } else {
2926     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2927     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2928   }
2929   if (!Subtarget->isLittle())
2930     std::swap (ArgValue, ArgValue2);
2931   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2932 }
2933
2934 // The remaining GPRs hold either the beginning of variable-argument
2935 // data, or the beginning of an aggregate passed by value (usually
2936 // byval).  Either way, we allocate stack slots adjacent to the data
2937 // provided by our caller, and store the unallocated registers there.
2938 // If this is a variadic function, the va_list pointer will begin with
2939 // these values; otherwise, this reassembles a (byval) structure that
2940 // was split between registers and memory.
2941 // Return: The frame index registers were stored into.
2942 int
2943 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2944                                   SDLoc dl, SDValue &Chain,
2945                                   const Value *OrigArg,
2946                                   unsigned InRegsParamRecordIdx,
2947                                   int ArgOffset,
2948                                   unsigned ArgSize) const {
2949   // Currently, two use-cases possible:
2950   // Case #1. Non-var-args function, and we meet first byval parameter.
2951   //          Setup first unallocated register as first byval register;
2952   //          eat all remained registers
2953   //          (these two actions are performed by HandleByVal method).
2954   //          Then, here, we initialize stack frame with
2955   //          "store-reg" instructions.
2956   // Case #2. Var-args function, that doesn't contain byval parameters.
2957   //          The same: eat all remained unallocated registers,
2958   //          initialize stack frame.
2959
2960   MachineFunction &MF = DAG.getMachineFunction();
2961   MachineFrameInfo *MFI = MF.getFrameInfo();
2962   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2963   unsigned RBegin, REnd;
2964   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2965     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2966   } else {
2967     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2968     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2969     REnd = ARM::R4;
2970   }
2971
2972   if (REnd != RBegin)
2973     ArgOffset = -4 * (ARM::R4 - RBegin);
2974
2975   auto PtrVT = getPointerTy(DAG.getDataLayout());
2976   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2977   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
2978
2979   SmallVector<SDValue, 4> MemOps;
2980   const TargetRegisterClass *RC =
2981       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2982
2983   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2984     unsigned VReg = MF.addLiveIn(Reg, RC);
2985     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2986     SDValue Store =
2987         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2988                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2989     MemOps.push_back(Store);
2990     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
2991   }
2992
2993   if (!MemOps.empty())
2994     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2995   return FrameIndex;
2996 }
2997
2998 // Setup stack frame, the va_list pointer will start from.
2999 void
3000 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3001                                         SDLoc dl, SDValue &Chain,
3002                                         unsigned ArgOffset,
3003                                         unsigned TotalArgRegsSaveSize,
3004                                         bool ForceMutable) const {
3005   MachineFunction &MF = DAG.getMachineFunction();
3006   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3007
3008   // Try to store any remaining integer argument regs
3009   // to their spots on the stack so that they may be loaded by deferencing
3010   // the result of va_next.
3011   // If there is no regs to be stored, just point address after last
3012   // argument passed via stack.
3013   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3014                                   CCInfo.getInRegsParamsCount(),
3015                                   CCInfo.getNextStackOffset(), 4);
3016   AFI->setVarArgsFrameIndex(FrameIndex);
3017 }
3018
3019 SDValue
3020 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3021                                         CallingConv::ID CallConv, bool isVarArg,
3022                                         const SmallVectorImpl<ISD::InputArg>
3023                                           &Ins,
3024                                         SDLoc dl, SelectionDAG &DAG,
3025                                         SmallVectorImpl<SDValue> &InVals)
3026                                           const {
3027   MachineFunction &MF = DAG.getMachineFunction();
3028   MachineFrameInfo *MFI = MF.getFrameInfo();
3029
3030   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3031
3032   // Assign locations to all of the incoming arguments.
3033   SmallVector<CCValAssign, 16> ArgLocs;
3034   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3035                     *DAG.getContext(), Prologue);
3036   CCInfo.AnalyzeFormalArguments(Ins,
3037                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3038                                                   isVarArg));
3039
3040   SmallVector<SDValue, 16> ArgValues;
3041   SDValue ArgValue;
3042   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3043   unsigned CurArgIdx = 0;
3044
3045   // Initially ArgRegsSaveSize is zero.
3046   // Then we increase this value each time we meet byval parameter.
3047   // We also increase this value in case of varargs function.
3048   AFI->setArgRegsSaveSize(0);
3049
3050   // Calculate the amount of stack space that we need to allocate to store
3051   // byval and variadic arguments that are passed in registers.
3052   // We need to know this before we allocate the first byval or variadic
3053   // argument, as they will be allocated a stack slot below the CFA (Canonical
3054   // Frame Address, the stack pointer at entry to the function).
3055   unsigned ArgRegBegin = ARM::R4;
3056   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3057     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3058       break;
3059
3060     CCValAssign &VA = ArgLocs[i];
3061     unsigned Index = VA.getValNo();
3062     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3063     if (!Flags.isByVal())
3064       continue;
3065
3066     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3067     unsigned RBegin, REnd;
3068     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3069     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3070
3071     CCInfo.nextInRegsParam();
3072   }
3073   CCInfo.rewindByValRegsInfo();
3074
3075   int lastInsIndex = -1;
3076   if (isVarArg && MFI->hasVAStart()) {
3077     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3078     if (RegIdx != array_lengthof(GPRArgRegs))
3079       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3080   }
3081
3082   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3083   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3084   auto PtrVT = getPointerTy(DAG.getDataLayout());
3085
3086   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3087     CCValAssign &VA = ArgLocs[i];
3088     if (Ins[VA.getValNo()].isOrigArg()) {
3089       std::advance(CurOrigArg,
3090                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3091       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3092     }
3093     // Arguments stored in registers.
3094     if (VA.isRegLoc()) {
3095       EVT RegVT = VA.getLocVT();
3096
3097       if (VA.needsCustom()) {
3098         // f64 and vector types are split up into multiple registers or
3099         // combinations of registers and stack slots.
3100         if (VA.getLocVT() == MVT::v2f64) {
3101           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3102                                                    Chain, DAG, dl);
3103           VA = ArgLocs[++i]; // skip ahead to next loc
3104           SDValue ArgValue2;
3105           if (VA.isMemLoc()) {
3106             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3107             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3108             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3109                                     MachinePointerInfo::getFixedStack(FI),
3110                                     false, false, false, 0);
3111           } else {
3112             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3113                                              Chain, DAG, dl);
3114           }
3115           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3116           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3117                                  ArgValue, ArgValue1,
3118                                  DAG.getIntPtrConstant(0, dl));
3119           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3120                                  ArgValue, ArgValue2,
3121                                  DAG.getIntPtrConstant(1, dl));
3122         } else
3123           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3124
3125       } else {
3126         const TargetRegisterClass *RC;
3127
3128         if (RegVT == MVT::f32)
3129           RC = &ARM::SPRRegClass;
3130         else if (RegVT == MVT::f64)
3131           RC = &ARM::DPRRegClass;
3132         else if (RegVT == MVT::v2f64)
3133           RC = &ARM::QPRRegClass;
3134         else if (RegVT == MVT::i32)
3135           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3136                                            : &ARM::GPRRegClass;
3137         else
3138           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3139
3140         // Transform the arguments in physical registers into virtual ones.
3141         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3142         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3143       }
3144
3145       // If this is an 8 or 16-bit value, it is really passed promoted
3146       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3147       // truncate to the right size.
3148       switch (VA.getLocInfo()) {
3149       default: llvm_unreachable("Unknown loc info!");
3150       case CCValAssign::Full: break;
3151       case CCValAssign::BCvt:
3152         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3153         break;
3154       case CCValAssign::SExt:
3155         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3156                                DAG.getValueType(VA.getValVT()));
3157         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3158         break;
3159       case CCValAssign::ZExt:
3160         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3161                                DAG.getValueType(VA.getValVT()));
3162         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3163         break;
3164       }
3165
3166       InVals.push_back(ArgValue);
3167
3168     } else { // VA.isRegLoc()
3169
3170       // sanity check
3171       assert(VA.isMemLoc());
3172       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3173
3174       int index = VA.getValNo();
3175
3176       // Some Ins[] entries become multiple ArgLoc[] entries.
3177       // Process them only once.
3178       if (index != lastInsIndex)
3179         {
3180           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3181           // FIXME: For now, all byval parameter objects are marked mutable.
3182           // This can be changed with more analysis.
3183           // In case of tail call optimization mark all arguments mutable.
3184           // Since they could be overwritten by lowering of arguments in case of
3185           // a tail call.
3186           if (Flags.isByVal()) {
3187             assert(Ins[index].isOrigArg() &&
3188                    "Byval arguments cannot be implicit");
3189             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3190
3191             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3192                                             CurByValIndex, VA.getLocMemOffset(),
3193                                             Flags.getByValSize());
3194             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3195             CCInfo.nextInRegsParam();
3196           } else {
3197             unsigned FIOffset = VA.getLocMemOffset();
3198             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3199                                             FIOffset, true);
3200
3201             // Create load nodes to retrieve arguments from the stack.
3202             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3203             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3204                                          MachinePointerInfo::getFixedStack(FI),
3205                                          false, false, false, 0));
3206           }
3207           lastInsIndex = index;
3208         }
3209     }
3210   }
3211
3212   // varargs
3213   if (isVarArg && MFI->hasVAStart())
3214     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3215                          CCInfo.getNextStackOffset(),
3216                          TotalArgRegsSaveSize);
3217
3218   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3219
3220   return Chain;
3221 }
3222
3223 /// isFloatingPointZero - Return true if this is +0.0.
3224 static bool isFloatingPointZero(SDValue Op) {
3225   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3226     return CFP->getValueAPF().isPosZero();
3227   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3228     // Maybe this has already been legalized into the constant pool?
3229     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3230       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3231       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3232         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3233           return CFP->getValueAPF().isPosZero();
3234     }
3235   } else if (Op->getOpcode() == ISD::BITCAST &&
3236              Op->getValueType(0) == MVT::f64) {
3237     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3238     // created by LowerConstantFP().
3239     SDValue BitcastOp = Op->getOperand(0);
3240     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3241       SDValue MoveOp = BitcastOp->getOperand(0);
3242       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3243           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3244         return true;
3245       }
3246     }
3247   }
3248   return false;
3249 }
3250
3251 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3252 /// the given operands.
3253 SDValue
3254 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3255                              SDValue &ARMcc, SelectionDAG &DAG,
3256                              SDLoc dl) const {
3257   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3258     unsigned C = RHSC->getZExtValue();
3259     if (!isLegalICmpImmediate(C)) {
3260       // Constant does not fit, try adjusting it by one?
3261       switch (CC) {
3262       default: break;
3263       case ISD::SETLT:
3264       case ISD::SETGE:
3265         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3266           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3267           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3268         }
3269         break;
3270       case ISD::SETULT:
3271       case ISD::SETUGE:
3272         if (C != 0 && isLegalICmpImmediate(C-1)) {
3273           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3274           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3275         }
3276         break;
3277       case ISD::SETLE:
3278       case ISD::SETGT:
3279         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3280           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3281           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3282         }
3283         break;
3284       case ISD::SETULE:
3285       case ISD::SETUGT:
3286         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3287           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3288           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3289         }
3290         break;
3291       }
3292     }
3293   }
3294
3295   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3296   ARMISD::NodeType CompareType;
3297   switch (CondCode) {
3298   default:
3299     CompareType = ARMISD::CMP;
3300     break;
3301   case ARMCC::EQ:
3302   case ARMCC::NE:
3303     // Uses only Z Flag
3304     CompareType = ARMISD::CMPZ;
3305     break;
3306   }
3307   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3308   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3309 }
3310
3311 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3312 SDValue
3313 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3314                              SDLoc dl) const {
3315   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3316   SDValue Cmp;
3317   if (!isFloatingPointZero(RHS))
3318     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3319   else
3320     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3321   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3322 }
3323
3324 /// duplicateCmp - Glue values can have only one use, so this function
3325 /// duplicates a comparison node.
3326 SDValue
3327 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3328   unsigned Opc = Cmp.getOpcode();
3329   SDLoc DL(Cmp);
3330   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3331     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3332
3333   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3334   Cmp = Cmp.getOperand(0);
3335   Opc = Cmp.getOpcode();
3336   if (Opc == ARMISD::CMPFP)
3337     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3338   else {
3339     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3340     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3341   }
3342   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3343 }
3344
3345 std::pair<SDValue, SDValue>
3346 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3347                                  SDValue &ARMcc) const {
3348   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3349
3350   SDValue Value, OverflowCmp;
3351   SDValue LHS = Op.getOperand(0);
3352   SDValue RHS = Op.getOperand(1);
3353   SDLoc dl(Op);
3354
3355   // FIXME: We are currently always generating CMPs because we don't support
3356   // generating CMN through the backend. This is not as good as the natural
3357   // CMP case because it causes a register dependency and cannot be folded
3358   // later.
3359
3360   switch (Op.getOpcode()) {
3361   default:
3362     llvm_unreachable("Unknown overflow instruction!");
3363   case ISD::SADDO:
3364     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3365     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3366     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3367     break;
3368   case ISD::UADDO:
3369     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3370     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3371     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3372     break;
3373   case ISD::SSUBO:
3374     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3375     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3376     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3377     break;
3378   case ISD::USUBO:
3379     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3380     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3381     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3382     break;
3383   } // switch (...)
3384
3385   return std::make_pair(Value, OverflowCmp);
3386 }
3387
3388
3389 SDValue
3390 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3391   // Let legalize expand this if it isn't a legal type yet.
3392   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3393     return SDValue();
3394
3395   SDValue Value, OverflowCmp;
3396   SDValue ARMcc;
3397   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3398   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3399   SDLoc dl(Op);
3400   // We use 0 and 1 as false and true values.
3401   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3402   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3403   EVT VT = Op.getValueType();
3404
3405   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3406                                  ARMcc, CCR, OverflowCmp);
3407
3408   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3409   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3410 }
3411
3412
3413 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3414   SDValue Cond = Op.getOperand(0);
3415   SDValue SelectTrue = Op.getOperand(1);
3416   SDValue SelectFalse = Op.getOperand(2);
3417   SDLoc dl(Op);
3418   unsigned Opc = Cond.getOpcode();
3419
3420   if (Cond.getResNo() == 1 &&
3421       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3422        Opc == ISD::USUBO)) {
3423     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3424       return SDValue();
3425
3426     SDValue Value, OverflowCmp;
3427     SDValue ARMcc;
3428     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3429     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3430     EVT VT = Op.getValueType();
3431
3432     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3433                    OverflowCmp, DAG);
3434   }
3435
3436   // Convert:
3437   //
3438   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3439   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3440   //
3441   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3442     const ConstantSDNode *CMOVTrue =
3443       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3444     const ConstantSDNode *CMOVFalse =
3445       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3446
3447     if (CMOVTrue && CMOVFalse) {
3448       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3449       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3450
3451       SDValue True;
3452       SDValue False;
3453       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3454         True = SelectTrue;
3455         False = SelectFalse;
3456       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3457         True = SelectFalse;
3458         False = SelectTrue;
3459       }
3460
3461       if (True.getNode() && False.getNode()) {
3462         EVT VT = Op.getValueType();
3463         SDValue ARMcc = Cond.getOperand(2);
3464         SDValue CCR = Cond.getOperand(3);
3465         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3466         assert(True.getValueType() == VT);
3467         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3468       }
3469     }
3470   }
3471
3472   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3473   // undefined bits before doing a full-word comparison with zero.
3474   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3475                      DAG.getConstant(1, dl, Cond.getValueType()));
3476
3477   return DAG.getSelectCC(dl, Cond,
3478                          DAG.getConstant(0, dl, Cond.getValueType()),
3479                          SelectTrue, SelectFalse, ISD::SETNE);
3480 }
3481
3482 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3483                                  bool &swpCmpOps, bool &swpVselOps) {
3484   // Start by selecting the GE condition code for opcodes that return true for
3485   // 'equality'
3486   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3487       CC == ISD::SETULE)
3488     CondCode = ARMCC::GE;
3489
3490   // and GT for opcodes that return false for 'equality'.
3491   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3492            CC == ISD::SETULT)
3493     CondCode = ARMCC::GT;
3494
3495   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3496   // to swap the compare operands.
3497   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3498       CC == ISD::SETULT)
3499     swpCmpOps = true;
3500
3501   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3502   // If we have an unordered opcode, we need to swap the operands to the VSEL
3503   // instruction (effectively negating the condition).
3504   //
3505   // This also has the effect of swapping which one of 'less' or 'greater'
3506   // returns true, so we also swap the compare operands. It also switches
3507   // whether we return true for 'equality', so we compensate by picking the
3508   // opposite condition code to our original choice.
3509   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3510       CC == ISD::SETUGT) {
3511     swpCmpOps = !swpCmpOps;
3512     swpVselOps = !swpVselOps;
3513     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3514   }
3515
3516   // 'ordered' is 'anything but unordered', so use the VS condition code and
3517   // swap the VSEL operands.
3518   if (CC == ISD::SETO) {
3519     CondCode = ARMCC::VS;
3520     swpVselOps = true;
3521   }
3522
3523   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3524   // code and swap the VSEL operands.
3525   if (CC == ISD::SETUNE) {
3526     CondCode = ARMCC::EQ;
3527     swpVselOps = true;
3528   }
3529 }
3530
3531 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3532                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3533                                    SDValue Cmp, SelectionDAG &DAG) const {
3534   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3535     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3536                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3537     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3538                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3539
3540     SDValue TrueLow = TrueVal.getValue(0);
3541     SDValue TrueHigh = TrueVal.getValue(1);
3542     SDValue FalseLow = FalseVal.getValue(0);
3543     SDValue FalseHigh = FalseVal.getValue(1);
3544
3545     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3546                               ARMcc, CCR, Cmp);
3547     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3548                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3549
3550     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3551   } else {
3552     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3553                        Cmp);
3554   }
3555 }
3556
3557 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3558   EVT VT = Op.getValueType();
3559   SDValue LHS = Op.getOperand(0);
3560   SDValue RHS = Op.getOperand(1);
3561   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3562   SDValue TrueVal = Op.getOperand(2);
3563   SDValue FalseVal = Op.getOperand(3);
3564   SDLoc dl(Op);
3565
3566   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3567     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3568                                                     dl);
3569
3570     // If softenSetCCOperands only returned one value, we should compare it to
3571     // zero.
3572     if (!RHS.getNode()) {
3573       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3574       CC = ISD::SETNE;
3575     }
3576   }
3577
3578   if (LHS.getValueType() == MVT::i32) {
3579     // Try to generate VSEL on ARMv8.
3580     // The VSEL instruction can't use all the usual ARM condition
3581     // codes: it only has two bits to select the condition code, so it's
3582     // constrained to use only GE, GT, VS and EQ.
3583     //
3584     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3585     // swap the operands of the previous compare instruction (effectively
3586     // inverting the compare condition, swapping 'less' and 'greater') and
3587     // sometimes need to swap the operands to the VSEL (which inverts the
3588     // condition in the sense of firing whenever the previous condition didn't)
3589     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3590                                     TrueVal.getValueType() == MVT::f64)) {
3591       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3592       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3593           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3594         CC = ISD::getSetCCInverse(CC, true);
3595         std::swap(TrueVal, FalseVal);
3596       }
3597     }
3598
3599     SDValue ARMcc;
3600     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3601     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3602     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3603   }
3604
3605   ARMCC::CondCodes CondCode, CondCode2;
3606   FPCCToARMCC(CC, CondCode, CondCode2);
3607
3608   // Try to generate VMAXNM/VMINNM on ARMv8.
3609   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3610                                   TrueVal.getValueType() == MVT::f64)) {
3611     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3612     // same operands, as follows:
3613     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3614     //   select c, a, b
3615     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3616     bool swapSides = false;
3617     if (!getTargetMachine().Options.NoNaNsFPMath) {
3618       // transformability may depend on which way around we compare
3619       switch (CC) {
3620       default:
3621         break;
3622       case ISD::SETOGT:
3623       case ISD::SETOGE:
3624       case ISD::SETOLT:
3625       case ISD::SETOLE:
3626         // the non-NaN should be RHS
3627         swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3628         break;
3629       case ISD::SETUGT:
3630       case ISD::SETUGE:
3631       case ISD::SETULT:
3632       case ISD::SETULE:
3633         // the non-NaN should be LHS
3634         swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3635         break;
3636       }
3637     }
3638     swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3639     if (swapSides) {
3640       CC = ISD::getSetCCSwappedOperands(CC);
3641       std::swap(LHS, RHS);
3642     }
3643     if (LHS == TrueVal && RHS == FalseVal) {
3644       bool canTransform = true;
3645       // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3646       if (!getTargetMachine().Options.UnsafeFPMath &&
3647           !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3648         const ConstantFPSDNode *Zero;
3649         switch (CC) {
3650         default:
3651           break;
3652         case ISD::SETOGT:
3653         case ISD::SETUGT:
3654         case ISD::SETGT:
3655           // RHS must not be -0
3656           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3657                          !Zero->isNegative();
3658           break;
3659         case ISD::SETOGE:
3660         case ISD::SETUGE:
3661         case ISD::SETGE:
3662           // LHS must not be -0
3663           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3664                          !Zero->isNegative();
3665           break;
3666         case ISD::SETOLT:
3667         case ISD::SETULT:
3668         case ISD::SETLT:
3669           // RHS must not be +0
3670           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3671                           Zero->isNegative();
3672           break;
3673         case ISD::SETOLE:
3674         case ISD::SETULE:
3675         case ISD::SETLE:
3676           // LHS must not be +0
3677           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3678                           Zero->isNegative();
3679           break;
3680         }
3681       }
3682       if (canTransform) {
3683         // Note: If one of the elements in a pair is a number and the other
3684         // element is NaN, the corresponding result element is the number.
3685         // This is consistent with the IEEE 754-2008 standard.
3686         // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3687         switch (CC) {
3688         default:
3689           break;
3690         case ISD::SETOGT:
3691         case ISD::SETOGE:
3692           if (!DAG.isKnownNeverNaN(RHS))
3693             break;
3694           return DAG.getNode(ISD::FMAXNUM, dl, VT, LHS, RHS);
3695         case ISD::SETUGT:
3696         case ISD::SETUGE:
3697           if (!DAG.isKnownNeverNaN(LHS))
3698             break;
3699         case ISD::SETGT:
3700         case ISD::SETGE:
3701           return DAG.getNode(ISD::FMAXNUM, dl, VT, LHS, RHS);
3702         case ISD::SETOLT:
3703         case ISD::SETOLE:
3704           if (!DAG.isKnownNeverNaN(RHS))
3705             break;
3706           return DAG.getNode(ISD::FMINNUM, dl, VT, LHS, RHS);
3707         case ISD::SETULT:
3708         case ISD::SETULE:
3709           if (!DAG.isKnownNeverNaN(LHS))
3710             break;
3711         case ISD::SETLT:
3712         case ISD::SETLE:
3713           return DAG.getNode(ISD::FMINNUM, dl, VT, LHS, RHS);
3714         }
3715       }
3716     }
3717
3718     bool swpCmpOps = false;
3719     bool swpVselOps = false;
3720     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3721
3722     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3723         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3724       if (swpCmpOps)
3725         std::swap(LHS, RHS);
3726       if (swpVselOps)
3727         std::swap(TrueVal, FalseVal);
3728     }
3729   }
3730
3731   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3732   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3733   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3734   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3735   if (CondCode2 != ARMCC::AL) {
3736     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3737     // FIXME: Needs another CMP because flag can have but one use.
3738     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3739     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3740   }
3741   return Result;
3742 }
3743
3744 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3745 /// to morph to an integer compare sequence.
3746 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3747                            const ARMSubtarget *Subtarget) {
3748   SDNode *N = Op.getNode();
3749   if (!N->hasOneUse())
3750     // Otherwise it requires moving the value from fp to integer registers.
3751     return false;
3752   if (!N->getNumValues())
3753     return false;
3754   EVT VT = Op.getValueType();
3755   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3756     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3757     // vmrs are very slow, e.g. cortex-a8.
3758     return false;
3759
3760   if (isFloatingPointZero(Op)) {
3761     SeenZero = true;
3762     return true;
3763   }
3764   return ISD::isNormalLoad(N);
3765 }
3766
3767 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3768   if (isFloatingPointZero(Op))
3769     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3770
3771   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3772     return DAG.getLoad(MVT::i32, SDLoc(Op),
3773                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3774                        Ld->isVolatile(), Ld->isNonTemporal(),
3775                        Ld->isInvariant(), Ld->getAlignment());
3776
3777   llvm_unreachable("Unknown VFP cmp argument!");
3778 }
3779
3780 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3781                            SDValue &RetVal1, SDValue &RetVal2) {
3782   SDLoc dl(Op);
3783
3784   if (isFloatingPointZero(Op)) {
3785     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3786     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3787     return;
3788   }
3789
3790   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3791     SDValue Ptr = Ld->getBasePtr();
3792     RetVal1 = DAG.getLoad(MVT::i32, dl,
3793                           Ld->getChain(), Ptr,
3794                           Ld->getPointerInfo(),
3795                           Ld->isVolatile(), Ld->isNonTemporal(),
3796                           Ld->isInvariant(), Ld->getAlignment());
3797
3798     EVT PtrType = Ptr.getValueType();
3799     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3800     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3801                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3802     RetVal2 = DAG.getLoad(MVT::i32, dl,
3803                           Ld->getChain(), NewPtr,
3804                           Ld->getPointerInfo().getWithOffset(4),
3805                           Ld->isVolatile(), Ld->isNonTemporal(),
3806                           Ld->isInvariant(), NewAlign);
3807     return;
3808   }
3809
3810   llvm_unreachable("Unknown VFP cmp argument!");
3811 }
3812
3813 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3814 /// f32 and even f64 comparisons to integer ones.
3815 SDValue
3816 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3817   SDValue Chain = Op.getOperand(0);
3818   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3819   SDValue LHS = Op.getOperand(2);
3820   SDValue RHS = Op.getOperand(3);
3821   SDValue Dest = Op.getOperand(4);
3822   SDLoc dl(Op);
3823
3824   bool LHSSeenZero = false;
3825   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3826   bool RHSSeenZero = false;
3827   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3828   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3829     // If unsafe fp math optimization is enabled and there are no other uses of
3830     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3831     // to an integer comparison.
3832     if (CC == ISD::SETOEQ)
3833       CC = ISD::SETEQ;
3834     else if (CC == ISD::SETUNE)
3835       CC = ISD::SETNE;
3836
3837     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3838     SDValue ARMcc;
3839     if (LHS.getValueType() == MVT::f32) {
3840       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3841                         bitcastf32Toi32(LHS, DAG), Mask);
3842       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3843                         bitcastf32Toi32(RHS, DAG), Mask);
3844       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3845       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3846       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3847                          Chain, Dest, ARMcc, CCR, Cmp);
3848     }
3849
3850     SDValue LHS1, LHS2;
3851     SDValue RHS1, RHS2;
3852     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3853     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3854     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3855     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3856     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3857     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3858     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3859     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3860     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3861   }
3862
3863   return SDValue();
3864 }
3865
3866 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3867   SDValue Chain = Op.getOperand(0);
3868   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3869   SDValue LHS = Op.getOperand(2);
3870   SDValue RHS = Op.getOperand(3);
3871   SDValue Dest = Op.getOperand(4);
3872   SDLoc dl(Op);
3873
3874   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3875     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3876                                                     dl);
3877
3878     // If softenSetCCOperands only returned one value, we should compare it to
3879     // zero.
3880     if (!RHS.getNode()) {
3881       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3882       CC = ISD::SETNE;
3883     }
3884   }
3885
3886   if (LHS.getValueType() == MVT::i32) {
3887     SDValue ARMcc;
3888     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3889     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3890     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3891                        Chain, Dest, ARMcc, CCR, Cmp);
3892   }
3893
3894   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3895
3896   if (getTargetMachine().Options.UnsafeFPMath &&
3897       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3898        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3899     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3900     if (Result.getNode())
3901       return Result;
3902   }
3903
3904   ARMCC::CondCodes CondCode, CondCode2;
3905   FPCCToARMCC(CC, CondCode, CondCode2);
3906
3907   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3908   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3909   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3910   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3911   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3912   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3913   if (CondCode2 != ARMCC::AL) {
3914     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3915     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3916     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3917   }
3918   return Res;
3919 }
3920
3921 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3922   SDValue Chain = Op.getOperand(0);
3923   SDValue Table = Op.getOperand(1);
3924   SDValue Index = Op.getOperand(2);
3925   SDLoc dl(Op);
3926
3927   EVT PTy = getPointerTy(DAG.getDataLayout());
3928   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3929   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3930   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3931   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3932   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3933   if (Subtarget->isThumb2()) {
3934     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3935     // which does another jump to the destination. This also makes it easier
3936     // to translate it to TBB / TBH later.
3937     // FIXME: This might not work if the function is extremely large.
3938     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3939                        Addr, Op.getOperand(2), JTI);
3940   }
3941   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3942     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3943                        MachinePointerInfo::getJumpTable(),
3944                        false, false, false, 0);
3945     Chain = Addr.getValue(1);
3946     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3947     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3948   } else {
3949     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3950                        MachinePointerInfo::getJumpTable(),
3951                        false, false, false, 0);
3952     Chain = Addr.getValue(1);
3953     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3954   }
3955 }
3956
3957 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3958   EVT VT = Op.getValueType();
3959   SDLoc dl(Op);
3960
3961   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3962     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3963       return Op;
3964     return DAG.UnrollVectorOp(Op.getNode());
3965   }
3966
3967   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3968          "Invalid type for custom lowering!");
3969   if (VT != MVT::v4i16)
3970     return DAG.UnrollVectorOp(Op.getNode());
3971
3972   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3973   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3974 }
3975
3976 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3977   EVT VT = Op.getValueType();
3978   if (VT.isVector())
3979     return LowerVectorFP_TO_INT(Op, DAG);
3980   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3981     RTLIB::Libcall LC;
3982     if (Op.getOpcode() == ISD::FP_TO_SINT)
3983       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3984                               Op.getValueType());
3985     else
3986       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3987                               Op.getValueType());
3988     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3989                        /*isSigned*/ false, SDLoc(Op)).first;
3990   }
3991
3992   return Op;
3993 }
3994
3995 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3996   EVT VT = Op.getValueType();
3997   SDLoc dl(Op);
3998
3999   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4000     if (VT.getVectorElementType() == MVT::f32)
4001       return Op;
4002     return DAG.UnrollVectorOp(Op.getNode());
4003   }
4004
4005   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4006          "Invalid type for custom lowering!");
4007   if (VT != MVT::v4f32)
4008     return DAG.UnrollVectorOp(Op.getNode());
4009
4010   unsigned CastOpc;
4011   unsigned Opc;
4012   switch (Op.getOpcode()) {
4013   default: llvm_unreachable("Invalid opcode!");
4014   case ISD::SINT_TO_FP:
4015     CastOpc = ISD::SIGN_EXTEND;
4016     Opc = ISD::SINT_TO_FP;
4017     break;
4018   case ISD::UINT_TO_FP:
4019     CastOpc = ISD::ZERO_EXTEND;
4020     Opc = ISD::UINT_TO_FP;
4021     break;
4022   }
4023
4024   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4025   return DAG.getNode(Opc, dl, VT, Op);
4026 }
4027
4028 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4029   EVT VT = Op.getValueType();
4030   if (VT.isVector())
4031     return LowerVectorINT_TO_FP(Op, DAG);
4032   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4033     RTLIB::Libcall LC;
4034     if (Op.getOpcode() == ISD::SINT_TO_FP)
4035       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4036                               Op.getValueType());
4037     else
4038       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4039                               Op.getValueType());
4040     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
4041                        /*isSigned*/ false, SDLoc(Op)).first;
4042   }
4043
4044   return Op;
4045 }
4046
4047 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4048   // Implement fcopysign with a fabs and a conditional fneg.
4049   SDValue Tmp0 = Op.getOperand(0);
4050   SDValue Tmp1 = Op.getOperand(1);
4051   SDLoc dl(Op);
4052   EVT VT = Op.getValueType();
4053   EVT SrcVT = Tmp1.getValueType();
4054   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4055     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4056   bool UseNEON = !InGPR && Subtarget->hasNEON();
4057
4058   if (UseNEON) {
4059     // Use VBSL to copy the sign bit.
4060     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4061     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4062                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4063     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4064     if (VT == MVT::f64)
4065       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4066                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4067                          DAG.getConstant(32, dl, MVT::i32));
4068     else /*if (VT == MVT::f32)*/
4069       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4070     if (SrcVT == MVT::f32) {
4071       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4072       if (VT == MVT::f64)
4073         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4074                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4075                            DAG.getConstant(32, dl, MVT::i32));
4076     } else if (VT == MVT::f32)
4077       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4078                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4079                          DAG.getConstant(32, dl, MVT::i32));
4080     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4081     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4082
4083     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4084                                             dl, MVT::i32);
4085     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4086     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4087                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4088
4089     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4090                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4091                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4092     if (VT == MVT::f32) {
4093       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4094       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4095                         DAG.getConstant(0, dl, MVT::i32));
4096     } else {
4097       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4098     }
4099
4100     return Res;
4101   }
4102
4103   // Bitcast operand 1 to i32.
4104   if (SrcVT == MVT::f64)
4105     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4106                        Tmp1).getValue(1);
4107   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4108
4109   // Or in the signbit with integer operations.
4110   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4111   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4112   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4113   if (VT == MVT::f32) {
4114     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4115                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4116     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4117                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4118   }
4119
4120   // f64: Or the high part with signbit and then combine two parts.
4121   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4122                      Tmp0);
4123   SDValue Lo = Tmp0.getValue(0);
4124   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4125   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4126   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4127 }
4128
4129 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4130   MachineFunction &MF = DAG.getMachineFunction();
4131   MachineFrameInfo *MFI = MF.getFrameInfo();
4132   MFI->setReturnAddressIsTaken(true);
4133
4134   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4135     return SDValue();
4136
4137   EVT VT = Op.getValueType();
4138   SDLoc dl(Op);
4139   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4140   if (Depth) {
4141     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4142     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4143     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4144                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4145                        MachinePointerInfo(), false, false, false, 0);
4146   }
4147
4148   // Return LR, which contains the return address. Mark it an implicit live-in.
4149   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4150   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4151 }
4152
4153 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4154   const ARMBaseRegisterInfo &ARI =
4155     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4156   MachineFunction &MF = DAG.getMachineFunction();
4157   MachineFrameInfo *MFI = MF.getFrameInfo();
4158   MFI->setFrameAddressIsTaken(true);
4159
4160   EVT VT = Op.getValueType();
4161   SDLoc dl(Op);  // FIXME probably not meaningful
4162   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4163   unsigned FrameReg = ARI.getFrameRegister(MF);
4164   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4165   while (Depth--)
4166     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4167                             MachinePointerInfo(),
4168                             false, false, false, 0);
4169   return FrameAddr;
4170 }
4171
4172 // FIXME? Maybe this could be a TableGen attribute on some registers and
4173 // this table could be generated automatically from RegInfo.
4174 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4175                                               SelectionDAG &DAG) const {
4176   unsigned Reg = StringSwitch<unsigned>(RegName)
4177                        .Case("sp", ARM::SP)
4178                        .Default(0);
4179   if (Reg)
4180     return Reg;
4181   report_fatal_error(Twine("Invalid register name \""
4182                               + StringRef(RegName)  + "\"."));
4183 }
4184
4185 // Result is 64 bit value so split into two 32 bit values and return as a
4186 // pair of values.
4187 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4188                                 SelectionDAG &DAG) {
4189   SDLoc DL(N);
4190
4191   // This function is only supposed to be called for i64 type destination.
4192   assert(N->getValueType(0) == MVT::i64
4193           && "ExpandREAD_REGISTER called for non-i64 type result.");
4194
4195   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4196                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4197                              N->getOperand(0),
4198                              N->getOperand(1));
4199
4200   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4201                     Read.getValue(1)));
4202   Results.push_back(Read.getOperand(0));
4203 }
4204
4205 /// ExpandBITCAST - If the target supports VFP, this function is called to
4206 /// expand a bit convert where either the source or destination type is i64 to
4207 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4208 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4209 /// vectors), since the legalizer won't know what to do with that.
4210 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4211   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4212   SDLoc dl(N);
4213   SDValue Op = N->getOperand(0);
4214
4215   // This function is only supposed to be called for i64 types, either as the
4216   // source or destination of the bit convert.
4217   EVT SrcVT = Op.getValueType();
4218   EVT DstVT = N->getValueType(0);
4219   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4220          "ExpandBITCAST called for non-i64 type");
4221
4222   // Turn i64->f64 into VMOVDRR.
4223   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4224     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4225                              DAG.getConstant(0, dl, MVT::i32));
4226     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4227                              DAG.getConstant(1, dl, MVT::i32));
4228     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4229                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4230   }
4231
4232   // Turn f64->i64 into VMOVRRD.
4233   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4234     SDValue Cvt;
4235     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4236         SrcVT.getVectorNumElements() > 1)
4237       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4238                         DAG.getVTList(MVT::i32, MVT::i32),
4239                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4240     else
4241       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4242                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4243     // Merge the pieces into a single i64 value.
4244     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4245   }
4246
4247   return SDValue();
4248 }
4249
4250 /// getZeroVector - Returns a vector of specified type with all zero elements.
4251 /// Zero vectors are used to represent vector negation and in those cases
4252 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4253 /// not support i64 elements, so sometimes the zero vectors will need to be
4254 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4255 /// zero vector.
4256 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4257   assert(VT.isVector() && "Expected a vector type");
4258   // The canonical modified immediate encoding of a zero vector is....0!
4259   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4260   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4261   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4262   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4263 }
4264
4265 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4266 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4267 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4268                                                 SelectionDAG &DAG) const {
4269   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4270   EVT VT = Op.getValueType();
4271   unsigned VTBits = VT.getSizeInBits();
4272   SDLoc dl(Op);
4273   SDValue ShOpLo = Op.getOperand(0);
4274   SDValue ShOpHi = Op.getOperand(1);
4275   SDValue ShAmt  = Op.getOperand(2);
4276   SDValue ARMcc;
4277   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4278
4279   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4280
4281   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4282                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4283   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4284   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4285                                    DAG.getConstant(VTBits, dl, MVT::i32));
4286   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4287   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4288   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4289
4290   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4291   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4292                           ISD::SETGE, ARMcc, DAG, dl);
4293   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4294   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4295                            CCR, Cmp);
4296
4297   SDValue Ops[2] = { Lo, Hi };
4298   return DAG.getMergeValues(Ops, dl);
4299 }
4300
4301 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4302 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4303 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4304                                                SelectionDAG &DAG) const {
4305   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4306   EVT VT = Op.getValueType();
4307   unsigned VTBits = VT.getSizeInBits();
4308   SDLoc dl(Op);
4309   SDValue ShOpLo = Op.getOperand(0);
4310   SDValue ShOpHi = Op.getOperand(1);
4311   SDValue ShAmt  = Op.getOperand(2);
4312   SDValue ARMcc;
4313
4314   assert(Op.getOpcode() == ISD::SHL_PARTS);
4315   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4316                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4317   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4318   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4319                                    DAG.getConstant(VTBits, dl, MVT::i32));
4320   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4321   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4322
4323   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4324   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4325   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4326                           ISD::SETGE, ARMcc, DAG, dl);
4327   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4328   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4329                            CCR, Cmp);
4330
4331   SDValue Ops[2] = { Lo, Hi };
4332   return DAG.getMergeValues(Ops, dl);
4333 }
4334
4335 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4336                                             SelectionDAG &DAG) const {
4337   // The rounding mode is in bits 23:22 of the FPSCR.
4338   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4339   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4340   // so that the shift + and get folded into a bitfield extract.
4341   SDLoc dl(Op);
4342   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4343                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4344                                               MVT::i32));
4345   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4346                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4347   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4348                               DAG.getConstant(22, dl, MVT::i32));
4349   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4350                      DAG.getConstant(3, dl, MVT::i32));
4351 }
4352
4353 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4354                          const ARMSubtarget *ST) {
4355   SDLoc dl(N);
4356   EVT VT = N->getValueType(0);
4357   if (VT.isVector()) {
4358     assert(ST->hasNEON());
4359
4360     // Compute the least significant set bit: LSB = X & -X
4361     SDValue X = N->getOperand(0);
4362     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4363     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4364
4365     EVT ElemTy = VT.getVectorElementType();
4366
4367     if (ElemTy == MVT::i8) {
4368       // Compute with: cttz(x) = ctpop(lsb - 1)
4369       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4370                                 DAG.getTargetConstant(1, dl, ElemTy));
4371       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4372       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4373     }
4374
4375     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4376         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4377       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4378       unsigned NumBits = ElemTy.getSizeInBits();
4379       SDValue WidthMinus1 =
4380           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4381                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4382       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4383       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4384     }
4385
4386     // Compute with: cttz(x) = ctpop(lsb - 1)
4387
4388     // Since we can only compute the number of bits in a byte with vcnt.8, we
4389     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4390     // and i64.
4391
4392     // Compute LSB - 1.
4393     SDValue Bits;
4394     if (ElemTy == MVT::i64) {
4395       // Load constant 0xffff'ffff'ffff'ffff to register.
4396       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4397                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4398       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4399     } else {
4400       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4401                                 DAG.getTargetConstant(1, dl, ElemTy));
4402       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4403     }
4404
4405     // Count #bits with vcnt.8.
4406     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4407     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4408     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4409
4410     // Gather the #bits with vpaddl (pairwise add.)
4411     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4412     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4413         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4414         Cnt8);
4415     if (ElemTy == MVT::i16)
4416       return Cnt16;
4417
4418     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4419     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4420         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4421         Cnt16);
4422     if (ElemTy == MVT::i32)
4423       return Cnt32;
4424
4425     assert(ElemTy == MVT::i64);
4426     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4427         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4428         Cnt32);
4429     return Cnt64;
4430   }
4431
4432   if (!ST->hasV6T2Ops())
4433     return SDValue();
4434
4435   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4436   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4437 }
4438
4439 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4440 /// for each 16-bit element from operand, repeated.  The basic idea is to
4441 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4442 ///
4443 /// Trace for v4i16:
4444 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4445 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4446 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4447 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4448 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4449 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4450 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4451 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4452 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4453   EVT VT = N->getValueType(0);
4454   SDLoc DL(N);
4455
4456   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4457   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4458   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4459   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4460   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4461   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4462 }
4463
4464 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4465 /// bit-count for each 16-bit element from the operand.  We need slightly
4466 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4467 /// 64/128-bit registers.
4468 ///
4469 /// Trace for v4i16:
4470 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4471 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4472 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4473 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4474 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4475   EVT VT = N->getValueType(0);
4476   SDLoc DL(N);
4477
4478   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4479   if (VT.is64BitVector()) {
4480     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4481     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4482                        DAG.getIntPtrConstant(0, DL));
4483   } else {
4484     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4485                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4486     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4487   }
4488 }
4489
4490 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4491 /// bit-count for each 32-bit element from the operand.  The idea here is
4492 /// to split the vector into 16-bit elements, leverage the 16-bit count
4493 /// routine, and then combine the results.
4494 ///
4495 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4496 /// input    = [v0    v1    ] (vi: 32-bit elements)
4497 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4498 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4499 /// vrev: N0 = [k1 k0 k3 k2 ]
4500 ///            [k0 k1 k2 k3 ]
4501 ///       N1 =+[k1 k0 k3 k2 ]
4502 ///            [k0 k2 k1 k3 ]
4503 ///       N2 =+[k1 k3 k0 k2 ]
4504 ///            [k0    k2    k1    k3    ]
4505 /// Extended =+[k1    k3    k0    k2    ]
4506 ///            [k0    k2    ]
4507 /// Extracted=+[k1    k3    ]
4508 ///
4509 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4510   EVT VT = N->getValueType(0);
4511   SDLoc DL(N);
4512
4513   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4514
4515   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4516   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4517   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4518   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4519   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4520
4521   if (VT.is64BitVector()) {
4522     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4523     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4524                        DAG.getIntPtrConstant(0, DL));
4525   } else {
4526     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4527                                     DAG.getIntPtrConstant(0, DL));
4528     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4529   }
4530 }
4531
4532 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4533                           const ARMSubtarget *ST) {
4534   EVT VT = N->getValueType(0);
4535
4536   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4537   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4538           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4539          "Unexpected type for custom ctpop lowering");
4540
4541   if (VT.getVectorElementType() == MVT::i32)
4542     return lowerCTPOP32BitElements(N, DAG);
4543   else
4544     return lowerCTPOP16BitElements(N, DAG);
4545 }
4546
4547 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4548                           const ARMSubtarget *ST) {
4549   EVT VT = N->getValueType(0);
4550   SDLoc dl(N);
4551
4552   if (!VT.isVector())
4553     return SDValue();
4554
4555   // Lower vector shifts on NEON to use VSHL.
4556   assert(ST->hasNEON() && "unexpected vector shift");
4557
4558   // Left shifts translate directly to the vshiftu intrinsic.
4559   if (N->getOpcode() == ISD::SHL)
4560     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4561                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4562                                        MVT::i32),
4563                        N->getOperand(0), N->getOperand(1));
4564
4565   assert((N->getOpcode() == ISD::SRA ||
4566           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4567
4568   // NEON uses the same intrinsics for both left and right shifts.  For
4569   // right shifts, the shift amounts are negative, so negate the vector of
4570   // shift amounts.
4571   EVT ShiftVT = N->getOperand(1).getValueType();
4572   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4573                                      getZeroVector(ShiftVT, DAG, dl),
4574                                      N->getOperand(1));
4575   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4576                              Intrinsic::arm_neon_vshifts :
4577                              Intrinsic::arm_neon_vshiftu);
4578   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4579                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4580                      N->getOperand(0), NegatedCount);
4581 }
4582
4583 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4584                                 const ARMSubtarget *ST) {
4585   EVT VT = N->getValueType(0);
4586   SDLoc dl(N);
4587
4588   // We can get here for a node like i32 = ISD::SHL i32, i64
4589   if (VT != MVT::i64)
4590     return SDValue();
4591
4592   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4593          "Unknown shift to lower!");
4594
4595   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4596   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4597       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4598     return SDValue();
4599
4600   // If we are in thumb mode, we don't have RRX.
4601   if (ST->isThumb1Only()) return SDValue();
4602
4603   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4604   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4605                            DAG.getConstant(0, dl, MVT::i32));
4606   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4607                            DAG.getConstant(1, dl, MVT::i32));
4608
4609   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4610   // captures the result into a carry flag.
4611   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4612   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4613
4614   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4615   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4616
4617   // Merge the pieces into a single i64 value.
4618  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4619 }
4620
4621 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4622   SDValue TmpOp0, TmpOp1;
4623   bool Invert = false;
4624   bool Swap = false;
4625   unsigned Opc = 0;
4626
4627   SDValue Op0 = Op.getOperand(0);
4628   SDValue Op1 = Op.getOperand(1);
4629   SDValue CC = Op.getOperand(2);
4630   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4631   EVT VT = Op.getValueType();
4632   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4633   SDLoc dl(Op);
4634
4635   if (Op1.getValueType().isFloatingPoint()) {
4636     switch (SetCCOpcode) {
4637     default: llvm_unreachable("Illegal FP comparison");
4638     case ISD::SETUNE:
4639     case ISD::SETNE:  Invert = true; // Fallthrough
4640     case ISD::SETOEQ:
4641     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4642     case ISD::SETOLT:
4643     case ISD::SETLT: Swap = true; // Fallthrough
4644     case ISD::SETOGT:
4645     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4646     case ISD::SETOLE:
4647     case ISD::SETLE:  Swap = true; // Fallthrough
4648     case ISD::SETOGE:
4649     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4650     case ISD::SETUGE: Swap = true; // Fallthrough
4651     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4652     case ISD::SETUGT: Swap = true; // Fallthrough
4653     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4654     case ISD::SETUEQ: Invert = true; // Fallthrough
4655     case ISD::SETONE:
4656       // Expand this to (OLT | OGT).
4657       TmpOp0 = Op0;
4658       TmpOp1 = Op1;
4659       Opc = ISD::OR;
4660       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4661       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4662       break;
4663     case ISD::SETUO: Invert = true; // Fallthrough
4664     case ISD::SETO:
4665       // Expand this to (OLT | OGE).
4666       TmpOp0 = Op0;
4667       TmpOp1 = Op1;
4668       Opc = ISD::OR;
4669       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4670       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4671       break;
4672     }
4673   } else {
4674     // Integer comparisons.
4675     switch (SetCCOpcode) {
4676     default: llvm_unreachable("Illegal integer comparison");
4677     case ISD::SETNE:  Invert = true;
4678     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4679     case ISD::SETLT:  Swap = true;
4680     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4681     case ISD::SETLE:  Swap = true;
4682     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4683     case ISD::SETULT: Swap = true;
4684     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4685     case ISD::SETULE: Swap = true;
4686     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4687     }
4688
4689     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4690     if (Opc == ARMISD::VCEQ) {
4691
4692       SDValue AndOp;
4693       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4694         AndOp = Op0;
4695       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4696         AndOp = Op1;
4697
4698       // Ignore bitconvert.
4699       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4700         AndOp = AndOp.getOperand(0);
4701
4702       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4703         Opc = ARMISD::VTST;
4704         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4705         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4706         Invert = !Invert;
4707       }
4708     }
4709   }
4710
4711   if (Swap)
4712     std::swap(Op0, Op1);
4713
4714   // If one of the operands is a constant vector zero, attempt to fold the
4715   // comparison to a specialized compare-against-zero form.
4716   SDValue SingleOp;
4717   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4718     SingleOp = Op0;
4719   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4720     if (Opc == ARMISD::VCGE)
4721       Opc = ARMISD::VCLEZ;
4722     else if (Opc == ARMISD::VCGT)
4723       Opc = ARMISD::VCLTZ;
4724     SingleOp = Op1;
4725   }
4726
4727   SDValue Result;
4728   if (SingleOp.getNode()) {
4729     switch (Opc) {
4730     case ARMISD::VCEQ:
4731       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4732     case ARMISD::VCGE:
4733       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4734     case ARMISD::VCLEZ:
4735       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4736     case ARMISD::VCGT:
4737       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4738     case ARMISD::VCLTZ:
4739       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4740     default:
4741       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4742     }
4743   } else {
4744      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4745   }
4746
4747   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4748
4749   if (Invert)
4750     Result = DAG.getNOT(dl, Result, VT);
4751
4752   return Result;
4753 }
4754
4755 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4756 /// valid vector constant for a NEON instruction with a "modified immediate"
4757 /// operand (e.g., VMOV).  If so, return the encoded value.
4758 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4759                                  unsigned SplatBitSize, SelectionDAG &DAG,
4760                                  SDLoc dl, EVT &VT, bool is128Bits,
4761                                  NEONModImmType type) {
4762   unsigned OpCmode, Imm;
4763
4764   // SplatBitSize is set to the smallest size that splats the vector, so a
4765   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4766   // immediate instructions others than VMOV do not support the 8-bit encoding
4767   // of a zero vector, and the default encoding of zero is supposed to be the
4768   // 32-bit version.
4769   if (SplatBits == 0)
4770     SplatBitSize = 32;
4771
4772   switch (SplatBitSize) {
4773   case 8:
4774     if (type != VMOVModImm)
4775       return SDValue();
4776     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4777     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4778     OpCmode = 0xe;
4779     Imm = SplatBits;
4780     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4781     break;
4782
4783   case 16:
4784     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4785     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4786     if ((SplatBits & ~0xff) == 0) {
4787       // Value = 0x00nn: Op=x, Cmode=100x.
4788       OpCmode = 0x8;
4789       Imm = SplatBits;
4790       break;
4791     }
4792     if ((SplatBits & ~0xff00) == 0) {
4793       // Value = 0xnn00: Op=x, Cmode=101x.
4794       OpCmode = 0xa;
4795       Imm = SplatBits >> 8;
4796       break;
4797     }
4798     return SDValue();
4799
4800   case 32:
4801     // NEON's 32-bit VMOV supports splat values where:
4802     // * only one byte is nonzero, or
4803     // * the least significant byte is 0xff and the second byte is nonzero, or
4804     // * the least significant 2 bytes are 0xff and the third is nonzero.
4805     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4806     if ((SplatBits & ~0xff) == 0) {
4807       // Value = 0x000000nn: Op=x, Cmode=000x.
4808       OpCmode = 0;
4809       Imm = SplatBits;
4810       break;
4811     }
4812     if ((SplatBits & ~0xff00) == 0) {
4813       // Value = 0x0000nn00: Op=x, Cmode=001x.
4814       OpCmode = 0x2;
4815       Imm = SplatBits >> 8;
4816       break;
4817     }
4818     if ((SplatBits & ~0xff0000) == 0) {
4819       // Value = 0x00nn0000: Op=x, Cmode=010x.
4820       OpCmode = 0x4;
4821       Imm = SplatBits >> 16;
4822       break;
4823     }
4824     if ((SplatBits & ~0xff000000) == 0) {
4825       // Value = 0xnn000000: Op=x, Cmode=011x.
4826       OpCmode = 0x6;
4827       Imm = SplatBits >> 24;
4828       break;
4829     }
4830
4831     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4832     if (type == OtherModImm) return SDValue();
4833
4834     if ((SplatBits & ~0xffff) == 0 &&
4835         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4836       // Value = 0x0000nnff: Op=x, Cmode=1100.
4837       OpCmode = 0xc;
4838       Imm = SplatBits >> 8;
4839       break;
4840     }
4841
4842     if ((SplatBits & ~0xffffff) == 0 &&
4843         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4844       // Value = 0x00nnffff: Op=x, Cmode=1101.
4845       OpCmode = 0xd;
4846       Imm = SplatBits >> 16;
4847       break;
4848     }
4849
4850     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4851     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4852     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4853     // and fall through here to test for a valid 64-bit splat.  But, then the
4854     // caller would also need to check and handle the change in size.
4855     return SDValue();
4856
4857   case 64: {
4858     if (type != VMOVModImm)
4859       return SDValue();
4860     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4861     uint64_t BitMask = 0xff;
4862     uint64_t Val = 0;
4863     unsigned ImmMask = 1;
4864     Imm = 0;
4865     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4866       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4867         Val |= BitMask;
4868         Imm |= ImmMask;
4869       } else if ((SplatBits & BitMask) != 0) {
4870         return SDValue();
4871       }
4872       BitMask <<= 8;
4873       ImmMask <<= 1;
4874     }
4875
4876     if (DAG.getDataLayout().isBigEndian())
4877       // swap higher and lower 32 bit word
4878       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4879
4880     // Op=1, Cmode=1110.
4881     OpCmode = 0x1e;
4882     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4883     break;
4884   }
4885
4886   default:
4887     llvm_unreachable("unexpected size for isNEONModifiedImm");
4888   }
4889
4890   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4891   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4892 }
4893
4894 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4895                                            const ARMSubtarget *ST) const {
4896   if (!ST->hasVFP3())
4897     return SDValue();
4898
4899   bool IsDouble = Op.getValueType() == MVT::f64;
4900   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4901
4902   // Use the default (constant pool) lowering for double constants when we have
4903   // an SP-only FPU
4904   if (IsDouble && Subtarget->isFPOnlySP())
4905     return SDValue();
4906
4907   // Try splatting with a VMOV.f32...
4908   APFloat FPVal = CFP->getValueAPF();
4909   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4910
4911   if (ImmVal != -1) {
4912     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4913       // We have code in place to select a valid ConstantFP already, no need to
4914       // do any mangling.
4915       return Op;
4916     }
4917
4918     // It's a float and we are trying to use NEON operations where
4919     // possible. Lower it to a splat followed by an extract.
4920     SDLoc DL(Op);
4921     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4922     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4923                                       NewVal);
4924     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4925                        DAG.getConstant(0, DL, MVT::i32));
4926   }
4927
4928   // The rest of our options are NEON only, make sure that's allowed before
4929   // proceeding..
4930   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4931     return SDValue();
4932
4933   EVT VMovVT;
4934   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4935
4936   // It wouldn't really be worth bothering for doubles except for one very
4937   // important value, which does happen to match: 0.0. So make sure we don't do
4938   // anything stupid.
4939   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4940     return SDValue();
4941
4942   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4943   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4944                                      VMovVT, false, VMOVModImm);
4945   if (NewVal != SDValue()) {
4946     SDLoc DL(Op);
4947     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4948                                       NewVal);
4949     if (IsDouble)
4950       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4951
4952     // It's a float: cast and extract a vector element.
4953     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4954                                        VecConstant);
4955     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4956                        DAG.getConstant(0, DL, MVT::i32));
4957   }
4958
4959   // Finally, try a VMVN.i32
4960   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4961                              false, VMVNModImm);
4962   if (NewVal != SDValue()) {
4963     SDLoc DL(Op);
4964     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4965
4966     if (IsDouble)
4967       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4968
4969     // It's a float: cast and extract a vector element.
4970     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4971                                        VecConstant);
4972     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4973                        DAG.getConstant(0, DL, MVT::i32));
4974   }
4975
4976   return SDValue();
4977 }
4978
4979 // check if an VEXT instruction can handle the shuffle mask when the
4980 // vector sources of the shuffle are the same.
4981 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4982   unsigned NumElts = VT.getVectorNumElements();
4983
4984   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4985   if (M[0] < 0)
4986     return false;
4987
4988   Imm = M[0];
4989
4990   // If this is a VEXT shuffle, the immediate value is the index of the first
4991   // element.  The other shuffle indices must be the successive elements after
4992   // the first one.
4993   unsigned ExpectedElt = Imm;
4994   for (unsigned i = 1; i < NumElts; ++i) {
4995     // Increment the expected index.  If it wraps around, just follow it
4996     // back to index zero and keep going.
4997     ++ExpectedElt;
4998     if (ExpectedElt == NumElts)
4999       ExpectedElt = 0;
5000
5001     if (M[i] < 0) continue; // ignore UNDEF indices
5002     if (ExpectedElt != static_cast<unsigned>(M[i]))
5003       return false;
5004   }
5005
5006   return true;
5007 }
5008
5009
5010 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5011                        bool &ReverseVEXT, unsigned &Imm) {
5012   unsigned NumElts = VT.getVectorNumElements();
5013   ReverseVEXT = false;
5014
5015   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5016   if (M[0] < 0)
5017     return false;
5018
5019   Imm = M[0];
5020
5021   // If this is a VEXT shuffle, the immediate value is the index of the first
5022   // element.  The other shuffle indices must be the successive elements after
5023   // the first one.
5024   unsigned ExpectedElt = Imm;
5025   for (unsigned i = 1; i < NumElts; ++i) {
5026     // Increment the expected index.  If it wraps around, it may still be
5027     // a VEXT but the source vectors must be swapped.
5028     ExpectedElt += 1;
5029     if (ExpectedElt == NumElts * 2) {
5030       ExpectedElt = 0;
5031       ReverseVEXT = true;
5032     }
5033
5034     if (M[i] < 0) continue; // ignore UNDEF indices
5035     if (ExpectedElt != static_cast<unsigned>(M[i]))
5036       return false;
5037   }
5038
5039   // Adjust the index value if the source operands will be swapped.
5040   if (ReverseVEXT)
5041     Imm -= NumElts;
5042
5043   return true;
5044 }
5045
5046 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5047 /// instruction with the specified blocksize.  (The order of the elements
5048 /// within each block of the vector is reversed.)
5049 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5050   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5051          "Only possible block sizes for VREV are: 16, 32, 64");
5052
5053   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5054   if (EltSz == 64)
5055     return false;
5056
5057   unsigned NumElts = VT.getVectorNumElements();
5058   unsigned BlockElts = M[0] + 1;
5059   // If the first shuffle index is UNDEF, be optimistic.
5060   if (M[0] < 0)
5061     BlockElts = BlockSize / EltSz;
5062
5063   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5064     return false;
5065
5066   for (unsigned i = 0; i < NumElts; ++i) {
5067     if (M[i] < 0) continue; // ignore UNDEF indices
5068     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5069       return false;
5070   }
5071
5072   return true;
5073 }
5074
5075 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5076   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5077   // range, then 0 is placed into the resulting vector. So pretty much any mask
5078   // of 8 elements can work here.
5079   return VT == MVT::v8i8 && M.size() == 8;
5080 }
5081
5082 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5083 // checking that pairs of elements in the shuffle mask represent the same index
5084 // in each vector, incrementing the expected index by 2 at each step.
5085 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5086 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5087 //  v2={e,f,g,h}
5088 // WhichResult gives the offset for each element in the mask based on which
5089 // of the two results it belongs to.
5090 //
5091 // The transpose can be represented either as:
5092 // result1 = shufflevector v1, v2, result1_shuffle_mask
5093 // result2 = shufflevector v1, v2, result2_shuffle_mask
5094 // where v1/v2 and the shuffle masks have the same number of elements
5095 // (here WhichResult (see below) indicates which result is being checked)
5096 //
5097 // or as:
5098 // results = shufflevector v1, v2, shuffle_mask
5099 // where both results are returned in one vector and the shuffle mask has twice
5100 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5101 // want to check the low half and high half of the shuffle mask as if it were
5102 // the other case
5103 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5104   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5105   if (EltSz == 64)
5106     return false;
5107
5108   unsigned NumElts = VT.getVectorNumElements();
5109   if (M.size() != NumElts && M.size() != NumElts*2)
5110     return false;
5111
5112   // If the mask is twice as long as the result then we need to check the upper
5113   // and lower parts of the mask
5114   for (unsigned i = 0; i < M.size(); i += NumElts) {
5115     WhichResult = M[i] == 0 ? 0 : 1;
5116     for (unsigned j = 0; j < NumElts; j += 2) {
5117       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5118           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5119         return false;
5120     }
5121   }
5122
5123   if (M.size() == NumElts*2)
5124     WhichResult = 0;
5125
5126   return true;
5127 }
5128
5129 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5130 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5131 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5132 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5133   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5134   if (EltSz == 64)
5135     return false;
5136
5137   unsigned NumElts = VT.getVectorNumElements();
5138   if (M.size() != NumElts && M.size() != NumElts*2)
5139     return false;
5140
5141   for (unsigned i = 0; i < M.size(); i += NumElts) {
5142     WhichResult = M[i] == 0 ? 0 : 1;
5143     for (unsigned j = 0; j < NumElts; j += 2) {
5144       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5145           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5146         return false;
5147     }
5148   }
5149
5150   if (M.size() == NumElts*2)
5151     WhichResult = 0;
5152
5153   return true;
5154 }
5155
5156 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5157 // that the mask elements are either all even and in steps of size 2 or all odd
5158 // and in steps of size 2.
5159 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5160 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5161 //  v2={e,f,g,h}
5162 // Requires similar checks to that of isVTRNMask with
5163 // respect the how results are returned.
5164 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5165   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5166   if (EltSz == 64)
5167     return false;
5168
5169   unsigned NumElts = VT.getVectorNumElements();
5170   if (M.size() != NumElts && M.size() != NumElts*2)
5171     return false;
5172
5173   for (unsigned i = 0; i < M.size(); i += NumElts) {
5174     WhichResult = M[i] == 0 ? 0 : 1;
5175     for (unsigned j = 0; j < NumElts; ++j) {
5176       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5177         return false;
5178     }
5179   }
5180
5181   if (M.size() == NumElts*2)
5182     WhichResult = 0;
5183
5184   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5185   if (VT.is64BitVector() && EltSz == 32)
5186     return false;
5187
5188   return true;
5189 }
5190
5191 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5192 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5193 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5194 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5195   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5196   if (EltSz == 64)
5197     return false;
5198
5199   unsigned NumElts = VT.getVectorNumElements();
5200   if (M.size() != NumElts && M.size() != NumElts*2)
5201     return false;
5202
5203   unsigned Half = NumElts / 2;
5204   for (unsigned i = 0; i < M.size(); i += NumElts) {
5205     WhichResult = M[i] == 0 ? 0 : 1;
5206     for (unsigned j = 0; j < NumElts; j += Half) {
5207       unsigned Idx = WhichResult;
5208       for (unsigned k = 0; k < Half; ++k) {
5209         int MIdx = M[i + j + k];
5210         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5211           return false;
5212         Idx += 2;
5213       }
5214     }
5215   }
5216
5217   if (M.size() == NumElts*2)
5218     WhichResult = 0;
5219
5220   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5221   if (VT.is64BitVector() && EltSz == 32)
5222     return false;
5223
5224   return true;
5225 }
5226
5227 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5228 // that pairs of elements of the shufflemask represent the same index in each
5229 // vector incrementing sequentially through the vectors.
5230 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5231 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5232 //  v2={e,f,g,h}
5233 // Requires similar checks to that of isVTRNMask with respect the how results
5234 // are returned.
5235 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5236   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5237   if (EltSz == 64)
5238     return false;
5239
5240   unsigned NumElts = VT.getVectorNumElements();
5241   if (M.size() != NumElts && M.size() != NumElts*2)
5242     return false;
5243
5244   for (unsigned i = 0; i < M.size(); i += NumElts) {
5245     WhichResult = M[i] == 0 ? 0 : 1;
5246     unsigned Idx = WhichResult * NumElts / 2;
5247     for (unsigned j = 0; j < NumElts; j += 2) {
5248       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5249           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5250         return false;
5251       Idx += 1;
5252     }
5253   }
5254
5255   if (M.size() == NumElts*2)
5256     WhichResult = 0;
5257
5258   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5259   if (VT.is64BitVector() && EltSz == 32)
5260     return false;
5261
5262   return true;
5263 }
5264
5265 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5266 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5267 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5268 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5269   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5270   if (EltSz == 64)
5271     return false;
5272
5273   unsigned NumElts = VT.getVectorNumElements();
5274   if (M.size() != NumElts && M.size() != NumElts*2)
5275     return false;
5276
5277   for (unsigned i = 0; i < M.size(); i += NumElts) {
5278     WhichResult = M[i] == 0 ? 0 : 1;
5279     unsigned Idx = WhichResult * NumElts / 2;
5280     for (unsigned j = 0; j < NumElts; j += 2) {
5281       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5282           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5283         return false;
5284       Idx += 1;
5285     }
5286   }
5287
5288   if (M.size() == NumElts*2)
5289     WhichResult = 0;
5290
5291   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5292   if (VT.is64BitVector() && EltSz == 32)
5293     return false;
5294
5295   return true;
5296 }
5297
5298 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5299 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5300 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5301                                            unsigned &WhichResult,
5302                                            bool &isV_UNDEF) {
5303   isV_UNDEF = false;
5304   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5305     return ARMISD::VTRN;
5306   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5307     return ARMISD::VUZP;
5308   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5309     return ARMISD::VZIP;
5310
5311   isV_UNDEF = true;
5312   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5313     return ARMISD::VTRN;
5314   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5315     return ARMISD::VUZP;
5316   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5317     return ARMISD::VZIP;
5318
5319   return 0;
5320 }
5321
5322 /// \return true if this is a reverse operation on an vector.
5323 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5324   unsigned NumElts = VT.getVectorNumElements();
5325   // Make sure the mask has the right size.
5326   if (NumElts != M.size())
5327       return false;
5328
5329   // Look for <15, ..., 3, -1, 1, 0>.
5330   for (unsigned i = 0; i != NumElts; ++i)
5331     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5332       return false;
5333
5334   return true;
5335 }
5336
5337 // If N is an integer constant that can be moved into a register in one
5338 // instruction, return an SDValue of such a constant (will become a MOV
5339 // instruction).  Otherwise return null.
5340 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5341                                      const ARMSubtarget *ST, SDLoc dl) {
5342   uint64_t Val;
5343   if (!isa<ConstantSDNode>(N))
5344     return SDValue();
5345   Val = cast<ConstantSDNode>(N)->getZExtValue();
5346
5347   if (ST->isThumb1Only()) {
5348     if (Val <= 255 || ~Val <= 255)
5349       return DAG.getConstant(Val, dl, MVT::i32);
5350   } else {
5351     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5352       return DAG.getConstant(Val, dl, MVT::i32);
5353   }
5354   return SDValue();
5355 }
5356
5357 // If this is a case we can't handle, return null and let the default
5358 // expansion code take care of it.
5359 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5360                                              const ARMSubtarget *ST) const {
5361   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5362   SDLoc dl(Op);
5363   EVT VT = Op.getValueType();
5364
5365   APInt SplatBits, SplatUndef;
5366   unsigned SplatBitSize;
5367   bool HasAnyUndefs;
5368   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5369     if (SplatBitSize <= 64) {
5370       // Check if an immediate VMOV works.
5371       EVT VmovVT;
5372       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5373                                       SplatUndef.getZExtValue(), SplatBitSize,
5374                                       DAG, dl, VmovVT, VT.is128BitVector(),
5375                                       VMOVModImm);
5376       if (Val.getNode()) {
5377         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5378         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5379       }
5380
5381       // Try an immediate VMVN.
5382       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5383       Val = isNEONModifiedImm(NegatedImm,
5384                                       SplatUndef.getZExtValue(), SplatBitSize,
5385                                       DAG, dl, VmovVT, VT.is128BitVector(),
5386                                       VMVNModImm);
5387       if (Val.getNode()) {
5388         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5389         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5390       }
5391
5392       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5393       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5394         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5395         if (ImmVal != -1) {
5396           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5397           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5398         }
5399       }
5400     }
5401   }
5402
5403   // Scan through the operands to see if only one value is used.
5404   //
5405   // As an optimisation, even if more than one value is used it may be more
5406   // profitable to splat with one value then change some lanes.
5407   //
5408   // Heuristically we decide to do this if the vector has a "dominant" value,
5409   // defined as splatted to more than half of the lanes.
5410   unsigned NumElts = VT.getVectorNumElements();
5411   bool isOnlyLowElement = true;
5412   bool usesOnlyOneValue = true;
5413   bool hasDominantValue = false;
5414   bool isConstant = true;
5415
5416   // Map of the number of times a particular SDValue appears in the
5417   // element list.
5418   DenseMap<SDValue, unsigned> ValueCounts;
5419   SDValue Value;
5420   for (unsigned i = 0; i < NumElts; ++i) {
5421     SDValue V = Op.getOperand(i);
5422     if (V.getOpcode() == ISD::UNDEF)
5423       continue;
5424     if (i > 0)
5425       isOnlyLowElement = false;
5426     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5427       isConstant = false;
5428
5429     ValueCounts.insert(std::make_pair(V, 0));
5430     unsigned &Count = ValueCounts[V];
5431
5432     // Is this value dominant? (takes up more than half of the lanes)
5433     if (++Count > (NumElts / 2)) {
5434       hasDominantValue = true;
5435       Value = V;
5436     }
5437   }
5438   if (ValueCounts.size() != 1)
5439     usesOnlyOneValue = false;
5440   if (!Value.getNode() && ValueCounts.size() > 0)
5441     Value = ValueCounts.begin()->first;
5442
5443   if (ValueCounts.size() == 0)
5444     return DAG.getUNDEF(VT);
5445
5446   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5447   // Keep going if we are hitting this case.
5448   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5449     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5450
5451   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5452
5453   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5454   // i32 and try again.
5455   if (hasDominantValue && EltSize <= 32) {
5456     if (!isConstant) {
5457       SDValue N;
5458
5459       // If we are VDUPing a value that comes directly from a vector, that will
5460       // cause an unnecessary move to and from a GPR, where instead we could
5461       // just use VDUPLANE. We can only do this if the lane being extracted
5462       // is at a constant index, as the VDUP from lane instructions only have
5463       // constant-index forms.
5464       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5465           isa<ConstantSDNode>(Value->getOperand(1))) {
5466         // We need to create a new undef vector to use for the VDUPLANE if the
5467         // size of the vector from which we get the value is different than the
5468         // size of the vector that we need to create. We will insert the element
5469         // such that the register coalescer will remove unnecessary copies.
5470         if (VT != Value->getOperand(0).getValueType()) {
5471           ConstantSDNode *constIndex;
5472           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5473           assert(constIndex && "The index is not a constant!");
5474           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5475                              VT.getVectorNumElements();
5476           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5477                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5478                         Value, DAG.getConstant(index, dl, MVT::i32)),
5479                            DAG.getConstant(index, dl, MVT::i32));
5480         } else
5481           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5482                         Value->getOperand(0), Value->getOperand(1));
5483       } else
5484         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5485
5486       if (!usesOnlyOneValue) {
5487         // The dominant value was splatted as 'N', but we now have to insert
5488         // all differing elements.
5489         for (unsigned I = 0; I < NumElts; ++I) {
5490           if (Op.getOperand(I) == Value)
5491             continue;
5492           SmallVector<SDValue, 3> Ops;
5493           Ops.push_back(N);
5494           Ops.push_back(Op.getOperand(I));
5495           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5496           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5497         }
5498       }
5499       return N;
5500     }
5501     if (VT.getVectorElementType().isFloatingPoint()) {
5502       SmallVector<SDValue, 8> Ops;
5503       for (unsigned i = 0; i < NumElts; ++i)
5504         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5505                                   Op.getOperand(i)));
5506       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5507       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5508       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5509       if (Val.getNode())
5510         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5511     }
5512     if (usesOnlyOneValue) {
5513       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5514       if (isConstant && Val.getNode())
5515         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5516     }
5517   }
5518
5519   // If all elements are constants and the case above didn't get hit, fall back
5520   // to the default expansion, which will generate a load from the constant
5521   // pool.
5522   if (isConstant)
5523     return SDValue();
5524
5525   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5526   if (NumElts >= 4) {
5527     SDValue shuffle = ReconstructShuffle(Op, DAG);
5528     if (shuffle != SDValue())
5529       return shuffle;
5530   }
5531
5532   // Vectors with 32- or 64-bit elements can be built by directly assigning
5533   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5534   // will be legalized.
5535   if (EltSize >= 32) {
5536     // Do the expansion with floating-point types, since that is what the VFP
5537     // registers are defined to use, and since i64 is not legal.
5538     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5539     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5540     SmallVector<SDValue, 8> Ops;
5541     for (unsigned i = 0; i < NumElts; ++i)
5542       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5543     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5544     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5545   }
5546
5547   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5548   // know the default expansion would otherwise fall back on something even
5549   // worse. For a vector with one or two non-undef values, that's
5550   // scalar_to_vector for the elements followed by a shuffle (provided the
5551   // shuffle is valid for the target) and materialization element by element
5552   // on the stack followed by a load for everything else.
5553   if (!isConstant && !usesOnlyOneValue) {
5554     SDValue Vec = DAG.getUNDEF(VT);
5555     for (unsigned i = 0 ; i < NumElts; ++i) {
5556       SDValue V = Op.getOperand(i);
5557       if (V.getOpcode() == ISD::UNDEF)
5558         continue;
5559       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5560       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5561     }
5562     return Vec;
5563   }
5564
5565   return SDValue();
5566 }
5567
5568 /// getExtFactor - Determine the adjustment factor for the position when
5569 /// generating an "extract from vector registers" instruction.
5570 static unsigned getExtFactor(SDValue &V) {
5571   EVT EltType = V.getValueType().getVectorElementType();
5572   return EltType.getSizeInBits() / 8;
5573 }
5574
5575 // Gather data to see if the operation can be modelled as a
5576 // shuffle in combination with VEXTs.
5577 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5578                                               SelectionDAG &DAG) const {
5579   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5580   SDLoc dl(Op);
5581   EVT VT = Op.getValueType();
5582   unsigned NumElts = VT.getVectorNumElements();
5583
5584   struct ShuffleSourceInfo {
5585     SDValue Vec;
5586     unsigned MinElt;
5587     unsigned MaxElt;
5588
5589     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5590     // be compatible with the shuffle we intend to construct. As a result
5591     // ShuffleVec will be some sliding window into the original Vec.
5592     SDValue ShuffleVec;
5593
5594     // Code should guarantee that element i in Vec starts at element "WindowBase
5595     // + i * WindowScale in ShuffleVec".
5596     int WindowBase;
5597     int WindowScale;
5598
5599     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5600     ShuffleSourceInfo(SDValue Vec)
5601         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5602           WindowScale(1) {}
5603   };
5604
5605   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5606   // node.
5607   SmallVector<ShuffleSourceInfo, 2> Sources;
5608   for (unsigned i = 0; i < NumElts; ++i) {
5609     SDValue V = Op.getOperand(i);
5610     if (V.getOpcode() == ISD::UNDEF)
5611       continue;
5612     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5613       // A shuffle can only come from building a vector from various
5614       // elements of other vectors.
5615       return SDValue();
5616     }
5617
5618     // Add this element source to the list if it's not already there.
5619     SDValue SourceVec = V.getOperand(0);
5620     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5621     if (Source == Sources.end())
5622       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5623
5624     // Update the minimum and maximum lane number seen.
5625     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5626     Source->MinElt = std::min(Source->MinElt, EltNo);
5627     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5628   }
5629
5630   // Currently only do something sane when at most two source vectors
5631   // are involved.
5632   if (Sources.size() > 2)
5633     return SDValue();
5634
5635   // Find out the smallest element size among result and two sources, and use
5636   // it as element size to build the shuffle_vector.
5637   EVT SmallestEltTy = VT.getVectorElementType();
5638   for (auto &Source : Sources) {
5639     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5640     if (SrcEltTy.bitsLT(SmallestEltTy))
5641       SmallestEltTy = SrcEltTy;
5642   }
5643   unsigned ResMultiplier =
5644       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5645   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5646   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5647
5648   // If the source vector is too wide or too narrow, we may nevertheless be able
5649   // to construct a compatible shuffle either by concatenating it with UNDEF or
5650   // extracting a suitable range of elements.
5651   for (auto &Src : Sources) {
5652     EVT SrcVT = Src.ShuffleVec.getValueType();
5653
5654     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5655       continue;
5656
5657     // This stage of the search produces a source with the same element type as
5658     // the original, but with a total width matching the BUILD_VECTOR output.
5659     EVT EltVT = SrcVT.getVectorElementType();
5660     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5661     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5662
5663     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5664       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5665         return SDValue();
5666       // We can pad out the smaller vector for free, so if it's part of a
5667       // shuffle...
5668       Src.ShuffleVec =
5669           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5670                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5671       continue;
5672     }
5673
5674     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5675       return SDValue();
5676
5677     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5678       // Span too large for a VEXT to cope
5679       return SDValue();
5680     }
5681
5682     if (Src.MinElt >= NumSrcElts) {
5683       // The extraction can just take the second half
5684       Src.ShuffleVec =
5685           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5686                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5687       Src.WindowBase = -NumSrcElts;
5688     } else if (Src.MaxElt < NumSrcElts) {
5689       // The extraction can just take the first half
5690       Src.ShuffleVec =
5691           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5692                       DAG.getConstant(0, dl, MVT::i32));
5693     } else {
5694       // An actual VEXT is needed
5695       SDValue VEXTSrc1 =
5696           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5697                       DAG.getConstant(0, dl, MVT::i32));
5698       SDValue VEXTSrc2 =
5699           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5700                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5701       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5702
5703       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5704                                    VEXTSrc2,
5705                                    DAG.getConstant(Imm, dl, MVT::i32));
5706       Src.WindowBase = -Src.MinElt;
5707     }
5708   }
5709
5710   // Another possible incompatibility occurs from the vector element types. We
5711   // can fix this by bitcasting the source vectors to the same type we intend
5712   // for the shuffle.
5713   for (auto &Src : Sources) {
5714     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5715     if (SrcEltTy == SmallestEltTy)
5716       continue;
5717     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5718     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5719     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5720     Src.WindowBase *= Src.WindowScale;
5721   }
5722
5723   // Final sanity check before we try to actually produce a shuffle.
5724   DEBUG(
5725     for (auto Src : Sources)
5726       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5727   );
5728
5729   // The stars all align, our next step is to produce the mask for the shuffle.
5730   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5731   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5732   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5733     SDValue Entry = Op.getOperand(i);
5734     if (Entry.getOpcode() == ISD::UNDEF)
5735       continue;
5736
5737     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5738     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5739
5740     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5741     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5742     // segment.
5743     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5744     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5745                                VT.getVectorElementType().getSizeInBits());
5746     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5747
5748     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5749     // starting at the appropriate offset.
5750     int *LaneMask = &Mask[i * ResMultiplier];
5751
5752     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5753     ExtractBase += NumElts * (Src - Sources.begin());
5754     for (int j = 0; j < LanesDefined; ++j)
5755       LaneMask[j] = ExtractBase + j;
5756   }
5757
5758   // Final check before we try to produce nonsense...
5759   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5760     return SDValue();
5761
5762   // We can't handle more than two sources. This should have already
5763   // been checked before this point.
5764   assert(Sources.size() <= 2 && "Too many sources!");
5765
5766   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5767   for (unsigned i = 0; i < Sources.size(); ++i)
5768     ShuffleOps[i] = Sources[i].ShuffleVec;
5769
5770   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5771                                          ShuffleOps[1], &Mask[0]);
5772   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5773 }
5774
5775 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5776 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5777 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5778 /// are assumed to be legal.
5779 bool
5780 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5781                                       EVT VT) const {
5782   if (VT.getVectorNumElements() == 4 &&
5783       (VT.is128BitVector() || VT.is64BitVector())) {
5784     unsigned PFIndexes[4];
5785     for (unsigned i = 0; i != 4; ++i) {
5786       if (M[i] < 0)
5787         PFIndexes[i] = 8;
5788       else
5789         PFIndexes[i] = M[i];
5790     }
5791
5792     // Compute the index in the perfect shuffle table.
5793     unsigned PFTableIndex =
5794       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5795     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5796     unsigned Cost = (PFEntry >> 30);
5797
5798     if (Cost <= 4)
5799       return true;
5800   }
5801
5802   bool ReverseVEXT, isV_UNDEF;
5803   unsigned Imm, WhichResult;
5804
5805   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5806   return (EltSize >= 32 ||
5807           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5808           isVREVMask(M, VT, 64) ||
5809           isVREVMask(M, VT, 32) ||
5810           isVREVMask(M, VT, 16) ||
5811           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5812           isVTBLMask(M, VT) ||
5813           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5814           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5815 }
5816
5817 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5818 /// the specified operations to build the shuffle.
5819 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5820                                       SDValue RHS, SelectionDAG &DAG,
5821                                       SDLoc dl) {
5822   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5823   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5824   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5825
5826   enum {
5827     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5828     OP_VREV,
5829     OP_VDUP0,
5830     OP_VDUP1,
5831     OP_VDUP2,
5832     OP_VDUP3,
5833     OP_VEXT1,
5834     OP_VEXT2,
5835     OP_VEXT3,
5836     OP_VUZPL, // VUZP, left result
5837     OP_VUZPR, // VUZP, right result
5838     OP_VZIPL, // VZIP, left result
5839     OP_VZIPR, // VZIP, right result
5840     OP_VTRNL, // VTRN, left result
5841     OP_VTRNR  // VTRN, right result
5842   };
5843
5844   if (OpNum == OP_COPY) {
5845     if (LHSID == (1*9+2)*9+3) return LHS;
5846     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5847     return RHS;
5848   }
5849
5850   SDValue OpLHS, OpRHS;
5851   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5852   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5853   EVT VT = OpLHS.getValueType();
5854
5855   switch (OpNum) {
5856   default: llvm_unreachable("Unknown shuffle opcode!");
5857   case OP_VREV:
5858     // VREV divides the vector in half and swaps within the half.
5859     if (VT.getVectorElementType() == MVT::i32 ||
5860         VT.getVectorElementType() == MVT::f32)
5861       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5862     // vrev <4 x i16> -> VREV32
5863     if (VT.getVectorElementType() == MVT::i16)
5864       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5865     // vrev <4 x i8> -> VREV16
5866     assert(VT.getVectorElementType() == MVT::i8);
5867     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5868   case OP_VDUP0:
5869   case OP_VDUP1:
5870   case OP_VDUP2:
5871   case OP_VDUP3:
5872     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5873                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5874   case OP_VEXT1:
5875   case OP_VEXT2:
5876   case OP_VEXT3:
5877     return DAG.getNode(ARMISD::VEXT, dl, VT,
5878                        OpLHS, OpRHS,
5879                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5880   case OP_VUZPL:
5881   case OP_VUZPR:
5882     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5883                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5884   case OP_VZIPL:
5885   case OP_VZIPR:
5886     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5887                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5888   case OP_VTRNL:
5889   case OP_VTRNR:
5890     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5891                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5892   }
5893 }
5894
5895 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5896                                        ArrayRef<int> ShuffleMask,
5897                                        SelectionDAG &DAG) {
5898   // Check to see if we can use the VTBL instruction.
5899   SDValue V1 = Op.getOperand(0);
5900   SDValue V2 = Op.getOperand(1);
5901   SDLoc DL(Op);
5902
5903   SmallVector<SDValue, 8> VTBLMask;
5904   for (ArrayRef<int>::iterator
5905          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5906     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5907
5908   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5909     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5910                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5911
5912   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5913                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5914 }
5915
5916 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5917                                                       SelectionDAG &DAG) {
5918   SDLoc DL(Op);
5919   SDValue OpLHS = Op.getOperand(0);
5920   EVT VT = OpLHS.getValueType();
5921
5922   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5923          "Expect an v8i16/v16i8 type");
5924   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5925   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5926   // extract the first 8 bytes into the top double word and the last 8 bytes
5927   // into the bottom double word. The v8i16 case is similar.
5928   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5929   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5930                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5931 }
5932
5933 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5934   SDValue V1 = Op.getOperand(0);
5935   SDValue V2 = Op.getOperand(1);
5936   SDLoc dl(Op);
5937   EVT VT = Op.getValueType();
5938   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5939
5940   // Convert shuffles that are directly supported on NEON to target-specific
5941   // DAG nodes, instead of keeping them as shuffles and matching them again
5942   // during code selection.  This is more efficient and avoids the possibility
5943   // of inconsistencies between legalization and selection.
5944   // FIXME: floating-point vectors should be canonicalized to integer vectors
5945   // of the same time so that they get CSEd properly.
5946   ArrayRef<int> ShuffleMask = SVN->getMask();
5947
5948   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5949   if (EltSize <= 32) {
5950     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5951       int Lane = SVN->getSplatIndex();
5952       // If this is undef splat, generate it via "just" vdup, if possible.
5953       if (Lane == -1) Lane = 0;
5954
5955       // Test if V1 is a SCALAR_TO_VECTOR.
5956       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5957         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5958       }
5959       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5960       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5961       // reaches it).
5962       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5963           !isa<ConstantSDNode>(V1.getOperand(0))) {
5964         bool IsScalarToVector = true;
5965         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5966           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5967             IsScalarToVector = false;
5968             break;
5969           }
5970         if (IsScalarToVector)
5971           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5972       }
5973       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5974                          DAG.getConstant(Lane, dl, MVT::i32));
5975     }
5976
5977     bool ReverseVEXT;
5978     unsigned Imm;
5979     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5980       if (ReverseVEXT)
5981         std::swap(V1, V2);
5982       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5983                          DAG.getConstant(Imm, dl, MVT::i32));
5984     }
5985
5986     if (isVREVMask(ShuffleMask, VT, 64))
5987       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5988     if (isVREVMask(ShuffleMask, VT, 32))
5989       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5990     if (isVREVMask(ShuffleMask, VT, 16))
5991       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5992
5993     if (V2->getOpcode() == ISD::UNDEF &&
5994         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5995       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5996                          DAG.getConstant(Imm, dl, MVT::i32));
5997     }
5998
5999     // Check for Neon shuffles that modify both input vectors in place.
6000     // If both results are used, i.e., if there are two shuffles with the same
6001     // source operands and with masks corresponding to both results of one of
6002     // these operations, DAG memoization will ensure that a single node is
6003     // used for both shuffles.
6004     unsigned WhichResult;
6005     bool isV_UNDEF;
6006     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6007             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6008       if (isV_UNDEF)
6009         V2 = V1;
6010       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6011           .getValue(WhichResult);
6012     }
6013
6014     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6015     // shuffles that produce a result larger than their operands with:
6016     //   shuffle(concat(v1, undef), concat(v2, undef))
6017     // ->
6018     //   shuffle(concat(v1, v2), undef)
6019     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6020     //
6021     // This is useful in the general case, but there are special cases where
6022     // native shuffles produce larger results: the two-result ops.
6023     //
6024     // Look through the concat when lowering them:
6025     //   shuffle(concat(v1, v2), undef)
6026     // ->
6027     //   concat(VZIP(v1, v2):0, :1)
6028     //
6029     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
6030         V2->getOpcode() == ISD::UNDEF) {
6031       SDValue SubV1 = V1->getOperand(0);
6032       SDValue SubV2 = V1->getOperand(1);
6033       EVT SubVT = SubV1.getValueType();
6034
6035       // We expect these to have been canonicalized to -1.
6036       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
6037         return i < (int)VT.getVectorNumElements();
6038       }) && "Unexpected shuffle index into UNDEF operand!");
6039
6040       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6041               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6042         if (isV_UNDEF)
6043           SubV2 = SubV1;
6044         assert((WhichResult == 0) &&
6045                "In-place shuffle of concat can only have one result!");
6046         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6047                                   SubV1, SubV2);
6048         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6049                            Res.getValue(1));
6050       }
6051     }
6052   }
6053
6054   // If the shuffle is not directly supported and it has 4 elements, use
6055   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6056   unsigned NumElts = VT.getVectorNumElements();
6057   if (NumElts == 4) {
6058     unsigned PFIndexes[4];
6059     for (unsigned i = 0; i != 4; ++i) {
6060       if (ShuffleMask[i] < 0)
6061         PFIndexes[i] = 8;
6062       else
6063         PFIndexes[i] = ShuffleMask[i];
6064     }
6065
6066     // Compute the index in the perfect shuffle table.
6067     unsigned PFTableIndex =
6068       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6069     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6070     unsigned Cost = (PFEntry >> 30);
6071
6072     if (Cost <= 4)
6073       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6074   }
6075
6076   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6077   if (EltSize >= 32) {
6078     // Do the expansion with floating-point types, since that is what the VFP
6079     // registers are defined to use, and since i64 is not legal.
6080     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6081     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6082     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6083     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6084     SmallVector<SDValue, 8> Ops;
6085     for (unsigned i = 0; i < NumElts; ++i) {
6086       if (ShuffleMask[i] < 0)
6087         Ops.push_back(DAG.getUNDEF(EltVT));
6088       else
6089         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6090                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6091                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6092                                                   dl, MVT::i32)));
6093     }
6094     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6095     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6096   }
6097
6098   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6099     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6100
6101   if (VT == MVT::v8i8) {
6102     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6103     if (NewOp.getNode())
6104       return NewOp;
6105   }
6106
6107   return SDValue();
6108 }
6109
6110 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6111   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6112   SDValue Lane = Op.getOperand(2);
6113   if (!isa<ConstantSDNode>(Lane))
6114     return SDValue();
6115
6116   return Op;
6117 }
6118
6119 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6120   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6121   SDValue Lane = Op.getOperand(1);
6122   if (!isa<ConstantSDNode>(Lane))
6123     return SDValue();
6124
6125   SDValue Vec = Op.getOperand(0);
6126   if (Op.getValueType() == MVT::i32 &&
6127       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6128     SDLoc dl(Op);
6129     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6130   }
6131
6132   return Op;
6133 }
6134
6135 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6136   // The only time a CONCAT_VECTORS operation can have legal types is when
6137   // two 64-bit vectors are concatenated to a 128-bit vector.
6138   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6139          "unexpected CONCAT_VECTORS");
6140   SDLoc dl(Op);
6141   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6142   SDValue Op0 = Op.getOperand(0);
6143   SDValue Op1 = Op.getOperand(1);
6144   if (Op0.getOpcode() != ISD::UNDEF)
6145     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6146                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6147                       DAG.getIntPtrConstant(0, dl));
6148   if (Op1.getOpcode() != ISD::UNDEF)
6149     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6150                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6151                       DAG.getIntPtrConstant(1, dl));
6152   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6153 }
6154
6155 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6156 /// element has been zero/sign-extended, depending on the isSigned parameter,
6157 /// from an integer type half its size.
6158 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6159                                    bool isSigned) {
6160   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6161   EVT VT = N->getValueType(0);
6162   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6163     SDNode *BVN = N->getOperand(0).getNode();
6164     if (BVN->getValueType(0) != MVT::v4i32 ||
6165         BVN->getOpcode() != ISD::BUILD_VECTOR)
6166       return false;
6167     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6168     unsigned HiElt = 1 - LoElt;
6169     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6170     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6171     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6172     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6173     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6174       return false;
6175     if (isSigned) {
6176       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6177           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6178         return true;
6179     } else {
6180       if (Hi0->isNullValue() && Hi1->isNullValue())
6181         return true;
6182     }
6183     return false;
6184   }
6185
6186   if (N->getOpcode() != ISD::BUILD_VECTOR)
6187     return false;
6188
6189   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6190     SDNode *Elt = N->getOperand(i).getNode();
6191     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6192       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6193       unsigned HalfSize = EltSize / 2;
6194       if (isSigned) {
6195         if (!isIntN(HalfSize, C->getSExtValue()))
6196           return false;
6197       } else {
6198         if (!isUIntN(HalfSize, C->getZExtValue()))
6199           return false;
6200       }
6201       continue;
6202     }
6203     return false;
6204   }
6205
6206   return true;
6207 }
6208
6209 /// isSignExtended - Check if a node is a vector value that is sign-extended
6210 /// or a constant BUILD_VECTOR with sign-extended elements.
6211 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6212   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6213     return true;
6214   if (isExtendedBUILD_VECTOR(N, DAG, true))
6215     return true;
6216   return false;
6217 }
6218
6219 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6220 /// or a constant BUILD_VECTOR with zero-extended elements.
6221 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6222   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6223     return true;
6224   if (isExtendedBUILD_VECTOR(N, DAG, false))
6225     return true;
6226   return false;
6227 }
6228
6229 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6230   if (OrigVT.getSizeInBits() >= 64)
6231     return OrigVT;
6232
6233   assert(OrigVT.isSimple() && "Expecting a simple value type");
6234
6235   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6236   switch (OrigSimpleTy) {
6237   default: llvm_unreachable("Unexpected Vector Type");
6238   case MVT::v2i8:
6239   case MVT::v2i16:
6240      return MVT::v2i32;
6241   case MVT::v4i8:
6242     return  MVT::v4i16;
6243   }
6244 }
6245
6246 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6247 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6248 /// We insert the required extension here to get the vector to fill a D register.
6249 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6250                                             const EVT &OrigTy,
6251                                             const EVT &ExtTy,
6252                                             unsigned ExtOpcode) {
6253   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6254   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6255   // 64-bits we need to insert a new extension so that it will be 64-bits.
6256   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6257   if (OrigTy.getSizeInBits() >= 64)
6258     return N;
6259
6260   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6261   EVT NewVT = getExtensionTo64Bits(OrigTy);
6262
6263   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6264 }
6265
6266 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6267 /// does not do any sign/zero extension. If the original vector is less
6268 /// than 64 bits, an appropriate extension will be added after the load to
6269 /// reach a total size of 64 bits. We have to add the extension separately
6270 /// because ARM does not have a sign/zero extending load for vectors.
6271 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6272   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6273
6274   // The load already has the right type.
6275   if (ExtendedTy == LD->getMemoryVT())
6276     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6277                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6278                 LD->isNonTemporal(), LD->isInvariant(),
6279                 LD->getAlignment());
6280
6281   // We need to create a zextload/sextload. We cannot just create a load
6282   // followed by a zext/zext node because LowerMUL is also run during normal
6283   // operation legalization where we can't create illegal types.
6284   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6285                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6286                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6287                         LD->isNonTemporal(), LD->getAlignment());
6288 }
6289
6290 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6291 /// extending load, or BUILD_VECTOR with extended elements, return the
6292 /// unextended value. The unextended vector should be 64 bits so that it can
6293 /// be used as an operand to a VMULL instruction. If the original vector size
6294 /// before extension is less than 64 bits we add a an extension to resize
6295 /// the vector to 64 bits.
6296 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6297   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6298     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6299                                         N->getOperand(0)->getValueType(0),
6300                                         N->getValueType(0),
6301                                         N->getOpcode());
6302
6303   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6304     return SkipLoadExtensionForVMULL(LD, DAG);
6305
6306   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6307   // have been legalized as a BITCAST from v4i32.
6308   if (N->getOpcode() == ISD::BITCAST) {
6309     SDNode *BVN = N->getOperand(0).getNode();
6310     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6311            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6312     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6313     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6314                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6315   }
6316   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6317   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6318   EVT VT = N->getValueType(0);
6319   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6320   unsigned NumElts = VT.getVectorNumElements();
6321   MVT TruncVT = MVT::getIntegerVT(EltSize);
6322   SmallVector<SDValue, 8> Ops;
6323   SDLoc dl(N);
6324   for (unsigned i = 0; i != NumElts; ++i) {
6325     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6326     const APInt &CInt = C->getAPIntValue();
6327     // Element types smaller than 32 bits are not legal, so use i32 elements.
6328     // The values are implicitly truncated so sext vs. zext doesn't matter.
6329     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6330   }
6331   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6332                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6333 }
6334
6335 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6336   unsigned Opcode = N->getOpcode();
6337   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6338     SDNode *N0 = N->getOperand(0).getNode();
6339     SDNode *N1 = N->getOperand(1).getNode();
6340     return N0->hasOneUse() && N1->hasOneUse() &&
6341       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6342   }
6343   return false;
6344 }
6345
6346 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6347   unsigned Opcode = N->getOpcode();
6348   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6349     SDNode *N0 = N->getOperand(0).getNode();
6350     SDNode *N1 = N->getOperand(1).getNode();
6351     return N0->hasOneUse() && N1->hasOneUse() &&
6352       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6353   }
6354   return false;
6355 }
6356
6357 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6358   // Multiplications are only custom-lowered for 128-bit vectors so that
6359   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6360   EVT VT = Op.getValueType();
6361   assert(VT.is128BitVector() && VT.isInteger() &&
6362          "unexpected type for custom-lowering ISD::MUL");
6363   SDNode *N0 = Op.getOperand(0).getNode();
6364   SDNode *N1 = Op.getOperand(1).getNode();
6365   unsigned NewOpc = 0;
6366   bool isMLA = false;
6367   bool isN0SExt = isSignExtended(N0, DAG);
6368   bool isN1SExt = isSignExtended(N1, DAG);
6369   if (isN0SExt && isN1SExt)
6370     NewOpc = ARMISD::VMULLs;
6371   else {
6372     bool isN0ZExt = isZeroExtended(N0, DAG);
6373     bool isN1ZExt = isZeroExtended(N1, DAG);
6374     if (isN0ZExt && isN1ZExt)
6375       NewOpc = ARMISD::VMULLu;
6376     else if (isN1SExt || isN1ZExt) {
6377       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6378       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6379       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6380         NewOpc = ARMISD::VMULLs;
6381         isMLA = true;
6382       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6383         NewOpc = ARMISD::VMULLu;
6384         isMLA = true;
6385       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6386         std::swap(N0, N1);
6387         NewOpc = ARMISD::VMULLu;
6388         isMLA = true;
6389       }
6390     }
6391
6392     if (!NewOpc) {
6393       if (VT == MVT::v2i64)
6394         // Fall through to expand this.  It is not legal.
6395         return SDValue();
6396       else
6397         // Other vector multiplications are legal.
6398         return Op;
6399     }
6400   }
6401
6402   // Legalize to a VMULL instruction.
6403   SDLoc DL(Op);
6404   SDValue Op0;
6405   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6406   if (!isMLA) {
6407     Op0 = SkipExtensionForVMULL(N0, DAG);
6408     assert(Op0.getValueType().is64BitVector() &&
6409            Op1.getValueType().is64BitVector() &&
6410            "unexpected types for extended operands to VMULL");
6411     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6412   }
6413
6414   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6415   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6416   //   vmull q0, d4, d6
6417   //   vmlal q0, d5, d6
6418   // is faster than
6419   //   vaddl q0, d4, d5
6420   //   vmovl q1, d6
6421   //   vmul  q0, q0, q1
6422   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6423   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6424   EVT Op1VT = Op1.getValueType();
6425   return DAG.getNode(N0->getOpcode(), DL, VT,
6426                      DAG.getNode(NewOpc, DL, VT,
6427                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6428                      DAG.getNode(NewOpc, DL, VT,
6429                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6430 }
6431
6432 static SDValue
6433 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6434   // Convert to float
6435   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6436   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6437   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6438   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6439   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6440   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6441   // Get reciprocal estimate.
6442   // float4 recip = vrecpeq_f32(yf);
6443   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6444                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6445                    Y);
6446   // Because char has a smaller range than uchar, we can actually get away
6447   // without any newton steps.  This requires that we use a weird bias
6448   // of 0xb000, however (again, this has been exhaustively tested).
6449   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6450   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6451   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6452   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6453   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6454   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6455   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6456   // Convert back to short.
6457   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6458   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6459   return X;
6460 }
6461
6462 static SDValue
6463 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6464   SDValue N2;
6465   // Convert to float.
6466   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6467   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6468   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6469   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6470   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6471   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6472
6473   // Use reciprocal estimate and one refinement step.
6474   // float4 recip = vrecpeq_f32(yf);
6475   // recip *= vrecpsq_f32(yf, recip);
6476   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6477                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6478                    N1);
6479   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6480                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6481                    N1, N2);
6482   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6483   // Because short has a smaller range than ushort, we can actually get away
6484   // with only a single newton step.  This requires that we use a weird bias
6485   // of 89, however (again, this has been exhaustively tested).
6486   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6487   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6488   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6489   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6490   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6491   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6492   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6493   // Convert back to integer and return.
6494   // return vmovn_s32(vcvt_s32_f32(result));
6495   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6496   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6497   return N0;
6498 }
6499
6500 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6501   EVT VT = Op.getValueType();
6502   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6503          "unexpected type for custom-lowering ISD::SDIV");
6504
6505   SDLoc dl(Op);
6506   SDValue N0 = Op.getOperand(0);
6507   SDValue N1 = Op.getOperand(1);
6508   SDValue N2, N3;
6509
6510   if (VT == MVT::v8i8) {
6511     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6512     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6513
6514     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6515                      DAG.getIntPtrConstant(4, dl));
6516     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6517                      DAG.getIntPtrConstant(4, dl));
6518     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6519                      DAG.getIntPtrConstant(0, dl));
6520     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6521                      DAG.getIntPtrConstant(0, dl));
6522
6523     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6524     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6525
6526     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6527     N0 = LowerCONCAT_VECTORS(N0, DAG);
6528
6529     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6530     return N0;
6531   }
6532   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6533 }
6534
6535 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6536   EVT VT = Op.getValueType();
6537   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6538          "unexpected type for custom-lowering ISD::UDIV");
6539
6540   SDLoc dl(Op);
6541   SDValue N0 = Op.getOperand(0);
6542   SDValue N1 = Op.getOperand(1);
6543   SDValue N2, N3;
6544
6545   if (VT == MVT::v8i8) {
6546     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6547     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6548
6549     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6550                      DAG.getIntPtrConstant(4, dl));
6551     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6552                      DAG.getIntPtrConstant(4, dl));
6553     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6554                      DAG.getIntPtrConstant(0, dl));
6555     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6556                      DAG.getIntPtrConstant(0, dl));
6557
6558     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6559     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6560
6561     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6562     N0 = LowerCONCAT_VECTORS(N0, DAG);
6563
6564     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6565                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6566                                      MVT::i32),
6567                      N0);
6568     return N0;
6569   }
6570
6571   // v4i16 sdiv ... Convert to float.
6572   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6573   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6574   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6575   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6576   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6577   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6578
6579   // Use reciprocal estimate and two refinement steps.
6580   // float4 recip = vrecpeq_f32(yf);
6581   // recip *= vrecpsq_f32(yf, recip);
6582   // recip *= vrecpsq_f32(yf, recip);
6583   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6584                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6585                    BN1);
6586   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6587                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6588                    BN1, N2);
6589   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6590   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6591                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6592                    BN1, N2);
6593   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6594   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6595   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6596   // and that it will never cause us to return an answer too large).
6597   // float4 result = as_float4(as_int4(xf*recip) + 2);
6598   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6599   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6600   N1 = DAG.getConstant(2, dl, MVT::i32);
6601   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6602   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6603   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6604   // Convert back to integer and return.
6605   // return vmovn_u32(vcvt_s32_f32(result));
6606   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6607   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6608   return N0;
6609 }
6610
6611 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6612   EVT VT = Op.getNode()->getValueType(0);
6613   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6614
6615   unsigned Opc;
6616   bool ExtraOp = false;
6617   switch (Op.getOpcode()) {
6618   default: llvm_unreachable("Invalid code");
6619   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6620   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6621   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6622   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6623   }
6624
6625   if (!ExtraOp)
6626     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6627                        Op.getOperand(1));
6628   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6629                      Op.getOperand(1), Op.getOperand(2));
6630 }
6631
6632 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6633   assert(Subtarget->isTargetDarwin());
6634
6635   // For iOS, we want to call an alternative entry point: __sincos_stret,
6636   // return values are passed via sret.
6637   SDLoc dl(Op);
6638   SDValue Arg = Op.getOperand(0);
6639   EVT ArgVT = Arg.getValueType();
6640   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6641   auto PtrVT = getPointerTy(DAG.getDataLayout());
6642
6643   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6644
6645   // Pair of floats / doubles used to pass the result.
6646   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6647
6648   // Create stack object for sret.
6649   auto &DL = DAG.getDataLayout();
6650   const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6651   const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6652   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6653   SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6654
6655   ArgListTy Args;
6656   ArgListEntry Entry;
6657
6658   Entry.Node = SRet;
6659   Entry.Ty = RetTy->getPointerTo();
6660   Entry.isSExt = false;
6661   Entry.isZExt = false;
6662   Entry.isSRet = true;
6663   Args.push_back(Entry);
6664
6665   Entry.Node = Arg;
6666   Entry.Ty = ArgTy;
6667   Entry.isSExt = false;
6668   Entry.isZExt = false;
6669   Args.push_back(Entry);
6670
6671   const char *LibcallName  = (ArgVT == MVT::f64)
6672   ? "__sincos_stret" : "__sincosf_stret";
6673   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6674
6675   TargetLowering::CallLoweringInfo CLI(DAG);
6676   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6677     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6678                std::move(Args), 0)
6679     .setDiscardResult();
6680
6681   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6682
6683   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6684                                 MachinePointerInfo(), false, false, false, 0);
6685
6686   // Address of cos field.
6687   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6688                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6689   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6690                                 MachinePointerInfo(), false, false, false, 0);
6691
6692   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6693   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6694                      LoadSin.getValue(0), LoadCos.getValue(0));
6695 }
6696
6697 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6698   // Monotonic load/store is legal for all targets
6699   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6700     return Op;
6701
6702   // Acquire/Release load/store is not legal for targets without a
6703   // dmb or equivalent available.
6704   return SDValue();
6705 }
6706
6707 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6708                                     SmallVectorImpl<SDValue> &Results,
6709                                     SelectionDAG &DAG,
6710                                     const ARMSubtarget *Subtarget) {
6711   SDLoc DL(N);
6712   SDValue Cycles32, OutChain;
6713
6714   if (Subtarget->hasPerfMon()) {
6715     // Under Power Management extensions, the cycle-count is:
6716     //    mrc p15, #0, <Rt>, c9, c13, #0
6717     SDValue Ops[] = { N->getOperand(0), // Chain
6718                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6719                       DAG.getConstant(15, DL, MVT::i32),
6720                       DAG.getConstant(0, DL, MVT::i32),
6721                       DAG.getConstant(9, DL, MVT::i32),
6722                       DAG.getConstant(13, DL, MVT::i32),
6723                       DAG.getConstant(0, DL, MVT::i32)
6724     };
6725
6726     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6727                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6728     OutChain = Cycles32.getValue(1);
6729   } else {
6730     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6731     // there are older ARM CPUs that have implementation-specific ways of
6732     // obtaining this information (FIXME!).
6733     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6734     OutChain = DAG.getEntryNode();
6735   }
6736
6737
6738   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6739                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6740   Results.push_back(Cycles64);
6741   Results.push_back(OutChain);
6742 }
6743
6744 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6745   switch (Op.getOpcode()) {
6746   default: llvm_unreachable("Don't know how to custom lower this!");
6747   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6748   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6749   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6750   case ISD::GlobalAddress:
6751     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6752     default: llvm_unreachable("unknown object format");
6753     case Triple::COFF:
6754       return LowerGlobalAddressWindows(Op, DAG);
6755     case Triple::ELF:
6756       return LowerGlobalAddressELF(Op, DAG);
6757     case Triple::MachO:
6758       return LowerGlobalAddressDarwin(Op, DAG);
6759     }
6760   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6761   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6762   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6763   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6764   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6765   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6766   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6767   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6768   case ISD::SINT_TO_FP:
6769   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6770   case ISD::FP_TO_SINT:
6771   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6772   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6773   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6774   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6775   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6776   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6777   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6778   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6779   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6780                                                                Subtarget);
6781   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6782   case ISD::SHL:
6783   case ISD::SRL:
6784   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6785   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6786   case ISD::SRL_PARTS:
6787   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6788   case ISD::CTTZ:
6789   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6790   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6791   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6792   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6793   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6794   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6795   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6796   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6797   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6798   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6799   case ISD::MUL:           return LowerMUL(Op, DAG);
6800   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6801   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6802   case ISD::ADDC:
6803   case ISD::ADDE:
6804   case ISD::SUBC:
6805   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6806   case ISD::SADDO:
6807   case ISD::UADDO:
6808   case ISD::SSUBO:
6809   case ISD::USUBO:
6810     return LowerXALUO(Op, DAG);
6811   case ISD::ATOMIC_LOAD:
6812   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6813   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6814   case ISD::SDIVREM:
6815   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6816   case ISD::DYNAMIC_STACKALLOC:
6817     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6818       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6819     llvm_unreachable("Don't know how to custom lower this!");
6820   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6821   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6822   }
6823 }
6824
6825 /// ReplaceNodeResults - Replace the results of node with an illegal result
6826 /// type with new values built out of custom code.
6827 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6828                                            SmallVectorImpl<SDValue>&Results,
6829                                            SelectionDAG &DAG) const {
6830   SDValue Res;
6831   switch (N->getOpcode()) {
6832   default:
6833     llvm_unreachable("Don't know how to custom expand this!");
6834   case ISD::READ_REGISTER:
6835     ExpandREAD_REGISTER(N, Results, DAG);
6836     break;
6837   case ISD::BITCAST:
6838     Res = ExpandBITCAST(N, DAG);
6839     break;
6840   case ISD::SRL:
6841   case ISD::SRA:
6842     Res = Expand64BitShift(N, DAG, Subtarget);
6843     break;
6844   case ISD::READCYCLECOUNTER:
6845     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6846     return;
6847   }
6848   if (Res.getNode())
6849     Results.push_back(Res);
6850 }
6851
6852 //===----------------------------------------------------------------------===//
6853 //                           ARM Scheduler Hooks
6854 //===----------------------------------------------------------------------===//
6855
6856 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6857 /// registers the function context.
6858 void ARMTargetLowering::
6859 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6860                        MachineBasicBlock *DispatchBB, int FI) const {
6861   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6862   DebugLoc dl = MI->getDebugLoc();
6863   MachineFunction *MF = MBB->getParent();
6864   MachineRegisterInfo *MRI = &MF->getRegInfo();
6865   MachineConstantPool *MCP = MF->getConstantPool();
6866   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6867   const Function *F = MF->getFunction();
6868
6869   bool isThumb = Subtarget->isThumb();
6870   bool isThumb2 = Subtarget->isThumb2();
6871
6872   unsigned PCLabelId = AFI->createPICLabelUId();
6873   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6874   ARMConstantPoolValue *CPV =
6875     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6876   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6877
6878   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6879                                            : &ARM::GPRRegClass;
6880
6881   // Grab constant pool and fixed stack memory operands.
6882   MachineMemOperand *CPMMO =
6883     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6884                              MachineMemOperand::MOLoad, 4, 4);
6885
6886   MachineMemOperand *FIMMOSt =
6887     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6888                              MachineMemOperand::MOStore, 4, 4);
6889
6890   // Load the address of the dispatch MBB into the jump buffer.
6891   if (isThumb2) {
6892     // Incoming value: jbuf
6893     //   ldr.n  r5, LCPI1_1
6894     //   orr    r5, r5, #1
6895     //   add    r5, pc
6896     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6897     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6898     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6899                    .addConstantPoolIndex(CPI)
6900                    .addMemOperand(CPMMO));
6901     // Set the low bit because of thumb mode.
6902     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6903     AddDefaultCC(
6904       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6905                      .addReg(NewVReg1, RegState::Kill)
6906                      .addImm(0x01)));
6907     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6908     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6909       .addReg(NewVReg2, RegState::Kill)
6910       .addImm(PCLabelId);
6911     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6912                    .addReg(NewVReg3, RegState::Kill)
6913                    .addFrameIndex(FI)
6914                    .addImm(36)  // &jbuf[1] :: pc
6915                    .addMemOperand(FIMMOSt));
6916   } else if (isThumb) {
6917     // Incoming value: jbuf
6918     //   ldr.n  r1, LCPI1_4
6919     //   add    r1, pc
6920     //   mov    r2, #1
6921     //   orrs   r1, r2
6922     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6923     //   str    r1, [r2]
6924     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6925     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6926                    .addConstantPoolIndex(CPI)
6927                    .addMemOperand(CPMMO));
6928     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6929     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6930       .addReg(NewVReg1, RegState::Kill)
6931       .addImm(PCLabelId);
6932     // Set the low bit because of thumb mode.
6933     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6934     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6935                    .addReg(ARM::CPSR, RegState::Define)
6936                    .addImm(1));
6937     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6938     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6939                    .addReg(ARM::CPSR, RegState::Define)
6940                    .addReg(NewVReg2, RegState::Kill)
6941                    .addReg(NewVReg3, RegState::Kill));
6942     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6943     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6944             .addFrameIndex(FI)
6945             .addImm(36); // &jbuf[1] :: pc
6946     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6947                    .addReg(NewVReg4, RegState::Kill)
6948                    .addReg(NewVReg5, RegState::Kill)
6949                    .addImm(0)
6950                    .addMemOperand(FIMMOSt));
6951   } else {
6952     // Incoming value: jbuf
6953     //   ldr  r1, LCPI1_1
6954     //   add  r1, pc, r1
6955     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6956     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6957     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6958                    .addConstantPoolIndex(CPI)
6959                    .addImm(0)
6960                    .addMemOperand(CPMMO));
6961     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6962     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6963                    .addReg(NewVReg1, RegState::Kill)
6964                    .addImm(PCLabelId));
6965     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6966                    .addReg(NewVReg2, RegState::Kill)
6967                    .addFrameIndex(FI)
6968                    .addImm(36)  // &jbuf[1] :: pc
6969                    .addMemOperand(FIMMOSt));
6970   }
6971 }
6972
6973 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6974                                               MachineBasicBlock *MBB) const {
6975   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6976   DebugLoc dl = MI->getDebugLoc();
6977   MachineFunction *MF = MBB->getParent();
6978   MachineRegisterInfo *MRI = &MF->getRegInfo();
6979   MachineFrameInfo *MFI = MF->getFrameInfo();
6980   int FI = MFI->getFunctionContextIndex();
6981
6982   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6983                                                         : &ARM::GPRnopcRegClass;
6984
6985   // Get a mapping of the call site numbers to all of the landing pads they're
6986   // associated with.
6987   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6988   unsigned MaxCSNum = 0;
6989   MachineModuleInfo &MMI = MF->getMMI();
6990   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6991        ++BB) {
6992     if (!BB->isLandingPad()) continue;
6993
6994     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6995     // pad.
6996     for (MachineBasicBlock::iterator
6997            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6998       if (!II->isEHLabel()) continue;
6999
7000       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7001       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7002
7003       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7004       for (SmallVectorImpl<unsigned>::iterator
7005              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7006            CSI != CSE; ++CSI) {
7007         CallSiteNumToLPad[*CSI].push_back(BB);
7008         MaxCSNum = std::max(MaxCSNum, *CSI);
7009       }
7010       break;
7011     }
7012   }
7013
7014   // Get an ordered list of the machine basic blocks for the jump table.
7015   std::vector<MachineBasicBlock*> LPadList;
7016   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7017   LPadList.reserve(CallSiteNumToLPad.size());
7018   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7019     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7020     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7021            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7022       LPadList.push_back(*II);
7023       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7024     }
7025   }
7026
7027   assert(!LPadList.empty() &&
7028          "No landing pad destinations for the dispatch jump table!");
7029
7030   // Create the jump table and associated information.
7031   MachineJumpTableInfo *JTI =
7032     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7033   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7034   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7035
7036   // Create the MBBs for the dispatch code.
7037
7038   // Shove the dispatch's address into the return slot in the function context.
7039   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7040   DispatchBB->setIsLandingPad();
7041
7042   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7043   unsigned trap_opcode;
7044   if (Subtarget->isThumb())
7045     trap_opcode = ARM::tTRAP;
7046   else
7047     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7048
7049   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7050   DispatchBB->addSuccessor(TrapBB);
7051
7052   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7053   DispatchBB->addSuccessor(DispContBB);
7054
7055   // Insert and MBBs.
7056   MF->insert(MF->end(), DispatchBB);
7057   MF->insert(MF->end(), DispContBB);
7058   MF->insert(MF->end(), TrapBB);
7059
7060   // Insert code into the entry block that creates and registers the function
7061   // context.
7062   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7063
7064   MachineMemOperand *FIMMOLd =
7065     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
7066                              MachineMemOperand::MOLoad |
7067                              MachineMemOperand::MOVolatile, 4, 4);
7068
7069   MachineInstrBuilder MIB;
7070   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7071
7072   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7073   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7074
7075   // Add a register mask with no preserved registers.  This results in all
7076   // registers being marked as clobbered.
7077   MIB.addRegMask(RI.getNoPreservedMask());
7078
7079   unsigned NumLPads = LPadList.size();
7080   if (Subtarget->isThumb2()) {
7081     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7082     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7083                    .addFrameIndex(FI)
7084                    .addImm(4)
7085                    .addMemOperand(FIMMOLd));
7086
7087     if (NumLPads < 256) {
7088       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7089                      .addReg(NewVReg1)
7090                      .addImm(LPadList.size()));
7091     } else {
7092       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7093       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7094                      .addImm(NumLPads & 0xFFFF));
7095
7096       unsigned VReg2 = VReg1;
7097       if ((NumLPads & 0xFFFF0000) != 0) {
7098         VReg2 = MRI->createVirtualRegister(TRC);
7099         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7100                        .addReg(VReg1)
7101                        .addImm(NumLPads >> 16));
7102       }
7103
7104       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7105                      .addReg(NewVReg1)
7106                      .addReg(VReg2));
7107     }
7108
7109     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7110       .addMBB(TrapBB)
7111       .addImm(ARMCC::HI)
7112       .addReg(ARM::CPSR);
7113
7114     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7115     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7116                    .addJumpTableIndex(MJTI));
7117
7118     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7119     AddDefaultCC(
7120       AddDefaultPred(
7121         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7122         .addReg(NewVReg3, RegState::Kill)
7123         .addReg(NewVReg1)
7124         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7125
7126     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7127       .addReg(NewVReg4, RegState::Kill)
7128       .addReg(NewVReg1)
7129       .addJumpTableIndex(MJTI);
7130   } else if (Subtarget->isThumb()) {
7131     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7132     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7133                    .addFrameIndex(FI)
7134                    .addImm(1)
7135                    .addMemOperand(FIMMOLd));
7136
7137     if (NumLPads < 256) {
7138       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7139                      .addReg(NewVReg1)
7140                      .addImm(NumLPads));
7141     } else {
7142       MachineConstantPool *ConstantPool = MF->getConstantPool();
7143       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7144       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7145
7146       // MachineConstantPool wants an explicit alignment.
7147       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7148       if (Align == 0)
7149         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7150       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7151
7152       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7153       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7154                      .addReg(VReg1, RegState::Define)
7155                      .addConstantPoolIndex(Idx));
7156       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7157                      .addReg(NewVReg1)
7158                      .addReg(VReg1));
7159     }
7160
7161     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7162       .addMBB(TrapBB)
7163       .addImm(ARMCC::HI)
7164       .addReg(ARM::CPSR);
7165
7166     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7167     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7168                    .addReg(ARM::CPSR, RegState::Define)
7169                    .addReg(NewVReg1)
7170                    .addImm(2));
7171
7172     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7173     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7174                    .addJumpTableIndex(MJTI));
7175
7176     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7177     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7178                    .addReg(ARM::CPSR, RegState::Define)
7179                    .addReg(NewVReg2, RegState::Kill)
7180                    .addReg(NewVReg3));
7181
7182     MachineMemOperand *JTMMOLd =
7183       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7184                                MachineMemOperand::MOLoad, 4, 4);
7185
7186     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7187     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7188                    .addReg(NewVReg4, RegState::Kill)
7189                    .addImm(0)
7190                    .addMemOperand(JTMMOLd));
7191
7192     unsigned NewVReg6 = NewVReg5;
7193     if (RelocM == Reloc::PIC_) {
7194       NewVReg6 = MRI->createVirtualRegister(TRC);
7195       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7196                      .addReg(ARM::CPSR, RegState::Define)
7197                      .addReg(NewVReg5, RegState::Kill)
7198                      .addReg(NewVReg3));
7199     }
7200
7201     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7202       .addReg(NewVReg6, RegState::Kill)
7203       .addJumpTableIndex(MJTI);
7204   } else {
7205     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7206     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7207                    .addFrameIndex(FI)
7208                    .addImm(4)
7209                    .addMemOperand(FIMMOLd));
7210
7211     if (NumLPads < 256) {
7212       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7213                      .addReg(NewVReg1)
7214                      .addImm(NumLPads));
7215     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7216       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7217       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7218                      .addImm(NumLPads & 0xFFFF));
7219
7220       unsigned VReg2 = VReg1;
7221       if ((NumLPads & 0xFFFF0000) != 0) {
7222         VReg2 = MRI->createVirtualRegister(TRC);
7223         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7224                        .addReg(VReg1)
7225                        .addImm(NumLPads >> 16));
7226       }
7227
7228       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7229                      .addReg(NewVReg1)
7230                      .addReg(VReg2));
7231     } else {
7232       MachineConstantPool *ConstantPool = MF->getConstantPool();
7233       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7234       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7235
7236       // MachineConstantPool wants an explicit alignment.
7237       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7238       if (Align == 0)
7239         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7240       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7241
7242       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7243       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7244                      .addReg(VReg1, RegState::Define)
7245                      .addConstantPoolIndex(Idx)
7246                      .addImm(0));
7247       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7248                      .addReg(NewVReg1)
7249                      .addReg(VReg1, RegState::Kill));
7250     }
7251
7252     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7253       .addMBB(TrapBB)
7254       .addImm(ARMCC::HI)
7255       .addReg(ARM::CPSR);
7256
7257     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7258     AddDefaultCC(
7259       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7260                      .addReg(NewVReg1)
7261                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7262     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7263     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7264                    .addJumpTableIndex(MJTI));
7265
7266     MachineMemOperand *JTMMOLd =
7267       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7268                                MachineMemOperand::MOLoad, 4, 4);
7269     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7270     AddDefaultPred(
7271       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7272       .addReg(NewVReg3, RegState::Kill)
7273       .addReg(NewVReg4)
7274       .addImm(0)
7275       .addMemOperand(JTMMOLd));
7276
7277     if (RelocM == Reloc::PIC_) {
7278       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7279         .addReg(NewVReg5, RegState::Kill)
7280         .addReg(NewVReg4)
7281         .addJumpTableIndex(MJTI);
7282     } else {
7283       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7284         .addReg(NewVReg5, RegState::Kill)
7285         .addJumpTableIndex(MJTI);
7286     }
7287   }
7288
7289   // Add the jump table entries as successors to the MBB.
7290   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7291   for (std::vector<MachineBasicBlock*>::iterator
7292          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7293     MachineBasicBlock *CurMBB = *I;
7294     if (SeenMBBs.insert(CurMBB).second)
7295       DispContBB->addSuccessor(CurMBB);
7296   }
7297
7298   // N.B. the order the invoke BBs are processed in doesn't matter here.
7299   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7300   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7301   for (MachineBasicBlock *BB : InvokeBBs) {
7302
7303     // Remove the landing pad successor from the invoke block and replace it
7304     // with the new dispatch block.
7305     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7306                                                   BB->succ_end());
7307     while (!Successors.empty()) {
7308       MachineBasicBlock *SMBB = Successors.pop_back_val();
7309       if (SMBB->isLandingPad()) {
7310         BB->removeSuccessor(SMBB);
7311         MBBLPads.push_back(SMBB);
7312       }
7313     }
7314
7315     BB->addSuccessor(DispatchBB);
7316
7317     // Find the invoke call and mark all of the callee-saved registers as
7318     // 'implicit defined' so that they're spilled. This prevents code from
7319     // moving instructions to before the EH block, where they will never be
7320     // executed.
7321     for (MachineBasicBlock::reverse_iterator
7322            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7323       if (!II->isCall()) continue;
7324
7325       DenseMap<unsigned, bool> DefRegs;
7326       for (MachineInstr::mop_iterator
7327              OI = II->operands_begin(), OE = II->operands_end();
7328            OI != OE; ++OI) {
7329         if (!OI->isReg()) continue;
7330         DefRegs[OI->getReg()] = true;
7331       }
7332
7333       MachineInstrBuilder MIB(*MF, &*II);
7334
7335       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7336         unsigned Reg = SavedRegs[i];
7337         if (Subtarget->isThumb2() &&
7338             !ARM::tGPRRegClass.contains(Reg) &&
7339             !ARM::hGPRRegClass.contains(Reg))
7340           continue;
7341         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7342           continue;
7343         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7344           continue;
7345         if (!DefRegs[Reg])
7346           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7347       }
7348
7349       break;
7350     }
7351   }
7352
7353   // Mark all former landing pads as non-landing pads. The dispatch is the only
7354   // landing pad now.
7355   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7356          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7357     (*I)->setIsLandingPad(false);
7358
7359   // The instruction is gone now.
7360   MI->eraseFromParent();
7361 }
7362
7363 static
7364 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7365   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7366        E = MBB->succ_end(); I != E; ++I)
7367     if (*I != Succ)
7368       return *I;
7369   llvm_unreachable("Expecting a BB with two successors!");
7370 }
7371
7372 /// Return the load opcode for a given load size. If load size >= 8,
7373 /// neon opcode will be returned.
7374 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7375   if (LdSize >= 8)
7376     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7377                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7378   if (IsThumb1)
7379     return LdSize == 4 ? ARM::tLDRi
7380                        : LdSize == 2 ? ARM::tLDRHi
7381                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7382   if (IsThumb2)
7383     return LdSize == 4 ? ARM::t2LDR_POST
7384                        : LdSize == 2 ? ARM::t2LDRH_POST
7385                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7386   return LdSize == 4 ? ARM::LDR_POST_IMM
7387                      : LdSize == 2 ? ARM::LDRH_POST
7388                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7389 }
7390
7391 /// Return the store opcode for a given store size. If store size >= 8,
7392 /// neon opcode will be returned.
7393 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7394   if (StSize >= 8)
7395     return StSize == 16 ? ARM::VST1q32wb_fixed
7396                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7397   if (IsThumb1)
7398     return StSize == 4 ? ARM::tSTRi
7399                        : StSize == 2 ? ARM::tSTRHi
7400                                      : StSize == 1 ? ARM::tSTRBi : 0;
7401   if (IsThumb2)
7402     return StSize == 4 ? ARM::t2STR_POST
7403                        : StSize == 2 ? ARM::t2STRH_POST
7404                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7405   return StSize == 4 ? ARM::STR_POST_IMM
7406                      : StSize == 2 ? ARM::STRH_POST
7407                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7408 }
7409
7410 /// Emit a post-increment load operation with given size. The instructions
7411 /// will be added to BB at Pos.
7412 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7413                        const TargetInstrInfo *TII, DebugLoc dl,
7414                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7415                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7416   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7417   assert(LdOpc != 0 && "Should have a load opcode");
7418   if (LdSize >= 8) {
7419     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7420                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7421                        .addImm(0));
7422   } else if (IsThumb1) {
7423     // load + update AddrIn
7424     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7425                        .addReg(AddrIn).addImm(0));
7426     MachineInstrBuilder MIB =
7427         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7428     MIB = AddDefaultT1CC(MIB);
7429     MIB.addReg(AddrIn).addImm(LdSize);
7430     AddDefaultPred(MIB);
7431   } else if (IsThumb2) {
7432     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7433                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7434                        .addImm(LdSize));
7435   } else { // arm
7436     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7437                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7438                        .addReg(0).addImm(LdSize));
7439   }
7440 }
7441
7442 /// Emit a post-increment store operation with given size. The instructions
7443 /// will be added to BB at Pos.
7444 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7445                        const TargetInstrInfo *TII, DebugLoc dl,
7446                        unsigned StSize, unsigned Data, unsigned AddrIn,
7447                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7448   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7449   assert(StOpc != 0 && "Should have a store opcode");
7450   if (StSize >= 8) {
7451     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7452                        .addReg(AddrIn).addImm(0).addReg(Data));
7453   } else if (IsThumb1) {
7454     // store + update AddrIn
7455     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7456                        .addReg(AddrIn).addImm(0));
7457     MachineInstrBuilder MIB =
7458         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7459     MIB = AddDefaultT1CC(MIB);
7460     MIB.addReg(AddrIn).addImm(StSize);
7461     AddDefaultPred(MIB);
7462   } else if (IsThumb2) {
7463     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7464                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7465   } else { // arm
7466     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7467                        .addReg(Data).addReg(AddrIn).addReg(0)
7468                        .addImm(StSize));
7469   }
7470 }
7471
7472 MachineBasicBlock *
7473 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7474                                    MachineBasicBlock *BB) const {
7475   // This pseudo instruction has 3 operands: dst, src, size
7476   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7477   // Otherwise, we will generate unrolled scalar copies.
7478   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7479   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7480   MachineFunction::iterator It = BB;
7481   ++It;
7482
7483   unsigned dest = MI->getOperand(0).getReg();
7484   unsigned src = MI->getOperand(1).getReg();
7485   unsigned SizeVal = MI->getOperand(2).getImm();
7486   unsigned Align = MI->getOperand(3).getImm();
7487   DebugLoc dl = MI->getDebugLoc();
7488
7489   MachineFunction *MF = BB->getParent();
7490   MachineRegisterInfo &MRI = MF->getRegInfo();
7491   unsigned UnitSize = 0;
7492   const TargetRegisterClass *TRC = nullptr;
7493   const TargetRegisterClass *VecTRC = nullptr;
7494
7495   bool IsThumb1 = Subtarget->isThumb1Only();
7496   bool IsThumb2 = Subtarget->isThumb2();
7497
7498   if (Align & 1) {
7499     UnitSize = 1;
7500   } else if (Align & 2) {
7501     UnitSize = 2;
7502   } else {
7503     // Check whether we can use NEON instructions.
7504     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7505         Subtarget->hasNEON()) {
7506       if ((Align % 16 == 0) && SizeVal >= 16)
7507         UnitSize = 16;
7508       else if ((Align % 8 == 0) && SizeVal >= 8)
7509         UnitSize = 8;
7510     }
7511     // Can't use NEON instructions.
7512     if (UnitSize == 0)
7513       UnitSize = 4;
7514   }
7515
7516   // Select the correct opcode and register class for unit size load/store
7517   bool IsNeon = UnitSize >= 8;
7518   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7519   if (IsNeon)
7520     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7521                             : UnitSize == 8 ? &ARM::DPRRegClass
7522                                             : nullptr;
7523
7524   unsigned BytesLeft = SizeVal % UnitSize;
7525   unsigned LoopSize = SizeVal - BytesLeft;
7526
7527   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7528     // Use LDR and STR to copy.
7529     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7530     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7531     unsigned srcIn = src;
7532     unsigned destIn = dest;
7533     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7534       unsigned srcOut = MRI.createVirtualRegister(TRC);
7535       unsigned destOut = MRI.createVirtualRegister(TRC);
7536       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7537       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7538                  IsThumb1, IsThumb2);
7539       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7540                  IsThumb1, IsThumb2);
7541       srcIn = srcOut;
7542       destIn = destOut;
7543     }
7544
7545     // Handle the leftover bytes with LDRB and STRB.
7546     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7547     // [destOut] = STRB_POST(scratch, destIn, 1)
7548     for (unsigned i = 0; i < BytesLeft; i++) {
7549       unsigned srcOut = MRI.createVirtualRegister(TRC);
7550       unsigned destOut = MRI.createVirtualRegister(TRC);
7551       unsigned scratch = MRI.createVirtualRegister(TRC);
7552       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7553                  IsThumb1, IsThumb2);
7554       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7555                  IsThumb1, IsThumb2);
7556       srcIn = srcOut;
7557       destIn = destOut;
7558     }
7559     MI->eraseFromParent();   // The instruction is gone now.
7560     return BB;
7561   }
7562
7563   // Expand the pseudo op to a loop.
7564   // thisMBB:
7565   //   ...
7566   //   movw varEnd, # --> with thumb2
7567   //   movt varEnd, #
7568   //   ldrcp varEnd, idx --> without thumb2
7569   //   fallthrough --> loopMBB
7570   // loopMBB:
7571   //   PHI varPhi, varEnd, varLoop
7572   //   PHI srcPhi, src, srcLoop
7573   //   PHI destPhi, dst, destLoop
7574   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7575   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7576   //   subs varLoop, varPhi, #UnitSize
7577   //   bne loopMBB
7578   //   fallthrough --> exitMBB
7579   // exitMBB:
7580   //   epilogue to handle left-over bytes
7581   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7582   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7583   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7584   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7585   MF->insert(It, loopMBB);
7586   MF->insert(It, exitMBB);
7587
7588   // Transfer the remainder of BB and its successor edges to exitMBB.
7589   exitMBB->splice(exitMBB->begin(), BB,
7590                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7591   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7592
7593   // Load an immediate to varEnd.
7594   unsigned varEnd = MRI.createVirtualRegister(TRC);
7595   if (Subtarget->useMovt(*MF)) {
7596     unsigned Vtmp = varEnd;
7597     if ((LoopSize & 0xFFFF0000) != 0)
7598       Vtmp = MRI.createVirtualRegister(TRC);
7599     AddDefaultPred(BuildMI(BB, dl,
7600                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7601                            Vtmp).addImm(LoopSize & 0xFFFF));
7602
7603     if ((LoopSize & 0xFFFF0000) != 0)
7604       AddDefaultPred(BuildMI(BB, dl,
7605                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7606                              varEnd)
7607                          .addReg(Vtmp)
7608                          .addImm(LoopSize >> 16));
7609   } else {
7610     MachineConstantPool *ConstantPool = MF->getConstantPool();
7611     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7612     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7613
7614     // MachineConstantPool wants an explicit alignment.
7615     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7616     if (Align == 0)
7617       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7618     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7619
7620     if (IsThumb1)
7621       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7622           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7623     else
7624       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7625           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7626   }
7627   BB->addSuccessor(loopMBB);
7628
7629   // Generate the loop body:
7630   //   varPhi = PHI(varLoop, varEnd)
7631   //   srcPhi = PHI(srcLoop, src)
7632   //   destPhi = PHI(destLoop, dst)
7633   MachineBasicBlock *entryBB = BB;
7634   BB = loopMBB;
7635   unsigned varLoop = MRI.createVirtualRegister(TRC);
7636   unsigned varPhi = MRI.createVirtualRegister(TRC);
7637   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7638   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7639   unsigned destLoop = MRI.createVirtualRegister(TRC);
7640   unsigned destPhi = MRI.createVirtualRegister(TRC);
7641
7642   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7643     .addReg(varLoop).addMBB(loopMBB)
7644     .addReg(varEnd).addMBB(entryBB);
7645   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7646     .addReg(srcLoop).addMBB(loopMBB)
7647     .addReg(src).addMBB(entryBB);
7648   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7649     .addReg(destLoop).addMBB(loopMBB)
7650     .addReg(dest).addMBB(entryBB);
7651
7652   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7653   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7654   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7655   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7656              IsThumb1, IsThumb2);
7657   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7658              IsThumb1, IsThumb2);
7659
7660   // Decrement loop variable by UnitSize.
7661   if (IsThumb1) {
7662     MachineInstrBuilder MIB =
7663         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7664     MIB = AddDefaultT1CC(MIB);
7665     MIB.addReg(varPhi).addImm(UnitSize);
7666     AddDefaultPred(MIB);
7667   } else {
7668     MachineInstrBuilder MIB =
7669         BuildMI(*BB, BB->end(), dl,
7670                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7671     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7672     MIB->getOperand(5).setReg(ARM::CPSR);
7673     MIB->getOperand(5).setIsDef(true);
7674   }
7675   BuildMI(*BB, BB->end(), dl,
7676           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7677       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7678
7679   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7680   BB->addSuccessor(loopMBB);
7681   BB->addSuccessor(exitMBB);
7682
7683   // Add epilogue to handle BytesLeft.
7684   BB = exitMBB;
7685   MachineInstr *StartOfExit = exitMBB->begin();
7686
7687   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7688   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7689   unsigned srcIn = srcLoop;
7690   unsigned destIn = destLoop;
7691   for (unsigned i = 0; i < BytesLeft; i++) {
7692     unsigned srcOut = MRI.createVirtualRegister(TRC);
7693     unsigned destOut = MRI.createVirtualRegister(TRC);
7694     unsigned scratch = MRI.createVirtualRegister(TRC);
7695     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7696                IsThumb1, IsThumb2);
7697     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7698                IsThumb1, IsThumb2);
7699     srcIn = srcOut;
7700     destIn = destOut;
7701   }
7702
7703   MI->eraseFromParent();   // The instruction is gone now.
7704   return BB;
7705 }
7706
7707 MachineBasicBlock *
7708 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7709                                        MachineBasicBlock *MBB) const {
7710   const TargetMachine &TM = getTargetMachine();
7711   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7712   DebugLoc DL = MI->getDebugLoc();
7713
7714   assert(Subtarget->isTargetWindows() &&
7715          "__chkstk is only supported on Windows");
7716   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7717
7718   // __chkstk takes the number of words to allocate on the stack in R4, and
7719   // returns the stack adjustment in number of bytes in R4.  This will not
7720   // clober any other registers (other than the obvious lr).
7721   //
7722   // Although, technically, IP should be considered a register which may be
7723   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7724   // thumb-2 environment, so there is no interworking required.  As a result, we
7725   // do not expect a veneer to be emitted by the linker, clobbering IP.
7726   //
7727   // Each module receives its own copy of __chkstk, so no import thunk is
7728   // required, again, ensuring that IP is not clobbered.
7729   //
7730   // Finally, although some linkers may theoretically provide a trampoline for
7731   // out of range calls (which is quite common due to a 32M range limitation of
7732   // branches for Thumb), we can generate the long-call version via
7733   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7734   // IP.
7735
7736   switch (TM.getCodeModel()) {
7737   case CodeModel::Small:
7738   case CodeModel::Medium:
7739   case CodeModel::Default:
7740   case CodeModel::Kernel:
7741     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7742       .addImm((unsigned)ARMCC::AL).addReg(0)
7743       .addExternalSymbol("__chkstk")
7744       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7745       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7746       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7747     break;
7748   case CodeModel::Large:
7749   case CodeModel::JITDefault: {
7750     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7751     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7752
7753     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7754       .addExternalSymbol("__chkstk");
7755     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7756       .addImm((unsigned)ARMCC::AL).addReg(0)
7757       .addReg(Reg, RegState::Kill)
7758       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7759       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7760       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7761     break;
7762   }
7763   }
7764
7765   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7766                                       ARM::SP)
7767                               .addReg(ARM::SP).addReg(ARM::R4)));
7768
7769   MI->eraseFromParent();
7770   return MBB;
7771 }
7772
7773 MachineBasicBlock *
7774 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7775                                                MachineBasicBlock *BB) const {
7776   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7777   DebugLoc dl = MI->getDebugLoc();
7778   bool isThumb2 = Subtarget->isThumb2();
7779   switch (MI->getOpcode()) {
7780   default: {
7781     MI->dump();
7782     llvm_unreachable("Unexpected instr type to insert");
7783   }
7784   // The Thumb2 pre-indexed stores have the same MI operands, they just
7785   // define them differently in the .td files from the isel patterns, so
7786   // they need pseudos.
7787   case ARM::t2STR_preidx:
7788     MI->setDesc(TII->get(ARM::t2STR_PRE));
7789     return BB;
7790   case ARM::t2STRB_preidx:
7791     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7792     return BB;
7793   case ARM::t2STRH_preidx:
7794     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7795     return BB;
7796
7797   case ARM::STRi_preidx:
7798   case ARM::STRBi_preidx: {
7799     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7800       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7801     // Decode the offset.
7802     unsigned Offset = MI->getOperand(4).getImm();
7803     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7804     Offset = ARM_AM::getAM2Offset(Offset);
7805     if (isSub)
7806       Offset = -Offset;
7807
7808     MachineMemOperand *MMO = *MI->memoperands_begin();
7809     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7810       .addOperand(MI->getOperand(0))  // Rn_wb
7811       .addOperand(MI->getOperand(1))  // Rt
7812       .addOperand(MI->getOperand(2))  // Rn
7813       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7814       .addOperand(MI->getOperand(5))  // pred
7815       .addOperand(MI->getOperand(6))
7816       .addMemOperand(MMO);
7817     MI->eraseFromParent();
7818     return BB;
7819   }
7820   case ARM::STRr_preidx:
7821   case ARM::STRBr_preidx:
7822   case ARM::STRH_preidx: {
7823     unsigned NewOpc;
7824     switch (MI->getOpcode()) {
7825     default: llvm_unreachable("unexpected opcode!");
7826     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7827     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7828     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7829     }
7830     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7831     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7832       MIB.addOperand(MI->getOperand(i));
7833     MI->eraseFromParent();
7834     return BB;
7835   }
7836
7837   case ARM::tMOVCCr_pseudo: {
7838     // To "insert" a SELECT_CC instruction, we actually have to insert the
7839     // diamond control-flow pattern.  The incoming instruction knows the
7840     // destination vreg to set, the condition code register to branch on, the
7841     // true/false values to select between, and a branch opcode to use.
7842     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7843     MachineFunction::iterator It = BB;
7844     ++It;
7845
7846     //  thisMBB:
7847     //  ...
7848     //   TrueVal = ...
7849     //   cmpTY ccX, r1, r2
7850     //   bCC copy1MBB
7851     //   fallthrough --> copy0MBB
7852     MachineBasicBlock *thisMBB  = BB;
7853     MachineFunction *F = BB->getParent();
7854     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7855     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7856     F->insert(It, copy0MBB);
7857     F->insert(It, sinkMBB);
7858
7859     // Transfer the remainder of BB and its successor edges to sinkMBB.
7860     sinkMBB->splice(sinkMBB->begin(), BB,
7861                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7862     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7863
7864     BB->addSuccessor(copy0MBB);
7865     BB->addSuccessor(sinkMBB);
7866
7867     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7868       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7869
7870     //  copy0MBB:
7871     //   %FalseValue = ...
7872     //   # fallthrough to sinkMBB
7873     BB = copy0MBB;
7874
7875     // Update machine-CFG edges
7876     BB->addSuccessor(sinkMBB);
7877
7878     //  sinkMBB:
7879     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7880     //  ...
7881     BB = sinkMBB;
7882     BuildMI(*BB, BB->begin(), dl,
7883             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7884       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7885       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7886
7887     MI->eraseFromParent();   // The pseudo instruction is gone now.
7888     return BB;
7889   }
7890
7891   case ARM::BCCi64:
7892   case ARM::BCCZi64: {
7893     // If there is an unconditional branch to the other successor, remove it.
7894     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7895
7896     // Compare both parts that make up the double comparison separately for
7897     // equality.
7898     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7899
7900     unsigned LHS1 = MI->getOperand(1).getReg();
7901     unsigned LHS2 = MI->getOperand(2).getReg();
7902     if (RHSisZero) {
7903       AddDefaultPred(BuildMI(BB, dl,
7904                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7905                      .addReg(LHS1).addImm(0));
7906       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7907         .addReg(LHS2).addImm(0)
7908         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7909     } else {
7910       unsigned RHS1 = MI->getOperand(3).getReg();
7911       unsigned RHS2 = MI->getOperand(4).getReg();
7912       AddDefaultPred(BuildMI(BB, dl,
7913                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7914                      .addReg(LHS1).addReg(RHS1));
7915       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7916         .addReg(LHS2).addReg(RHS2)
7917         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7918     }
7919
7920     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7921     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7922     if (MI->getOperand(0).getImm() == ARMCC::NE)
7923       std::swap(destMBB, exitMBB);
7924
7925     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7926       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7927     if (isThumb2)
7928       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7929     else
7930       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7931
7932     MI->eraseFromParent();   // The pseudo instruction is gone now.
7933     return BB;
7934   }
7935
7936   case ARM::Int_eh_sjlj_setjmp:
7937   case ARM::Int_eh_sjlj_setjmp_nofp:
7938   case ARM::tInt_eh_sjlj_setjmp:
7939   case ARM::t2Int_eh_sjlj_setjmp:
7940   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7941     return BB;
7942
7943   case ARM::Int_eh_sjlj_setup_dispatch:
7944     EmitSjLjDispatchBlock(MI, BB);
7945     return BB;
7946
7947   case ARM::ABS:
7948   case ARM::t2ABS: {
7949     // To insert an ABS instruction, we have to insert the
7950     // diamond control-flow pattern.  The incoming instruction knows the
7951     // source vreg to test against 0, the destination vreg to set,
7952     // the condition code register to branch on, the
7953     // true/false values to select between, and a branch opcode to use.
7954     // It transforms
7955     //     V1 = ABS V0
7956     // into
7957     //     V2 = MOVS V0
7958     //     BCC                      (branch to SinkBB if V0 >= 0)
7959     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7960     //     SinkBB: V1 = PHI(V2, V3)
7961     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7962     MachineFunction::iterator BBI = BB;
7963     ++BBI;
7964     MachineFunction *Fn = BB->getParent();
7965     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7966     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7967     Fn->insert(BBI, RSBBB);
7968     Fn->insert(BBI, SinkBB);
7969
7970     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7971     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7972     bool ABSSrcKIll = MI->getOperand(1).isKill();
7973     bool isThumb2 = Subtarget->isThumb2();
7974     MachineRegisterInfo &MRI = Fn->getRegInfo();
7975     // In Thumb mode S must not be specified if source register is the SP or
7976     // PC and if destination register is the SP, so restrict register class
7977     unsigned NewRsbDstReg =
7978       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7979
7980     // Transfer the remainder of BB and its successor edges to sinkMBB.
7981     SinkBB->splice(SinkBB->begin(), BB,
7982                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7983     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7984
7985     BB->addSuccessor(RSBBB);
7986     BB->addSuccessor(SinkBB);
7987
7988     // fall through to SinkMBB
7989     RSBBB->addSuccessor(SinkBB);
7990
7991     // insert a cmp at the end of BB
7992     AddDefaultPred(BuildMI(BB, dl,
7993                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7994                    .addReg(ABSSrcReg).addImm(0));
7995
7996     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7997     BuildMI(BB, dl,
7998       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7999       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8000
8001     // insert rsbri in RSBBB
8002     // Note: BCC and rsbri will be converted into predicated rsbmi
8003     // by if-conversion pass
8004     BuildMI(*RSBBB, RSBBB->begin(), dl,
8005       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8006       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8007       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8008
8009     // insert PHI in SinkBB,
8010     // reuse ABSDstReg to not change uses of ABS instruction
8011     BuildMI(*SinkBB, SinkBB->begin(), dl,
8012       TII->get(ARM::PHI), ABSDstReg)
8013       .addReg(NewRsbDstReg).addMBB(RSBBB)
8014       .addReg(ABSSrcReg).addMBB(BB);
8015
8016     // remove ABS instruction
8017     MI->eraseFromParent();
8018
8019     // return last added BB
8020     return SinkBB;
8021   }
8022   case ARM::COPY_STRUCT_BYVAL_I32:
8023     ++NumLoopByVals;
8024     return EmitStructByval(MI, BB);
8025   case ARM::WIN__CHKSTK:
8026     return EmitLowered__chkstk(MI, BB);
8027   }
8028 }
8029
8030 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8031                                                       SDNode *Node) const {
8032   const MCInstrDesc *MCID = &MI->getDesc();
8033   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8034   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8035   // operand is still set to noreg. If needed, set the optional operand's
8036   // register to CPSR, and remove the redundant implicit def.
8037   //
8038   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8039
8040   // Rename pseudo opcodes.
8041   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8042   if (NewOpc) {
8043     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8044     MCID = &TII->get(NewOpc);
8045
8046     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8047            "converted opcode should be the same except for cc_out");
8048
8049     MI->setDesc(*MCID);
8050
8051     // Add the optional cc_out operand
8052     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8053   }
8054   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8055
8056   // Any ARM instruction that sets the 's' bit should specify an optional
8057   // "cc_out" operand in the last operand position.
8058   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8059     assert(!NewOpc && "Optional cc_out operand required");
8060     return;
8061   }
8062   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8063   // since we already have an optional CPSR def.
8064   bool definesCPSR = false;
8065   bool deadCPSR = false;
8066   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8067        i != e; ++i) {
8068     const MachineOperand &MO = MI->getOperand(i);
8069     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8070       definesCPSR = true;
8071       if (MO.isDead())
8072         deadCPSR = true;
8073       MI->RemoveOperand(i);
8074       break;
8075     }
8076   }
8077   if (!definesCPSR) {
8078     assert(!NewOpc && "Optional cc_out operand required");
8079     return;
8080   }
8081   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8082   if (deadCPSR) {
8083     assert(!MI->getOperand(ccOutIdx).getReg() &&
8084            "expect uninitialized optional cc_out operand");
8085     return;
8086   }
8087
8088   // If this instruction was defined with an optional CPSR def and its dag node
8089   // had a live implicit CPSR def, then activate the optional CPSR def.
8090   MachineOperand &MO = MI->getOperand(ccOutIdx);
8091   MO.setReg(ARM::CPSR);
8092   MO.setIsDef(true);
8093 }
8094
8095 //===----------------------------------------------------------------------===//
8096 //                           ARM Optimization Hooks
8097 //===----------------------------------------------------------------------===//
8098
8099 // Helper function that checks if N is a null or all ones constant.
8100 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8101   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8102   if (!C)
8103     return false;
8104   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8105 }
8106
8107 // Return true if N is conditionally 0 or all ones.
8108 // Detects these expressions where cc is an i1 value:
8109 //
8110 //   (select cc 0, y)   [AllOnes=0]
8111 //   (select cc y, 0)   [AllOnes=0]
8112 //   (zext cc)          [AllOnes=0]
8113 //   (sext cc)          [AllOnes=0/1]
8114 //   (select cc -1, y)  [AllOnes=1]
8115 //   (select cc y, -1)  [AllOnes=1]
8116 //
8117 // Invert is set when N is the null/all ones constant when CC is false.
8118 // OtherOp is set to the alternative value of N.
8119 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8120                                        SDValue &CC, bool &Invert,
8121                                        SDValue &OtherOp,
8122                                        SelectionDAG &DAG) {
8123   switch (N->getOpcode()) {
8124   default: return false;
8125   case ISD::SELECT: {
8126     CC = N->getOperand(0);
8127     SDValue N1 = N->getOperand(1);
8128     SDValue N2 = N->getOperand(2);
8129     if (isZeroOrAllOnes(N1, AllOnes)) {
8130       Invert = false;
8131       OtherOp = N2;
8132       return true;
8133     }
8134     if (isZeroOrAllOnes(N2, AllOnes)) {
8135       Invert = true;
8136       OtherOp = N1;
8137       return true;
8138     }
8139     return false;
8140   }
8141   case ISD::ZERO_EXTEND:
8142     // (zext cc) can never be the all ones value.
8143     if (AllOnes)
8144       return false;
8145     // Fall through.
8146   case ISD::SIGN_EXTEND: {
8147     SDLoc dl(N);
8148     EVT VT = N->getValueType(0);
8149     CC = N->getOperand(0);
8150     if (CC.getValueType() != MVT::i1)
8151       return false;
8152     Invert = !AllOnes;
8153     if (AllOnes)
8154       // When looking for an AllOnes constant, N is an sext, and the 'other'
8155       // value is 0.
8156       OtherOp = DAG.getConstant(0, dl, VT);
8157     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8158       // When looking for a 0 constant, N can be zext or sext.
8159       OtherOp = DAG.getConstant(1, dl, VT);
8160     else
8161       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8162                                 VT);
8163     return true;
8164   }
8165   }
8166 }
8167
8168 // Combine a constant select operand into its use:
8169 //
8170 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8171 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8172 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8173 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8174 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8175 //
8176 // The transform is rejected if the select doesn't have a constant operand that
8177 // is null, or all ones when AllOnes is set.
8178 //
8179 // Also recognize sext/zext from i1:
8180 //
8181 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8182 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8183 //
8184 // These transformations eventually create predicated instructions.
8185 //
8186 // @param N       The node to transform.
8187 // @param Slct    The N operand that is a select.
8188 // @param OtherOp The other N operand (x above).
8189 // @param DCI     Context.
8190 // @param AllOnes Require the select constant to be all ones instead of null.
8191 // @returns The new node, or SDValue() on failure.
8192 static
8193 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8194                             TargetLowering::DAGCombinerInfo &DCI,
8195                             bool AllOnes = false) {
8196   SelectionDAG &DAG = DCI.DAG;
8197   EVT VT = N->getValueType(0);
8198   SDValue NonConstantVal;
8199   SDValue CCOp;
8200   bool SwapSelectOps;
8201   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8202                                   NonConstantVal, DAG))
8203     return SDValue();
8204
8205   // Slct is now know to be the desired identity constant when CC is true.
8206   SDValue TrueVal = OtherOp;
8207   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8208                                  OtherOp, NonConstantVal);
8209   // Unless SwapSelectOps says CC should be false.
8210   if (SwapSelectOps)
8211     std::swap(TrueVal, FalseVal);
8212
8213   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8214                      CCOp, TrueVal, FalseVal);
8215 }
8216
8217 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8218 static
8219 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8220                                        TargetLowering::DAGCombinerInfo &DCI) {
8221   SDValue N0 = N->getOperand(0);
8222   SDValue N1 = N->getOperand(1);
8223   if (N0.getNode()->hasOneUse()) {
8224     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8225     if (Result.getNode())
8226       return Result;
8227   }
8228   if (N1.getNode()->hasOneUse()) {
8229     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8230     if (Result.getNode())
8231       return Result;
8232   }
8233   return SDValue();
8234 }
8235
8236 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8237 // (only after legalization).
8238 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8239                                  TargetLowering::DAGCombinerInfo &DCI,
8240                                  const ARMSubtarget *Subtarget) {
8241
8242   // Only perform optimization if after legalize, and if NEON is available. We
8243   // also expected both operands to be BUILD_VECTORs.
8244   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8245       || N0.getOpcode() != ISD::BUILD_VECTOR
8246       || N1.getOpcode() != ISD::BUILD_VECTOR)
8247     return SDValue();
8248
8249   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8250   EVT VT = N->getValueType(0);
8251   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8252     return SDValue();
8253
8254   // Check that the vector operands are of the right form.
8255   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8256   // operands, where N is the size of the formed vector.
8257   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8258   // index such that we have a pair wise add pattern.
8259
8260   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8261   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8262     return SDValue();
8263   SDValue Vec = N0->getOperand(0)->getOperand(0);
8264   SDNode *V = Vec.getNode();
8265   unsigned nextIndex = 0;
8266
8267   // For each operands to the ADD which are BUILD_VECTORs,
8268   // check to see if each of their operands are an EXTRACT_VECTOR with
8269   // the same vector and appropriate index.
8270   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8271     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8272         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8273
8274       SDValue ExtVec0 = N0->getOperand(i);
8275       SDValue ExtVec1 = N1->getOperand(i);
8276
8277       // First operand is the vector, verify its the same.
8278       if (V != ExtVec0->getOperand(0).getNode() ||
8279           V != ExtVec1->getOperand(0).getNode())
8280         return SDValue();
8281
8282       // Second is the constant, verify its correct.
8283       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8284       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8285
8286       // For the constant, we want to see all the even or all the odd.
8287       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8288           || C1->getZExtValue() != nextIndex+1)
8289         return SDValue();
8290
8291       // Increment index.
8292       nextIndex+=2;
8293     } else
8294       return SDValue();
8295   }
8296
8297   // Create VPADDL node.
8298   SelectionDAG &DAG = DCI.DAG;
8299   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8300
8301   SDLoc dl(N);
8302
8303   // Build operand list.
8304   SmallVector<SDValue, 8> Ops;
8305   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8306                                 TLI.getPointerTy(DAG.getDataLayout())));
8307
8308   // Input is the vector.
8309   Ops.push_back(Vec);
8310
8311   // Get widened type and narrowed type.
8312   MVT widenType;
8313   unsigned numElem = VT.getVectorNumElements();
8314   
8315   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8316   switch (inputLaneType.getSimpleVT().SimpleTy) {
8317     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8318     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8319     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8320     default:
8321       llvm_unreachable("Invalid vector element type for padd optimization.");
8322   }
8323
8324   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8325   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8326   return DAG.getNode(ExtOp, dl, VT, tmp);
8327 }
8328
8329 static SDValue findMUL_LOHI(SDValue V) {
8330   if (V->getOpcode() == ISD::UMUL_LOHI ||
8331       V->getOpcode() == ISD::SMUL_LOHI)
8332     return V;
8333   return SDValue();
8334 }
8335
8336 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8337                                      TargetLowering::DAGCombinerInfo &DCI,
8338                                      const ARMSubtarget *Subtarget) {
8339
8340   if (Subtarget->isThumb1Only()) return SDValue();
8341
8342   // Only perform the checks after legalize when the pattern is available.
8343   if (DCI.isBeforeLegalize()) return SDValue();
8344
8345   // Look for multiply add opportunities.
8346   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8347   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8348   // a glue link from the first add to the second add.
8349   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8350   // a S/UMLAL instruction.
8351   //                  UMUL_LOHI
8352   //                 / :lo    \ :hi
8353   //                /          \          [no multiline comment]
8354   //    loAdd ->  ADDE         |
8355   //                 \ :glue  /
8356   //                  \      /
8357   //                    ADDC   <- hiAdd
8358   //
8359   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8360   SDValue AddcOp0 = AddcNode->getOperand(0);
8361   SDValue AddcOp1 = AddcNode->getOperand(1);
8362
8363   // Check if the two operands are from the same mul_lohi node.
8364   if (AddcOp0.getNode() == AddcOp1.getNode())
8365     return SDValue();
8366
8367   assert(AddcNode->getNumValues() == 2 &&
8368          AddcNode->getValueType(0) == MVT::i32 &&
8369          "Expect ADDC with two result values. First: i32");
8370
8371   // Check that we have a glued ADDC node.
8372   if (AddcNode->getValueType(1) != MVT::Glue)
8373     return SDValue();
8374
8375   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8376   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8377       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8378       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8379       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8380     return SDValue();
8381
8382   // Look for the glued ADDE.
8383   SDNode* AddeNode = AddcNode->getGluedUser();
8384   if (!AddeNode)
8385     return SDValue();
8386
8387   // Make sure it is really an ADDE.
8388   if (AddeNode->getOpcode() != ISD::ADDE)
8389     return SDValue();
8390
8391   assert(AddeNode->getNumOperands() == 3 &&
8392          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8393          "ADDE node has the wrong inputs");
8394
8395   // Check for the triangle shape.
8396   SDValue AddeOp0 = AddeNode->getOperand(0);
8397   SDValue AddeOp1 = AddeNode->getOperand(1);
8398
8399   // Make sure that the ADDE operands are not coming from the same node.
8400   if (AddeOp0.getNode() == AddeOp1.getNode())
8401     return SDValue();
8402
8403   // Find the MUL_LOHI node walking up ADDE's operands.
8404   bool IsLeftOperandMUL = false;
8405   SDValue MULOp = findMUL_LOHI(AddeOp0);
8406   if (MULOp == SDValue())
8407    MULOp = findMUL_LOHI(AddeOp1);
8408   else
8409     IsLeftOperandMUL = true;
8410   if (MULOp == SDValue())
8411     return SDValue();
8412
8413   // Figure out the right opcode.
8414   unsigned Opc = MULOp->getOpcode();
8415   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8416
8417   // Figure out the high and low input values to the MLAL node.
8418   SDValue* HiAdd = nullptr;
8419   SDValue* LoMul = nullptr;
8420   SDValue* LowAdd = nullptr;
8421
8422   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8423   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8424     return SDValue();
8425
8426   if (IsLeftOperandMUL)
8427     HiAdd = &AddeOp1;
8428   else
8429     HiAdd = &AddeOp0;
8430
8431
8432   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8433   // whose low result is fed to the ADDC we are checking.
8434
8435   if (AddcOp0 == MULOp.getValue(0)) {
8436     LoMul = &AddcOp0;
8437     LowAdd = &AddcOp1;
8438   }
8439   if (AddcOp1 == MULOp.getValue(0)) {
8440     LoMul = &AddcOp1;
8441     LowAdd = &AddcOp0;
8442   }
8443
8444   if (!LoMul)
8445     return SDValue();
8446
8447   // Create the merged node.
8448   SelectionDAG &DAG = DCI.DAG;
8449
8450   // Build operand list.
8451   SmallVector<SDValue, 8> Ops;
8452   Ops.push_back(LoMul->getOperand(0));
8453   Ops.push_back(LoMul->getOperand(1));
8454   Ops.push_back(*LowAdd);
8455   Ops.push_back(*HiAdd);
8456
8457   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8458                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8459
8460   // Replace the ADDs' nodes uses by the MLA node's values.
8461   SDValue HiMLALResult(MLALNode.getNode(), 1);
8462   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8463
8464   SDValue LoMLALResult(MLALNode.getNode(), 0);
8465   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8466
8467   // Return original node to notify the driver to stop replacing.
8468   SDValue resNode(AddcNode, 0);
8469   return resNode;
8470 }
8471
8472 /// PerformADDCCombine - Target-specific dag combine transform from
8473 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8474 static SDValue PerformADDCCombine(SDNode *N,
8475                                  TargetLowering::DAGCombinerInfo &DCI,
8476                                  const ARMSubtarget *Subtarget) {
8477
8478   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8479
8480 }
8481
8482 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8483 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8484 /// called with the default operands, and if that fails, with commuted
8485 /// operands.
8486 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8487                                           TargetLowering::DAGCombinerInfo &DCI,
8488                                           const ARMSubtarget *Subtarget){
8489
8490   // Attempt to create vpaddl for this add.
8491   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8492   if (Result.getNode())
8493     return Result;
8494
8495   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8496   if (N0.getNode()->hasOneUse()) {
8497     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8498     if (Result.getNode()) return Result;
8499   }
8500   return SDValue();
8501 }
8502
8503 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8504 ///
8505 static SDValue PerformADDCombine(SDNode *N,
8506                                  TargetLowering::DAGCombinerInfo &DCI,
8507                                  const ARMSubtarget *Subtarget) {
8508   SDValue N0 = N->getOperand(0);
8509   SDValue N1 = N->getOperand(1);
8510
8511   // First try with the default operand order.
8512   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8513   if (Result.getNode())
8514     return Result;
8515
8516   // If that didn't work, try again with the operands commuted.
8517   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8518 }
8519
8520 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8521 ///
8522 static SDValue PerformSUBCombine(SDNode *N,
8523                                  TargetLowering::DAGCombinerInfo &DCI) {
8524   SDValue N0 = N->getOperand(0);
8525   SDValue N1 = N->getOperand(1);
8526
8527   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8528   if (N1.getNode()->hasOneUse()) {
8529     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8530     if (Result.getNode()) return Result;
8531   }
8532
8533   return SDValue();
8534 }
8535
8536 /// PerformVMULCombine
8537 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8538 /// special multiplier accumulator forwarding.
8539 ///   vmul d3, d0, d2
8540 ///   vmla d3, d1, d2
8541 /// is faster than
8542 ///   vadd d3, d0, d1
8543 ///   vmul d3, d3, d2
8544 //  However, for (A + B) * (A + B),
8545 //    vadd d2, d0, d1
8546 //    vmul d3, d0, d2
8547 //    vmla d3, d1, d2
8548 //  is slower than
8549 //    vadd d2, d0, d1
8550 //    vmul d3, d2, d2
8551 static SDValue PerformVMULCombine(SDNode *N,
8552                                   TargetLowering::DAGCombinerInfo &DCI,
8553                                   const ARMSubtarget *Subtarget) {
8554   if (!Subtarget->hasVMLxForwarding())
8555     return SDValue();
8556
8557   SelectionDAG &DAG = DCI.DAG;
8558   SDValue N0 = N->getOperand(0);
8559   SDValue N1 = N->getOperand(1);
8560   unsigned Opcode = N0.getOpcode();
8561   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8562       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8563     Opcode = N1.getOpcode();
8564     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8565         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8566       return SDValue();
8567     std::swap(N0, N1);
8568   }
8569
8570   if (N0 == N1)
8571     return SDValue();
8572
8573   EVT VT = N->getValueType(0);
8574   SDLoc DL(N);
8575   SDValue N00 = N0->getOperand(0);
8576   SDValue N01 = N0->getOperand(1);
8577   return DAG.getNode(Opcode, DL, VT,
8578                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8579                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8580 }
8581
8582 static SDValue PerformMULCombine(SDNode *N,
8583                                  TargetLowering::DAGCombinerInfo &DCI,
8584                                  const ARMSubtarget *Subtarget) {
8585   SelectionDAG &DAG = DCI.DAG;
8586
8587   if (Subtarget->isThumb1Only())
8588     return SDValue();
8589
8590   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8591     return SDValue();
8592
8593   EVT VT = N->getValueType(0);
8594   if (VT.is64BitVector() || VT.is128BitVector())
8595     return PerformVMULCombine(N, DCI, Subtarget);
8596   if (VT != MVT::i32)
8597     return SDValue();
8598
8599   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8600   if (!C)
8601     return SDValue();
8602
8603   int64_t MulAmt = C->getSExtValue();
8604   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8605
8606   ShiftAmt = ShiftAmt & (32 - 1);
8607   SDValue V = N->getOperand(0);
8608   SDLoc DL(N);
8609
8610   SDValue Res;
8611   MulAmt >>= ShiftAmt;
8612
8613   if (MulAmt >= 0) {
8614     if (isPowerOf2_32(MulAmt - 1)) {
8615       // (mul x, 2^N + 1) => (add (shl x, N), x)
8616       Res = DAG.getNode(ISD::ADD, DL, VT,
8617                         V,
8618                         DAG.getNode(ISD::SHL, DL, VT,
8619                                     V,
8620                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8621                                                     MVT::i32)));
8622     } else if (isPowerOf2_32(MulAmt + 1)) {
8623       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8624       Res = DAG.getNode(ISD::SUB, DL, VT,
8625                         DAG.getNode(ISD::SHL, DL, VT,
8626                                     V,
8627                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8628                                                     MVT::i32)),
8629                         V);
8630     } else
8631       return SDValue();
8632   } else {
8633     uint64_t MulAmtAbs = -MulAmt;
8634     if (isPowerOf2_32(MulAmtAbs + 1)) {
8635       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8636       Res = DAG.getNode(ISD::SUB, DL, VT,
8637                         V,
8638                         DAG.getNode(ISD::SHL, DL, VT,
8639                                     V,
8640                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8641                                                     MVT::i32)));
8642     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8643       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8644       Res = DAG.getNode(ISD::ADD, DL, VT,
8645                         V,
8646                         DAG.getNode(ISD::SHL, DL, VT,
8647                                     V,
8648                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8649                                                     MVT::i32)));
8650       Res = DAG.getNode(ISD::SUB, DL, VT,
8651                         DAG.getConstant(0, DL, MVT::i32), Res);
8652
8653     } else
8654       return SDValue();
8655   }
8656
8657   if (ShiftAmt != 0)
8658     Res = DAG.getNode(ISD::SHL, DL, VT,
8659                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8660
8661   // Do not add new nodes to DAG combiner worklist.
8662   DCI.CombineTo(N, Res, false);
8663   return SDValue();
8664 }
8665
8666 static SDValue PerformANDCombine(SDNode *N,
8667                                  TargetLowering::DAGCombinerInfo &DCI,
8668                                  const ARMSubtarget *Subtarget) {
8669
8670   // Attempt to use immediate-form VBIC
8671   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8672   SDLoc dl(N);
8673   EVT VT = N->getValueType(0);
8674   SelectionDAG &DAG = DCI.DAG;
8675
8676   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8677     return SDValue();
8678
8679   APInt SplatBits, SplatUndef;
8680   unsigned SplatBitSize;
8681   bool HasAnyUndefs;
8682   if (BVN &&
8683       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8684     if (SplatBitSize <= 64) {
8685       EVT VbicVT;
8686       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8687                                       SplatUndef.getZExtValue(), SplatBitSize,
8688                                       DAG, dl, VbicVT, VT.is128BitVector(),
8689                                       OtherModImm);
8690       if (Val.getNode()) {
8691         SDValue Input =
8692           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8693         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8694         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8695       }
8696     }
8697   }
8698
8699   if (!Subtarget->isThumb1Only()) {
8700     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8701     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8702     if (Result.getNode())
8703       return Result;
8704   }
8705
8706   return SDValue();
8707 }
8708
8709 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8710 static SDValue PerformORCombine(SDNode *N,
8711                                 TargetLowering::DAGCombinerInfo &DCI,
8712                                 const ARMSubtarget *Subtarget) {
8713   // Attempt to use immediate-form VORR
8714   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8715   SDLoc dl(N);
8716   EVT VT = N->getValueType(0);
8717   SelectionDAG &DAG = DCI.DAG;
8718
8719   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8720     return SDValue();
8721
8722   APInt SplatBits, SplatUndef;
8723   unsigned SplatBitSize;
8724   bool HasAnyUndefs;
8725   if (BVN && Subtarget->hasNEON() &&
8726       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8727     if (SplatBitSize <= 64) {
8728       EVT VorrVT;
8729       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8730                                       SplatUndef.getZExtValue(), SplatBitSize,
8731                                       DAG, dl, VorrVT, VT.is128BitVector(),
8732                                       OtherModImm);
8733       if (Val.getNode()) {
8734         SDValue Input =
8735           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8736         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8737         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8738       }
8739     }
8740   }
8741
8742   if (!Subtarget->isThumb1Only()) {
8743     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8744     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8745     if (Result.getNode())
8746       return Result;
8747   }
8748
8749   // The code below optimizes (or (and X, Y), Z).
8750   // The AND operand needs to have a single user to make these optimizations
8751   // profitable.
8752   SDValue N0 = N->getOperand(0);
8753   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8754     return SDValue();
8755   SDValue N1 = N->getOperand(1);
8756
8757   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8758   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8759       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8760     APInt SplatUndef;
8761     unsigned SplatBitSize;
8762     bool HasAnyUndefs;
8763
8764     APInt SplatBits0, SplatBits1;
8765     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8766     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8767     // Ensure that the second operand of both ands are constants
8768     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8769                                       HasAnyUndefs) && !HasAnyUndefs) {
8770         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8771                                           HasAnyUndefs) && !HasAnyUndefs) {
8772             // Ensure that the bit width of the constants are the same and that
8773             // the splat arguments are logical inverses as per the pattern we
8774             // are trying to simplify.
8775             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8776                 SplatBits0 == ~SplatBits1) {
8777                 // Canonicalize the vector type to make instruction selection
8778                 // simpler.
8779                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8780                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8781                                              N0->getOperand(1),
8782                                              N0->getOperand(0),
8783                                              N1->getOperand(0));
8784                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8785             }
8786         }
8787     }
8788   }
8789
8790   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8791   // reasonable.
8792
8793   // BFI is only available on V6T2+
8794   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8795     return SDValue();
8796
8797   SDLoc DL(N);
8798   // 1) or (and A, mask), val => ARMbfi A, val, mask
8799   //      iff (val & mask) == val
8800   //
8801   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8802   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8803   //          && mask == ~mask2
8804   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8805   //          && ~mask == mask2
8806   //  (i.e., copy a bitfield value into another bitfield of the same width)
8807
8808   if (VT != MVT::i32)
8809     return SDValue();
8810
8811   SDValue N00 = N0.getOperand(0);
8812
8813   // The value and the mask need to be constants so we can verify this is
8814   // actually a bitfield set. If the mask is 0xffff, we can do better
8815   // via a movt instruction, so don't use BFI in that case.
8816   SDValue MaskOp = N0.getOperand(1);
8817   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8818   if (!MaskC)
8819     return SDValue();
8820   unsigned Mask = MaskC->getZExtValue();
8821   if (Mask == 0xffff)
8822     return SDValue();
8823   SDValue Res;
8824   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8825   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8826   if (N1C) {
8827     unsigned Val = N1C->getZExtValue();
8828     if ((Val & ~Mask) != Val)
8829       return SDValue();
8830
8831     if (ARM::isBitFieldInvertedMask(Mask)) {
8832       Val >>= countTrailingZeros(~Mask);
8833
8834       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8835                         DAG.getConstant(Val, DL, MVT::i32),
8836                         DAG.getConstant(Mask, DL, MVT::i32));
8837
8838       // Do not add new nodes to DAG combiner worklist.
8839       DCI.CombineTo(N, Res, false);
8840       return SDValue();
8841     }
8842   } else if (N1.getOpcode() == ISD::AND) {
8843     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8844     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8845     if (!N11C)
8846       return SDValue();
8847     unsigned Mask2 = N11C->getZExtValue();
8848
8849     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8850     // as is to match.
8851     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           (Mask == 0xffff || Mask == 0xffff0000))
8857         return SDValue();
8858       // 2a
8859       unsigned amt = countTrailingZeros(Mask2);
8860       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8861                         DAG.getConstant(amt, DL, MVT::i32));
8862       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8863                         DAG.getConstant(Mask, DL, MVT::i32));
8864       // Do not add new nodes to DAG combiner worklist.
8865       DCI.CombineTo(N, Res, false);
8866       return SDValue();
8867     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8868                (~Mask == Mask2)) {
8869       // The pack halfword instruction works better for masks that fit it,
8870       // so use that when it's available.
8871       if (Subtarget->hasT2ExtractPack() &&
8872           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8873         return SDValue();
8874       // 2b
8875       unsigned lsb = countTrailingZeros(Mask);
8876       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8877                         DAG.getConstant(lsb, DL, MVT::i32));
8878       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8879                         DAG.getConstant(Mask2, DL, MVT::i32));
8880       // Do not add new nodes to DAG combiner worklist.
8881       DCI.CombineTo(N, Res, false);
8882       return SDValue();
8883     }
8884   }
8885
8886   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8887       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8888       ARM::isBitFieldInvertedMask(~Mask)) {
8889     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8890     // where lsb(mask) == #shamt and masked bits of B are known zero.
8891     SDValue ShAmt = N00.getOperand(1);
8892     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8893     unsigned LSB = countTrailingZeros(Mask);
8894     if (ShAmtC != LSB)
8895       return SDValue();
8896
8897     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8898                       DAG.getConstant(~Mask, DL, MVT::i32));
8899
8900     // Do not add new nodes to DAG combiner worklist.
8901     DCI.CombineTo(N, Res, false);
8902   }
8903
8904   return SDValue();
8905 }
8906
8907 static SDValue PerformXORCombine(SDNode *N,
8908                                  TargetLowering::DAGCombinerInfo &DCI,
8909                                  const ARMSubtarget *Subtarget) {
8910   EVT VT = N->getValueType(0);
8911   SelectionDAG &DAG = DCI.DAG;
8912
8913   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8914     return SDValue();
8915
8916   if (!Subtarget->isThumb1Only()) {
8917     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8918     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8919     if (Result.getNode())
8920       return Result;
8921   }
8922
8923   return SDValue();
8924 }
8925
8926 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8927 /// the bits being cleared by the AND are not demanded by the BFI.
8928 static SDValue PerformBFICombine(SDNode *N,
8929                                  TargetLowering::DAGCombinerInfo &DCI) {
8930   SDValue N1 = N->getOperand(1);
8931   if (N1.getOpcode() == ISD::AND) {
8932     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8933     if (!N11C)
8934       return SDValue();
8935     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8936     unsigned LSB = countTrailingZeros(~InvMask);
8937     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8938     assert(Width <
8939                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8940            "undefined behavior");
8941     unsigned Mask = (1u << Width) - 1;
8942     unsigned Mask2 = N11C->getZExtValue();
8943     if ((Mask & (~Mask2)) == 0)
8944       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8945                              N->getOperand(0), N1.getOperand(0),
8946                              N->getOperand(2));
8947   }
8948   return SDValue();
8949 }
8950
8951 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8952 /// ARMISD::VMOVRRD.
8953 static SDValue PerformVMOVRRDCombine(SDNode *N,
8954                                      TargetLowering::DAGCombinerInfo &DCI,
8955                                      const ARMSubtarget *Subtarget) {
8956   // vmovrrd(vmovdrr x, y) -> x,y
8957   SDValue InDouble = N->getOperand(0);
8958   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8959     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8960
8961   // vmovrrd(load f64) -> (load i32), (load i32)
8962   SDNode *InNode = InDouble.getNode();
8963   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8964       InNode->getValueType(0) == MVT::f64 &&
8965       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8966       !cast<LoadSDNode>(InNode)->isVolatile()) {
8967     // TODO: Should this be done for non-FrameIndex operands?
8968     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8969
8970     SelectionDAG &DAG = DCI.DAG;
8971     SDLoc DL(LD);
8972     SDValue BasePtr = LD->getBasePtr();
8973     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8974                                  LD->getPointerInfo(), LD->isVolatile(),
8975                                  LD->isNonTemporal(), LD->isInvariant(),
8976                                  LD->getAlignment());
8977
8978     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8979                                     DAG.getConstant(4, DL, MVT::i32));
8980     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8981                                  LD->getPointerInfo(), LD->isVolatile(),
8982                                  LD->isNonTemporal(), LD->isInvariant(),
8983                                  std::min(4U, LD->getAlignment() / 2));
8984
8985     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8986     if (DCI.DAG.getDataLayout().isBigEndian())
8987       std::swap (NewLD1, NewLD2);
8988     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8989     return Result;
8990   }
8991
8992   return SDValue();
8993 }
8994
8995 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8996 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8997 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8998   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8999   SDValue Op0 = N->getOperand(0);
9000   SDValue Op1 = N->getOperand(1);
9001   if (Op0.getOpcode() == ISD::BITCAST)
9002     Op0 = Op0.getOperand(0);
9003   if (Op1.getOpcode() == ISD::BITCAST)
9004     Op1 = Op1.getOperand(0);
9005   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9006       Op0.getNode() == Op1.getNode() &&
9007       Op0.getResNo() == 0 && Op1.getResNo() == 1)
9008     return DAG.getNode(ISD::BITCAST, SDLoc(N),
9009                        N->getValueType(0), Op0.getOperand(0));
9010   return SDValue();
9011 }
9012
9013 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9014 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9015 /// i64 vector to have f64 elements, since the value can then be loaded
9016 /// directly into a VFP register.
9017 static bool hasNormalLoadOperand(SDNode *N) {
9018   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9019   for (unsigned i = 0; i < NumElts; ++i) {
9020     SDNode *Elt = N->getOperand(i).getNode();
9021     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9022       return true;
9023   }
9024   return false;
9025 }
9026
9027 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9028 /// ISD::BUILD_VECTOR.
9029 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9030                                           TargetLowering::DAGCombinerInfo &DCI,
9031                                           const ARMSubtarget *Subtarget) {
9032   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9033   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9034   // into a pair of GPRs, which is fine when the value is used as a scalar,
9035   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9036   SelectionDAG &DAG = DCI.DAG;
9037   if (N->getNumOperands() == 2) {
9038     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9039     if (RV.getNode())
9040       return RV;
9041   }
9042
9043   // Load i64 elements as f64 values so that type legalization does not split
9044   // them up into i32 values.
9045   EVT VT = N->getValueType(0);
9046   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9047     return SDValue();
9048   SDLoc dl(N);
9049   SmallVector<SDValue, 8> Ops;
9050   unsigned NumElts = VT.getVectorNumElements();
9051   for (unsigned i = 0; i < NumElts; ++i) {
9052     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9053     Ops.push_back(V);
9054     // Make the DAGCombiner fold the bitcast.
9055     DCI.AddToWorklist(V.getNode());
9056   }
9057   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9058   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9059   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9060 }
9061
9062 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9063 static SDValue
9064 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9065   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9066   // At that time, we may have inserted bitcasts from integer to float.
9067   // If these bitcasts have survived DAGCombine, change the lowering of this
9068   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9069   // force to use floating point types.
9070
9071   // Make sure we can change the type of the vector.
9072   // This is possible iff:
9073   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9074   //    1.1. Vector is used only once.
9075   //    1.2. Use is a bit convert to an integer type.
9076   // 2. The size of its operands are 32-bits (64-bits are not legal).
9077   EVT VT = N->getValueType(0);
9078   EVT EltVT = VT.getVectorElementType();
9079
9080   // Check 1.1. and 2.
9081   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9082     return SDValue();
9083
9084   // By construction, the input type must be float.
9085   assert(EltVT == MVT::f32 && "Unexpected type!");
9086
9087   // Check 1.2.
9088   SDNode *Use = *N->use_begin();
9089   if (Use->getOpcode() != ISD::BITCAST ||
9090       Use->getValueType(0).isFloatingPoint())
9091     return SDValue();
9092
9093   // Check profitability.
9094   // Model is, if more than half of the relevant operands are bitcast from
9095   // i32, turn the build_vector into a sequence of insert_vector_elt.
9096   // Relevant operands are everything that is not statically
9097   // (i.e., at compile time) bitcasted.
9098   unsigned NumOfBitCastedElts = 0;
9099   unsigned NumElts = VT.getVectorNumElements();
9100   unsigned NumOfRelevantElts = NumElts;
9101   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9102     SDValue Elt = N->getOperand(Idx);
9103     if (Elt->getOpcode() == ISD::BITCAST) {
9104       // Assume only bit cast to i32 will go away.
9105       if (Elt->getOperand(0).getValueType() == MVT::i32)
9106         ++NumOfBitCastedElts;
9107     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9108       // Constants are statically casted, thus do not count them as
9109       // relevant operands.
9110       --NumOfRelevantElts;
9111   }
9112
9113   // Check if more than half of the elements require a non-free bitcast.
9114   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9115     return SDValue();
9116
9117   SelectionDAG &DAG = DCI.DAG;
9118   // Create the new vector type.
9119   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9120   // Check if the type is legal.
9121   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9122   if (!TLI.isTypeLegal(VecVT))
9123     return SDValue();
9124
9125   // Combine:
9126   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9127   // => BITCAST INSERT_VECTOR_ELT
9128   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9129   //                      (BITCAST EN), N.
9130   SDValue Vec = DAG.getUNDEF(VecVT);
9131   SDLoc dl(N);
9132   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9133     SDValue V = N->getOperand(Idx);
9134     if (V.getOpcode() == ISD::UNDEF)
9135       continue;
9136     if (V.getOpcode() == ISD::BITCAST &&
9137         V->getOperand(0).getValueType() == MVT::i32)
9138       // Fold obvious case.
9139       V = V.getOperand(0);
9140     else {
9141       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9142       // Make the DAGCombiner fold the bitcasts.
9143       DCI.AddToWorklist(V.getNode());
9144     }
9145     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9146     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9147   }
9148   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9149   // Make the DAGCombiner fold the bitcasts.
9150   DCI.AddToWorklist(Vec.getNode());
9151   return Vec;
9152 }
9153
9154 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9155 /// ISD::INSERT_VECTOR_ELT.
9156 static SDValue PerformInsertEltCombine(SDNode *N,
9157                                        TargetLowering::DAGCombinerInfo &DCI) {
9158   // Bitcast an i64 load inserted into a vector to f64.
9159   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9160   EVT VT = N->getValueType(0);
9161   SDNode *Elt = N->getOperand(1).getNode();
9162   if (VT.getVectorElementType() != MVT::i64 ||
9163       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9164     return SDValue();
9165
9166   SelectionDAG &DAG = DCI.DAG;
9167   SDLoc dl(N);
9168   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9169                                  VT.getVectorNumElements());
9170   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9171   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9172   // Make the DAGCombiner fold the bitcasts.
9173   DCI.AddToWorklist(Vec.getNode());
9174   DCI.AddToWorklist(V.getNode());
9175   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9176                                Vec, V, N->getOperand(2));
9177   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9178 }
9179
9180 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9181 /// ISD::VECTOR_SHUFFLE.
9182 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9183   // The LLVM shufflevector instruction does not require the shuffle mask
9184   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9185   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9186   // operands do not match the mask length, they are extended by concatenating
9187   // them with undef vectors.  That is probably the right thing for other
9188   // targets, but for NEON it is better to concatenate two double-register
9189   // size vector operands into a single quad-register size vector.  Do that
9190   // transformation here:
9191   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9192   //   shuffle(concat(v1, v2), undef)
9193   SDValue Op0 = N->getOperand(0);
9194   SDValue Op1 = N->getOperand(1);
9195   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9196       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9197       Op0.getNumOperands() != 2 ||
9198       Op1.getNumOperands() != 2)
9199     return SDValue();
9200   SDValue Concat0Op1 = Op0.getOperand(1);
9201   SDValue Concat1Op1 = Op1.getOperand(1);
9202   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9203       Concat1Op1.getOpcode() != ISD::UNDEF)
9204     return SDValue();
9205   // Skip the transformation if any of the types are illegal.
9206   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9207   EVT VT = N->getValueType(0);
9208   if (!TLI.isTypeLegal(VT) ||
9209       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9210       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9211     return SDValue();
9212
9213   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9214                                   Op0.getOperand(0), Op1.getOperand(0));
9215   // Translate the shuffle mask.
9216   SmallVector<int, 16> NewMask;
9217   unsigned NumElts = VT.getVectorNumElements();
9218   unsigned HalfElts = NumElts/2;
9219   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9220   for (unsigned n = 0; n < NumElts; ++n) {
9221     int MaskElt = SVN->getMaskElt(n);
9222     int NewElt = -1;
9223     if (MaskElt < (int)HalfElts)
9224       NewElt = MaskElt;
9225     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9226       NewElt = HalfElts + MaskElt - NumElts;
9227     NewMask.push_back(NewElt);
9228   }
9229   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9230                               DAG.getUNDEF(VT), NewMask.data());
9231 }
9232
9233 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9234 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9235 /// base address updates.
9236 /// For generic load/stores, the memory type is assumed to be a vector.
9237 /// The caller is assumed to have checked legality.
9238 static SDValue CombineBaseUpdate(SDNode *N,
9239                                  TargetLowering::DAGCombinerInfo &DCI) {
9240   SelectionDAG &DAG = DCI.DAG;
9241   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9242                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9243   const bool isStore = N->getOpcode() == ISD::STORE;
9244   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9245   SDValue Addr = N->getOperand(AddrOpIdx);
9246   MemSDNode *MemN = cast<MemSDNode>(N);
9247   SDLoc dl(N);
9248
9249   // Search for a use of the address operand that is an increment.
9250   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9251          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9252     SDNode *User = *UI;
9253     if (User->getOpcode() != ISD::ADD ||
9254         UI.getUse().getResNo() != Addr.getResNo())
9255       continue;
9256
9257     // Check that the add is independent of the load/store.  Otherwise, folding
9258     // it would create a cycle.
9259     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9260       continue;
9261
9262     // Find the new opcode for the updating load/store.
9263     bool isLoadOp = true;
9264     bool isLaneOp = false;
9265     unsigned NewOpc = 0;
9266     unsigned NumVecs = 0;
9267     if (isIntrinsic) {
9268       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9269       switch (IntNo) {
9270       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9271       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9272         NumVecs = 1; break;
9273       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9274         NumVecs = 2; break;
9275       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9276         NumVecs = 3; break;
9277       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9278         NumVecs = 4; break;
9279       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9280         NumVecs = 2; isLaneOp = true; break;
9281       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9282         NumVecs = 3; isLaneOp = true; break;
9283       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9284         NumVecs = 4; isLaneOp = true; break;
9285       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9286         NumVecs = 1; isLoadOp = false; break;
9287       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9288         NumVecs = 2; isLoadOp = false; break;
9289       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9290         NumVecs = 3; isLoadOp = false; break;
9291       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9292         NumVecs = 4; isLoadOp = false; break;
9293       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9294         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9295       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9296         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9297       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9298         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9299       }
9300     } else {
9301       isLaneOp = true;
9302       switch (N->getOpcode()) {
9303       default: llvm_unreachable("unexpected opcode for Neon base update");
9304       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9305       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9306       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9307       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9308         NumVecs = 1; isLaneOp = false; break;
9309       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9310         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9311       }
9312     }
9313
9314     // Find the size of memory referenced by the load/store.
9315     EVT VecTy;
9316     if (isLoadOp) {
9317       VecTy = N->getValueType(0);
9318     } else if (isIntrinsic) {
9319       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9320     } else {
9321       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9322       VecTy = N->getOperand(1).getValueType();
9323     }
9324
9325     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9326     if (isLaneOp)
9327       NumBytes /= VecTy.getVectorNumElements();
9328
9329     // If the increment is a constant, it must match the memory ref size.
9330     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9331     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9332       uint64_t IncVal = CInc->getZExtValue();
9333       if (IncVal != NumBytes)
9334         continue;
9335     } else if (NumBytes >= 3 * 16) {
9336       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9337       // separate instructions that make it harder to use a non-constant update.
9338       continue;
9339     }
9340
9341     // OK, we found an ADD we can fold into the base update.
9342     // Now, create a _UPD node, taking care of not breaking alignment.
9343
9344     EVT AlignedVecTy = VecTy;
9345     unsigned Alignment = MemN->getAlignment();
9346
9347     // If this is a less-than-standard-aligned load/store, change the type to
9348     // match the standard alignment.
9349     // The alignment is overlooked when selecting _UPD variants; and it's
9350     // easier to introduce bitcasts here than fix that.
9351     // There are 3 ways to get to this base-update combine:
9352     // - intrinsics: they are assumed to be properly aligned (to the standard
9353     //   alignment of the memory type), so we don't need to do anything.
9354     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9355     //   intrinsics, so, likewise, there's nothing to do.
9356     // - generic load/store instructions: the alignment is specified as an
9357     //   explicit operand, rather than implicitly as the standard alignment
9358     //   of the memory type (like the intrisics).  We need to change the
9359     //   memory type to match the explicit alignment.  That way, we don't
9360     //   generate non-standard-aligned ARMISD::VLDx nodes.
9361     if (isa<LSBaseSDNode>(N)) {
9362       if (Alignment == 0)
9363         Alignment = 1;
9364       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9365         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9366         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9367         assert(!isLaneOp && "Unexpected generic load/store lane.");
9368         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9369         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9370       }
9371       // Don't set an explicit alignment on regular load/stores that we want
9372       // to transform to VLD/VST 1_UPD nodes.
9373       // This matches the behavior of regular load/stores, which only get an
9374       // explicit alignment if the MMO alignment is larger than the standard
9375       // alignment of the memory type.
9376       // Intrinsics, however, always get an explicit alignment, set to the
9377       // alignment of the MMO.
9378       Alignment = 1;
9379     }
9380
9381     // Create the new updating load/store node.
9382     // First, create an SDVTList for the new updating node's results.
9383     EVT Tys[6];
9384     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9385     unsigned n;
9386     for (n = 0; n < NumResultVecs; ++n)
9387       Tys[n] = AlignedVecTy;
9388     Tys[n++] = MVT::i32;
9389     Tys[n] = MVT::Other;
9390     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9391
9392     // Then, gather the new node's operands.
9393     SmallVector<SDValue, 8> Ops;
9394     Ops.push_back(N->getOperand(0)); // incoming chain
9395     Ops.push_back(N->getOperand(AddrOpIdx));
9396     Ops.push_back(Inc);
9397
9398     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9399       // Try to match the intrinsic's signature
9400       Ops.push_back(StN->getValue());
9401     } else {
9402       // Loads (and of course intrinsics) match the intrinsics' signature,
9403       // so just add all but the alignment operand.
9404       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9405         Ops.push_back(N->getOperand(i));
9406     }
9407
9408     // For all node types, the alignment operand is always the last one.
9409     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9410
9411     // If this is a non-standard-aligned STORE, the penultimate operand is the
9412     // stored value.  Bitcast it to the aligned type.
9413     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9414       SDValue &StVal = Ops[Ops.size()-2];
9415       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9416     }
9417
9418     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9419                                            Ops, AlignedVecTy,
9420                                            MemN->getMemOperand());
9421
9422     // Update the uses.
9423     SmallVector<SDValue, 5> NewResults;
9424     for (unsigned i = 0; i < NumResultVecs; ++i)
9425       NewResults.push_back(SDValue(UpdN.getNode(), i));
9426
9427     // If this is an non-standard-aligned LOAD, the first result is the loaded
9428     // value.  Bitcast it to the expected result type.
9429     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9430       SDValue &LdVal = NewResults[0];
9431       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9432     }
9433
9434     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9435     DCI.CombineTo(N, NewResults);
9436     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9437
9438     break;
9439   }
9440   return SDValue();
9441 }
9442
9443 static SDValue PerformVLDCombine(SDNode *N,
9444                                  TargetLowering::DAGCombinerInfo &DCI) {
9445   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9446     return SDValue();
9447
9448   return CombineBaseUpdate(N, DCI);
9449 }
9450
9451 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9452 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9453 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9454 /// return true.
9455 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9456   SelectionDAG &DAG = DCI.DAG;
9457   EVT VT = N->getValueType(0);
9458   // vldN-dup instructions only support 64-bit vectors for N > 1.
9459   if (!VT.is64BitVector())
9460     return false;
9461
9462   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9463   SDNode *VLD = N->getOperand(0).getNode();
9464   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9465     return false;
9466   unsigned NumVecs = 0;
9467   unsigned NewOpc = 0;
9468   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9469   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9470     NumVecs = 2;
9471     NewOpc = ARMISD::VLD2DUP;
9472   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9473     NumVecs = 3;
9474     NewOpc = ARMISD::VLD3DUP;
9475   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9476     NumVecs = 4;
9477     NewOpc = ARMISD::VLD4DUP;
9478   } else {
9479     return false;
9480   }
9481
9482   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9483   // numbers match the load.
9484   unsigned VLDLaneNo =
9485     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9486   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9487        UI != UE; ++UI) {
9488     // Ignore uses of the chain result.
9489     if (UI.getUse().getResNo() == NumVecs)
9490       continue;
9491     SDNode *User = *UI;
9492     if (User->getOpcode() != ARMISD::VDUPLANE ||
9493         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9494       return false;
9495   }
9496
9497   // Create the vldN-dup node.
9498   EVT Tys[5];
9499   unsigned n;
9500   for (n = 0; n < NumVecs; ++n)
9501     Tys[n] = VT;
9502   Tys[n] = MVT::Other;
9503   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9504   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9505   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9506   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9507                                            Ops, VLDMemInt->getMemoryVT(),
9508                                            VLDMemInt->getMemOperand());
9509
9510   // Update the uses.
9511   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9512        UI != UE; ++UI) {
9513     unsigned ResNo = UI.getUse().getResNo();
9514     // Ignore uses of the chain result.
9515     if (ResNo == NumVecs)
9516       continue;
9517     SDNode *User = *UI;
9518     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9519   }
9520
9521   // Now the vldN-lane intrinsic is dead except for its chain result.
9522   // Update uses of the chain.
9523   std::vector<SDValue> VLDDupResults;
9524   for (unsigned n = 0; n < NumVecs; ++n)
9525     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9526   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9527   DCI.CombineTo(VLD, VLDDupResults);
9528
9529   return true;
9530 }
9531
9532 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9533 /// ARMISD::VDUPLANE.
9534 static SDValue PerformVDUPLANECombine(SDNode *N,
9535                                       TargetLowering::DAGCombinerInfo &DCI) {
9536   SDValue Op = N->getOperand(0);
9537
9538   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9539   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9540   if (CombineVLDDUP(N, DCI))
9541     return SDValue(N, 0);
9542
9543   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9544   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9545   while (Op.getOpcode() == ISD::BITCAST)
9546     Op = Op.getOperand(0);
9547   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9548     return SDValue();
9549
9550   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9551   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9552   // The canonical VMOV for a zero vector uses a 32-bit element size.
9553   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9554   unsigned EltBits;
9555   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9556     EltSize = 8;
9557   EVT VT = N->getValueType(0);
9558   if (EltSize > VT.getVectorElementType().getSizeInBits())
9559     return SDValue();
9560
9561   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9562 }
9563
9564 static SDValue PerformLOADCombine(SDNode *N,
9565                                   TargetLowering::DAGCombinerInfo &DCI) {
9566   EVT VT = N->getValueType(0);
9567
9568   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9569   if (ISD::isNormalLoad(N) && VT.isVector() &&
9570       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9571     return CombineBaseUpdate(N, DCI);
9572
9573   return SDValue();
9574 }
9575
9576 /// PerformSTORECombine - Target-specific dag combine xforms for
9577 /// ISD::STORE.
9578 static SDValue PerformSTORECombine(SDNode *N,
9579                                    TargetLowering::DAGCombinerInfo &DCI) {
9580   StoreSDNode *St = cast<StoreSDNode>(N);
9581   if (St->isVolatile())
9582     return SDValue();
9583
9584   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9585   // pack all of the elements in one place.  Next, store to memory in fewer
9586   // chunks.
9587   SDValue StVal = St->getValue();
9588   EVT VT = StVal.getValueType();
9589   if (St->isTruncatingStore() && VT.isVector()) {
9590     SelectionDAG &DAG = DCI.DAG;
9591     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9592     EVT StVT = St->getMemoryVT();
9593     unsigned NumElems = VT.getVectorNumElements();
9594     assert(StVT != VT && "Cannot truncate to the same type");
9595     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9596     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9597
9598     // From, To sizes and ElemCount must be pow of two
9599     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9600
9601     // We are going to use the original vector elt for storing.
9602     // Accumulated smaller vector elements must be a multiple of the store size.
9603     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9604
9605     unsigned SizeRatio  = FromEltSz / ToEltSz;
9606     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9607
9608     // Create a type on which we perform the shuffle.
9609     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9610                                      NumElems*SizeRatio);
9611     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9612
9613     SDLoc DL(St);
9614     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9615     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9616     for (unsigned i = 0; i < NumElems; ++i)
9617       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9618                           ? (i + 1) * SizeRatio - 1
9619                           : i * SizeRatio;
9620
9621     // Can't shuffle using an illegal type.
9622     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9623
9624     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9625                                 DAG.getUNDEF(WideVec.getValueType()),
9626                                 ShuffleVec.data());
9627     // At this point all of the data is stored at the bottom of the
9628     // register. We now need to save it to mem.
9629
9630     // Find the largest store unit
9631     MVT StoreType = MVT::i8;
9632     for (MVT Tp : MVT::integer_valuetypes()) {
9633       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9634         StoreType = Tp;
9635     }
9636     // Didn't find a legal store type.
9637     if (!TLI.isTypeLegal(StoreType))
9638       return SDValue();
9639
9640     // Bitcast the original vector into a vector of store-size units
9641     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9642             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9643     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9644     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9645     SmallVector<SDValue, 8> Chains;
9646     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9647                                         TLI.getPointerTy(DAG.getDataLayout()));
9648     SDValue BasePtr = St->getBasePtr();
9649
9650     // Perform one or more big stores into memory.
9651     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9652     for (unsigned I = 0; I < E; I++) {
9653       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9654                                    StoreType, ShuffWide,
9655                                    DAG.getIntPtrConstant(I, DL));
9656       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9657                                 St->getPointerInfo(), St->isVolatile(),
9658                                 St->isNonTemporal(), St->getAlignment());
9659       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9660                             Increment);
9661       Chains.push_back(Ch);
9662     }
9663     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9664   }
9665
9666   if (!ISD::isNormalStore(St))
9667     return SDValue();
9668
9669   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9670   // ARM stores of arguments in the same cache line.
9671   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9672       StVal.getNode()->hasOneUse()) {
9673     SelectionDAG  &DAG = DCI.DAG;
9674     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9675     SDLoc DL(St);
9676     SDValue BasePtr = St->getBasePtr();
9677     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9678                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9679                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9680                                   St->isNonTemporal(), St->getAlignment());
9681
9682     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9683                                     DAG.getConstant(4, DL, MVT::i32));
9684     return DAG.getStore(NewST1.getValue(0), DL,
9685                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9686                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9687                         St->isNonTemporal(),
9688                         std::min(4U, St->getAlignment() / 2));
9689   }
9690
9691   if (StVal.getValueType() == MVT::i64 &&
9692       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9693
9694     // Bitcast an i64 store extracted from a vector to f64.
9695     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9696     SelectionDAG &DAG = DCI.DAG;
9697     SDLoc dl(StVal);
9698     SDValue IntVec = StVal.getOperand(0);
9699     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9700                                    IntVec.getValueType().getVectorNumElements());
9701     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9702     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9703                                  Vec, StVal.getOperand(1));
9704     dl = SDLoc(N);
9705     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9706     // Make the DAGCombiner fold the bitcasts.
9707     DCI.AddToWorklist(Vec.getNode());
9708     DCI.AddToWorklist(ExtElt.getNode());
9709     DCI.AddToWorklist(V.getNode());
9710     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9711                         St->getPointerInfo(), St->isVolatile(),
9712                         St->isNonTemporal(), St->getAlignment(),
9713                         St->getAAInfo());
9714   }
9715
9716   // If this is a legal vector store, try to combine it into a VST1_UPD.
9717   if (ISD::isNormalStore(N) && VT.isVector() &&
9718       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9719     return CombineBaseUpdate(N, DCI);
9720
9721   return SDValue();
9722 }
9723
9724 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9725 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9726 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9727 {
9728   integerPart cN;
9729   integerPart c0 = 0;
9730   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9731        I != E; I++) {
9732     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9733     if (!C)
9734       return false;
9735
9736     bool isExact;
9737     APFloat APF = C->getValueAPF();
9738     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9739         != APFloat::opOK || !isExact)
9740       return false;
9741
9742     c0 = (I == 0) ? cN : c0;
9743     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9744       return false;
9745   }
9746   C = c0;
9747   return true;
9748 }
9749
9750 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9751 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9752 /// when the VMUL has a constant operand that is a power of 2.
9753 ///
9754 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9755 ///  vmul.f32        d16, d17, d16
9756 ///  vcvt.s32.f32    d16, d16
9757 /// becomes:
9758 ///  vcvt.s32.f32    d16, d16, #3
9759 static SDValue PerformVCVTCombine(SDNode *N,
9760                                   TargetLowering::DAGCombinerInfo &DCI,
9761                                   const ARMSubtarget *Subtarget) {
9762   SelectionDAG &DAG = DCI.DAG;
9763   SDValue Op = N->getOperand(0);
9764
9765   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9766       Op.getOpcode() != ISD::FMUL)
9767     return SDValue();
9768
9769   uint64_t C;
9770   SDValue N0 = Op->getOperand(0);
9771   SDValue ConstVec = Op->getOperand(1);
9772   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9773
9774   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9775       !isConstVecPow2(ConstVec, isSigned, C))
9776     return SDValue();
9777
9778   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9779   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9780   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9781   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9782       NumLanes > 4) {
9783     // These instructions only exist converting from f32 to i32. We can handle
9784     // smaller integers by generating an extra truncate, but larger ones would
9785     // be lossy. We also can't handle more then 4 lanes, since these intructions
9786     // only support v2i32/v4i32 types.
9787     return SDValue();
9788   }
9789
9790   SDLoc dl(N);
9791   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9792     Intrinsic::arm_neon_vcvtfp2fxu;
9793   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9794                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9795                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9796                                  N0,
9797                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9798
9799   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9800     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9801
9802   return FixConv;
9803 }
9804
9805 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9806 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9807 /// when the VDIV has a constant operand that is a power of 2.
9808 ///
9809 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9810 ///  vcvt.f32.s32    d16, d16
9811 ///  vdiv.f32        d16, d17, d16
9812 /// becomes:
9813 ///  vcvt.f32.s32    d16, d16, #3
9814 static SDValue PerformVDIVCombine(SDNode *N,
9815                                   TargetLowering::DAGCombinerInfo &DCI,
9816                                   const ARMSubtarget *Subtarget) {
9817   SelectionDAG &DAG = DCI.DAG;
9818   SDValue Op = N->getOperand(0);
9819   unsigned OpOpcode = Op.getNode()->getOpcode();
9820
9821   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9822       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9823     return SDValue();
9824
9825   uint64_t C;
9826   SDValue ConstVec = N->getOperand(1);
9827   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9828
9829   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9830       !isConstVecPow2(ConstVec, isSigned, C))
9831     return SDValue();
9832
9833   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9834   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9835   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9836     // These instructions only exist converting from i32 to f32. We can handle
9837     // smaller integers by generating an extra extend, but larger ones would
9838     // be lossy.
9839     return SDValue();
9840   }
9841
9842   SDLoc dl(N);
9843   SDValue ConvInput = Op.getOperand(0);
9844   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9845   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9846     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9847                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9848                             ConvInput);
9849
9850   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9851     Intrinsic::arm_neon_vcvtfxu2fp;
9852   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9853                      Op.getValueType(),
9854                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9855                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9856 }
9857
9858 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9859 /// operand of a vector shift operation, where all the elements of the
9860 /// build_vector must have the same constant integer value.
9861 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9862   // Ignore bit_converts.
9863   while (Op.getOpcode() == ISD::BITCAST)
9864     Op = Op.getOperand(0);
9865   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9866   APInt SplatBits, SplatUndef;
9867   unsigned SplatBitSize;
9868   bool HasAnyUndefs;
9869   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9870                                       HasAnyUndefs, ElementBits) ||
9871       SplatBitSize > ElementBits)
9872     return false;
9873   Cnt = SplatBits.getSExtValue();
9874   return true;
9875 }
9876
9877 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9878 /// operand of a vector shift left operation.  That value must be in the range:
9879 ///   0 <= Value < ElementBits for a left shift; or
9880 ///   0 <= Value <= ElementBits for a long left shift.
9881 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9882   assert(VT.isVector() && "vector shift count is not a vector type");
9883   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9884   if (! getVShiftImm(Op, ElementBits, Cnt))
9885     return false;
9886   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9887 }
9888
9889 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9890 /// operand of a vector shift right operation.  For a shift opcode, the value
9891 /// is positive, but for an intrinsic the value count must be negative. The
9892 /// absolute value must be in the range:
9893 ///   1 <= |Value| <= ElementBits for a right shift; or
9894 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9895 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9896                          int64_t &Cnt) {
9897   assert(VT.isVector() && "vector shift count is not a vector type");
9898   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9899   if (! getVShiftImm(Op, ElementBits, Cnt))
9900     return false;
9901   if (!isIntrinsic)
9902     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9903   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9904     Cnt = -Cnt;
9905     return true;
9906   }
9907   return false;
9908 }
9909
9910 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9911 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9912   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9913   switch (IntNo) {
9914   default:
9915     // Don't do anything for most intrinsics.
9916     break;
9917
9918   case Intrinsic::arm_neon_vabds:
9919     if (!N->getValueType(0).isInteger())
9920       return SDValue();
9921     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9922                        N->getOperand(1), N->getOperand(2));
9923   case Intrinsic::arm_neon_vabdu:
9924     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9925                        N->getOperand(1), N->getOperand(2));
9926
9927   // Vector shifts: check for immediate versions and lower them.
9928   // Note: This is done during DAG combining instead of DAG legalizing because
9929   // the build_vectors for 64-bit vector element shift counts are generally
9930   // not legal, and it is hard to see their values after they get legalized to
9931   // loads from a constant pool.
9932   case Intrinsic::arm_neon_vshifts:
9933   case Intrinsic::arm_neon_vshiftu:
9934   case Intrinsic::arm_neon_vrshifts:
9935   case Intrinsic::arm_neon_vrshiftu:
9936   case Intrinsic::arm_neon_vrshiftn:
9937   case Intrinsic::arm_neon_vqshifts:
9938   case Intrinsic::arm_neon_vqshiftu:
9939   case Intrinsic::arm_neon_vqshiftsu:
9940   case Intrinsic::arm_neon_vqshiftns:
9941   case Intrinsic::arm_neon_vqshiftnu:
9942   case Intrinsic::arm_neon_vqshiftnsu:
9943   case Intrinsic::arm_neon_vqrshiftns:
9944   case Intrinsic::arm_neon_vqrshiftnu:
9945   case Intrinsic::arm_neon_vqrshiftnsu: {
9946     EVT VT = N->getOperand(1).getValueType();
9947     int64_t Cnt;
9948     unsigned VShiftOpc = 0;
9949
9950     switch (IntNo) {
9951     case Intrinsic::arm_neon_vshifts:
9952     case Intrinsic::arm_neon_vshiftu:
9953       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9954         VShiftOpc = ARMISD::VSHL;
9955         break;
9956       }
9957       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9958         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9959                      ARMISD::VSHRs : ARMISD::VSHRu);
9960         break;
9961       }
9962       return SDValue();
9963
9964     case Intrinsic::arm_neon_vrshifts:
9965     case Intrinsic::arm_neon_vrshiftu:
9966       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9967         break;
9968       return SDValue();
9969
9970     case Intrinsic::arm_neon_vqshifts:
9971     case Intrinsic::arm_neon_vqshiftu:
9972       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9973         break;
9974       return SDValue();
9975
9976     case Intrinsic::arm_neon_vqshiftsu:
9977       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9978         break;
9979       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9980
9981     case Intrinsic::arm_neon_vrshiftn:
9982     case Intrinsic::arm_neon_vqshiftns:
9983     case Intrinsic::arm_neon_vqshiftnu:
9984     case Intrinsic::arm_neon_vqshiftnsu:
9985     case Intrinsic::arm_neon_vqrshiftns:
9986     case Intrinsic::arm_neon_vqrshiftnu:
9987     case Intrinsic::arm_neon_vqrshiftnsu:
9988       // Narrowing shifts require an immediate right shift.
9989       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9990         break;
9991       llvm_unreachable("invalid shift count for narrowing vector shift "
9992                        "intrinsic");
9993
9994     default:
9995       llvm_unreachable("unhandled vector shift");
9996     }
9997
9998     switch (IntNo) {
9999     case Intrinsic::arm_neon_vshifts:
10000     case Intrinsic::arm_neon_vshiftu:
10001       // Opcode already set above.
10002       break;
10003     case Intrinsic::arm_neon_vrshifts:
10004       VShiftOpc = ARMISD::VRSHRs; break;
10005     case Intrinsic::arm_neon_vrshiftu:
10006       VShiftOpc = ARMISD::VRSHRu; break;
10007     case Intrinsic::arm_neon_vrshiftn:
10008       VShiftOpc = ARMISD::VRSHRN; break;
10009     case Intrinsic::arm_neon_vqshifts:
10010       VShiftOpc = ARMISD::VQSHLs; break;
10011     case Intrinsic::arm_neon_vqshiftu:
10012       VShiftOpc = ARMISD::VQSHLu; break;
10013     case Intrinsic::arm_neon_vqshiftsu:
10014       VShiftOpc = ARMISD::VQSHLsu; break;
10015     case Intrinsic::arm_neon_vqshiftns:
10016       VShiftOpc = ARMISD::VQSHRNs; break;
10017     case Intrinsic::arm_neon_vqshiftnu:
10018       VShiftOpc = ARMISD::VQSHRNu; break;
10019     case Intrinsic::arm_neon_vqshiftnsu:
10020       VShiftOpc = ARMISD::VQSHRNsu; break;
10021     case Intrinsic::arm_neon_vqrshiftns:
10022       VShiftOpc = ARMISD::VQRSHRNs; break;
10023     case Intrinsic::arm_neon_vqrshiftnu:
10024       VShiftOpc = ARMISD::VQRSHRNu; break;
10025     case Intrinsic::arm_neon_vqrshiftnsu:
10026       VShiftOpc = ARMISD::VQRSHRNsu; break;
10027     }
10028
10029     SDLoc dl(N);
10030     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10031                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10032   }
10033
10034   case Intrinsic::arm_neon_vshiftins: {
10035     EVT VT = N->getOperand(1).getValueType();
10036     int64_t Cnt;
10037     unsigned VShiftOpc = 0;
10038
10039     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10040       VShiftOpc = ARMISD::VSLI;
10041     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10042       VShiftOpc = ARMISD::VSRI;
10043     else {
10044       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10045     }
10046
10047     SDLoc dl(N);
10048     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10049                        N->getOperand(1), N->getOperand(2),
10050                        DAG.getConstant(Cnt, dl, MVT::i32));
10051   }
10052
10053   case Intrinsic::arm_neon_vqrshifts:
10054   case Intrinsic::arm_neon_vqrshiftu:
10055     // No immediate versions of these to check for.
10056     break;
10057   }
10058
10059   return SDValue();
10060 }
10061
10062 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10063 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
10064 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10065 /// vector element shift counts are generally not legal, and it is hard to see
10066 /// their values after they get legalized to loads from a constant pool.
10067 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10068                                    const ARMSubtarget *ST) {
10069   EVT VT = N->getValueType(0);
10070   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10071     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10072     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10073     SDValue N1 = N->getOperand(1);
10074     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10075       SDValue N0 = N->getOperand(0);
10076       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10077           DAG.MaskedValueIsZero(N0.getOperand(0),
10078                                 APInt::getHighBitsSet(32, 16)))
10079         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10080     }
10081   }
10082
10083   // Nothing to be done for scalar shifts.
10084   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10085   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10086     return SDValue();
10087
10088   assert(ST->hasNEON() && "unexpected vector shift");
10089   int64_t Cnt;
10090
10091   switch (N->getOpcode()) {
10092   default: llvm_unreachable("unexpected shift opcode");
10093
10094   case ISD::SHL:
10095     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10096       SDLoc dl(N);
10097       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10098                          DAG.getConstant(Cnt, dl, MVT::i32));
10099     }
10100     break;
10101
10102   case ISD::SRA:
10103   case ISD::SRL:
10104     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10105       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10106                             ARMISD::VSHRs : ARMISD::VSHRu);
10107       SDLoc dl(N);
10108       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10109                          DAG.getConstant(Cnt, dl, MVT::i32));
10110     }
10111   }
10112   return SDValue();
10113 }
10114
10115 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10116 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10117 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10118                                     const ARMSubtarget *ST) {
10119   SDValue N0 = N->getOperand(0);
10120
10121   // Check for sign- and zero-extensions of vector extract operations of 8-
10122   // and 16-bit vector elements.  NEON supports these directly.  They are
10123   // handled during DAG combining because type legalization will promote them
10124   // to 32-bit types and it is messy to recognize the operations after that.
10125   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10126     SDValue Vec = N0.getOperand(0);
10127     SDValue Lane = N0.getOperand(1);
10128     EVT VT = N->getValueType(0);
10129     EVT EltVT = N0.getValueType();
10130     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10131
10132     if (VT == MVT::i32 &&
10133         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10134         TLI.isTypeLegal(Vec.getValueType()) &&
10135         isa<ConstantSDNode>(Lane)) {
10136
10137       unsigned Opc = 0;
10138       switch (N->getOpcode()) {
10139       default: llvm_unreachable("unexpected opcode");
10140       case ISD::SIGN_EXTEND:
10141         Opc = ARMISD::VGETLANEs;
10142         break;
10143       case ISD::ZERO_EXTEND:
10144       case ISD::ANY_EXTEND:
10145         Opc = ARMISD::VGETLANEu;
10146         break;
10147       }
10148       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10149     }
10150   }
10151
10152   return SDValue();
10153 }
10154
10155 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
10156 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
10157 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
10158                                        const ARMSubtarget *ST) {
10159   // If the target supports NEON, try to use vmax/vmin instructions for f32
10160   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
10161   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
10162   // a NaN; only do the transformation when it matches that behavior.
10163
10164   // For now only do this when using NEON for FP operations; if using VFP, it
10165   // is not obvious that the benefit outweighs the cost of switching to the
10166   // NEON pipeline.
10167   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
10168       N->getValueType(0) != MVT::f32)
10169     return SDValue();
10170
10171   SDValue CondLHS = N->getOperand(0);
10172   SDValue CondRHS = N->getOperand(1);
10173   SDValue LHS = N->getOperand(2);
10174   SDValue RHS = N->getOperand(3);
10175   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
10176
10177   unsigned Opcode = 0;
10178   bool IsReversed;
10179   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
10180     IsReversed = false; // x CC y ? x : y
10181   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
10182     IsReversed = true ; // x CC y ? y : x
10183   } else {
10184     return SDValue();
10185   }
10186
10187   bool IsUnordered;
10188   switch (CC) {
10189   default: break;
10190   case ISD::SETOLT:
10191   case ISD::SETOLE:
10192   case ISD::SETLT:
10193   case ISD::SETLE:
10194   case ISD::SETULT:
10195   case ISD::SETULE:
10196     // If LHS is NaN, an ordered comparison will be false and the result will
10197     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
10198     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10199     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10200     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10201       break;
10202     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10203     // will return -0, so vmin can only be used for unsafe math or if one of
10204     // the operands is known to be nonzero.
10205     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10206         !DAG.getTarget().Options.UnsafeFPMath &&
10207         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10208       break;
10209     Opcode = IsReversed ? ISD::FMAXNAN : ISD::FMINNAN;
10210     break;
10211
10212   case ISD::SETOGT:
10213   case ISD::SETOGE:
10214   case ISD::SETGT:
10215   case ISD::SETGE:
10216   case ISD::SETUGT:
10217   case ISD::SETUGE:
10218     // If LHS is NaN, an ordered comparison will be false and the result will
10219     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
10220     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10221     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10222     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10223       break;
10224     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10225     // will return +0, so vmax can only be used for unsafe math or if one of
10226     // the operands is known to be nonzero.
10227     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10228         !DAG.getTarget().Options.UnsafeFPMath &&
10229         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10230       break;
10231     Opcode = IsReversed ? ISD::FMINNAN : ISD::FMAXNAN;
10232     break;
10233   }
10234
10235   if (!Opcode)
10236     return SDValue();
10237   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10238 }
10239
10240 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10241 SDValue
10242 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10243   SDValue Cmp = N->getOperand(4);
10244   if (Cmp.getOpcode() != ARMISD::CMPZ)
10245     // Only looking at EQ and NE cases.
10246     return SDValue();
10247
10248   EVT VT = N->getValueType(0);
10249   SDLoc dl(N);
10250   SDValue LHS = Cmp.getOperand(0);
10251   SDValue RHS = Cmp.getOperand(1);
10252   SDValue FalseVal = N->getOperand(0);
10253   SDValue TrueVal = N->getOperand(1);
10254   SDValue ARMcc = N->getOperand(2);
10255   ARMCC::CondCodes CC =
10256     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10257
10258   // Simplify
10259   //   mov     r1, r0
10260   //   cmp     r1, x
10261   //   mov     r0, y
10262   //   moveq   r0, x
10263   // to
10264   //   cmp     r0, x
10265   //   movne   r0, y
10266   //
10267   //   mov     r1, r0
10268   //   cmp     r1, x
10269   //   mov     r0, x
10270   //   movne   r0, y
10271   // to
10272   //   cmp     r0, x
10273   //   movne   r0, y
10274   /// FIXME: Turn this into a target neutral optimization?
10275   SDValue Res;
10276   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10277     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10278                       N->getOperand(3), Cmp);
10279   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10280     SDValue ARMcc;
10281     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10282     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10283                       N->getOperand(3), NewCmp);
10284   }
10285
10286   if (Res.getNode()) {
10287     APInt KnownZero, KnownOne;
10288     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10289     // Capture demanded bits information that would be otherwise lost.
10290     if (KnownZero == 0xfffffffe)
10291       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10292                         DAG.getValueType(MVT::i1));
10293     else if (KnownZero == 0xffffff00)
10294       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10295                         DAG.getValueType(MVT::i8));
10296     else if (KnownZero == 0xffff0000)
10297       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10298                         DAG.getValueType(MVT::i16));
10299   }
10300
10301   return Res;
10302 }
10303
10304 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10305                                              DAGCombinerInfo &DCI) const {
10306   switch (N->getOpcode()) {
10307   default: break;
10308   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10309   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10310   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10311   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10312   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10313   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10314   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10315   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10316   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10317   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10318   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10319   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10320   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10321   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10322   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10323   case ISD::FP_TO_SINT:
10324   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10325   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10326   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10327   case ISD::SHL:
10328   case ISD::SRA:
10329   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10330   case ISD::SIGN_EXTEND:
10331   case ISD::ZERO_EXTEND:
10332   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10333   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10334   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10335   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10336   case ARMISD::VLD2DUP:
10337   case ARMISD::VLD3DUP:
10338   case ARMISD::VLD4DUP:
10339     return PerformVLDCombine(N, DCI);
10340   case ARMISD::BUILD_VECTOR:
10341     return PerformARMBUILD_VECTORCombine(N, DCI);
10342   case ISD::INTRINSIC_VOID:
10343   case ISD::INTRINSIC_W_CHAIN:
10344     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10345     case Intrinsic::arm_neon_vld1:
10346     case Intrinsic::arm_neon_vld2:
10347     case Intrinsic::arm_neon_vld3:
10348     case Intrinsic::arm_neon_vld4:
10349     case Intrinsic::arm_neon_vld2lane:
10350     case Intrinsic::arm_neon_vld3lane:
10351     case Intrinsic::arm_neon_vld4lane:
10352     case Intrinsic::arm_neon_vst1:
10353     case Intrinsic::arm_neon_vst2:
10354     case Intrinsic::arm_neon_vst3:
10355     case Intrinsic::arm_neon_vst4:
10356     case Intrinsic::arm_neon_vst2lane:
10357     case Intrinsic::arm_neon_vst3lane:
10358     case Intrinsic::arm_neon_vst4lane:
10359       return PerformVLDCombine(N, DCI);
10360     default: break;
10361     }
10362     break;
10363   }
10364   return SDValue();
10365 }
10366
10367 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10368                                                           EVT VT) const {
10369   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10370 }
10371
10372 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10373                                                        unsigned,
10374                                                        unsigned,
10375                                                        bool *Fast) const {
10376   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10377   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10378
10379   switch (VT.getSimpleVT().SimpleTy) {
10380   default:
10381     return false;
10382   case MVT::i8:
10383   case MVT::i16:
10384   case MVT::i32: {
10385     // Unaligned access can use (for example) LRDB, LRDH, LDR
10386     if (AllowsUnaligned) {
10387       if (Fast)
10388         *Fast = Subtarget->hasV7Ops();
10389       return true;
10390     }
10391     return false;
10392   }
10393   case MVT::f64:
10394   case MVT::v2f64: {
10395     // For any little-endian targets with neon, we can support unaligned ld/st
10396     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10397     // A big-endian target may also explicitly support unaligned accesses
10398     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10399       if (Fast)
10400         *Fast = true;
10401       return true;
10402     }
10403     return false;
10404   }
10405   }
10406 }
10407
10408 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10409                        unsigned AlignCheck) {
10410   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10411           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10412 }
10413
10414 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10415                                            unsigned DstAlign, unsigned SrcAlign,
10416                                            bool IsMemset, bool ZeroMemset,
10417                                            bool MemcpyStrSrc,
10418                                            MachineFunction &MF) const {
10419   const Function *F = MF.getFunction();
10420
10421   // See if we can use NEON instructions for this...
10422   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10423       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10424     bool Fast;
10425     if (Size >= 16 &&
10426         (memOpAlign(SrcAlign, DstAlign, 16) ||
10427          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10428       return MVT::v2f64;
10429     } else if (Size >= 8 &&
10430                (memOpAlign(SrcAlign, DstAlign, 8) ||
10431                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10432                  Fast))) {
10433       return MVT::f64;
10434     }
10435   }
10436
10437   // Lowering to i32/i16 if the size permits.
10438   if (Size >= 4)
10439     return MVT::i32;
10440   else if (Size >= 2)
10441     return MVT::i16;
10442
10443   // Let the target-independent logic figure it out.
10444   return MVT::Other;
10445 }
10446
10447 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10448   if (Val.getOpcode() != ISD::LOAD)
10449     return false;
10450
10451   EVT VT1 = Val.getValueType();
10452   if (!VT1.isSimple() || !VT1.isInteger() ||
10453       !VT2.isSimple() || !VT2.isInteger())
10454     return false;
10455
10456   switch (VT1.getSimpleVT().SimpleTy) {
10457   default: break;
10458   case MVT::i1:
10459   case MVT::i8:
10460   case MVT::i16:
10461     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10462     return true;
10463   }
10464
10465   return false;
10466 }
10467
10468 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10469   EVT VT = ExtVal.getValueType();
10470
10471   if (!isTypeLegal(VT))
10472     return false;
10473
10474   // Don't create a loadext if we can fold the extension into a wide/long
10475   // instruction.
10476   // If there's more than one user instruction, the loadext is desirable no
10477   // matter what.  There can be two uses by the same instruction.
10478   if (ExtVal->use_empty() ||
10479       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10480     return true;
10481
10482   SDNode *U = *ExtVal->use_begin();
10483   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10484        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10485     return false;
10486
10487   return true;
10488 }
10489
10490 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10491   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10492     return false;
10493
10494   if (!isTypeLegal(EVT::getEVT(Ty1)))
10495     return false;
10496
10497   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10498
10499   // Assuming the caller doesn't have a zeroext or signext return parameter,
10500   // truncation all the way down to i1 is valid.
10501   return true;
10502 }
10503
10504
10505 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10506   if (V < 0)
10507     return false;
10508
10509   unsigned Scale = 1;
10510   switch (VT.getSimpleVT().SimpleTy) {
10511   default: return false;
10512   case MVT::i1:
10513   case MVT::i8:
10514     // Scale == 1;
10515     break;
10516   case MVT::i16:
10517     // Scale == 2;
10518     Scale = 2;
10519     break;
10520   case MVT::i32:
10521     // Scale == 4;
10522     Scale = 4;
10523     break;
10524   }
10525
10526   if ((V & (Scale - 1)) != 0)
10527     return false;
10528   V /= Scale;
10529   return V == (V & ((1LL << 5) - 1));
10530 }
10531
10532 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10533                                       const ARMSubtarget *Subtarget) {
10534   bool isNeg = false;
10535   if (V < 0) {
10536     isNeg = true;
10537     V = - V;
10538   }
10539
10540   switch (VT.getSimpleVT().SimpleTy) {
10541   default: return false;
10542   case MVT::i1:
10543   case MVT::i8:
10544   case MVT::i16:
10545   case MVT::i32:
10546     // + imm12 or - imm8
10547     if (isNeg)
10548       return V == (V & ((1LL << 8) - 1));
10549     return V == (V & ((1LL << 12) - 1));
10550   case MVT::f32:
10551   case MVT::f64:
10552     // Same as ARM mode. FIXME: NEON?
10553     if (!Subtarget->hasVFP2())
10554       return false;
10555     if ((V & 3) != 0)
10556       return false;
10557     V >>= 2;
10558     return V == (V & ((1LL << 8) - 1));
10559   }
10560 }
10561
10562 /// isLegalAddressImmediate - Return true if the integer value can be used
10563 /// as the offset of the target addressing mode for load / store of the
10564 /// given type.
10565 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10566                                     const ARMSubtarget *Subtarget) {
10567   if (V == 0)
10568     return true;
10569
10570   if (!VT.isSimple())
10571     return false;
10572
10573   if (Subtarget->isThumb1Only())
10574     return isLegalT1AddressImmediate(V, VT);
10575   else if (Subtarget->isThumb2())
10576     return isLegalT2AddressImmediate(V, VT, Subtarget);
10577
10578   // ARM mode.
10579   if (V < 0)
10580     V = - V;
10581   switch (VT.getSimpleVT().SimpleTy) {
10582   default: return false;
10583   case MVT::i1:
10584   case MVT::i8:
10585   case MVT::i32:
10586     // +- imm12
10587     return V == (V & ((1LL << 12) - 1));
10588   case MVT::i16:
10589     // +- imm8
10590     return V == (V & ((1LL << 8) - 1));
10591   case MVT::f32:
10592   case MVT::f64:
10593     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10594       return false;
10595     if ((V & 3) != 0)
10596       return false;
10597     V >>= 2;
10598     return V == (V & ((1LL << 8) - 1));
10599   }
10600 }
10601
10602 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10603                                                       EVT VT) const {
10604   int Scale = AM.Scale;
10605   if (Scale < 0)
10606     return false;
10607
10608   switch (VT.getSimpleVT().SimpleTy) {
10609   default: return false;
10610   case MVT::i1:
10611   case MVT::i8:
10612   case MVT::i16:
10613   case MVT::i32:
10614     if (Scale == 1)
10615       return true;
10616     // r + r << imm
10617     Scale = Scale & ~1;
10618     return Scale == 2 || Scale == 4 || Scale == 8;
10619   case MVT::i64:
10620     // r + r
10621     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10622       return true;
10623     return false;
10624   case MVT::isVoid:
10625     // Note, we allow "void" uses (basically, uses that aren't loads or
10626     // stores), because arm allows folding a scale into many arithmetic
10627     // operations.  This should be made more precise and revisited later.
10628
10629     // Allow r << imm, but the imm has to be a multiple of two.
10630     if (Scale & 1) return false;
10631     return isPowerOf2_32(Scale);
10632   }
10633 }
10634
10635 /// isLegalAddressingMode - Return true if the addressing mode represented
10636 /// by AM is legal for this target, for a load/store of the specified type.
10637 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10638                                               const AddrMode &AM, Type *Ty,
10639                                               unsigned AS) const {
10640   EVT VT = getValueType(DL, Ty, true);
10641   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10642     return false;
10643
10644   // Can never fold addr of global into load/store.
10645   if (AM.BaseGV)
10646     return false;
10647
10648   switch (AM.Scale) {
10649   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10650     break;
10651   case 1:
10652     if (Subtarget->isThumb1Only())
10653       return false;
10654     // FALL THROUGH.
10655   default:
10656     // ARM doesn't support any R+R*scale+imm addr modes.
10657     if (AM.BaseOffs)
10658       return false;
10659
10660     if (!VT.isSimple())
10661       return false;
10662
10663     if (Subtarget->isThumb2())
10664       return isLegalT2ScaledAddressingMode(AM, VT);
10665
10666     int Scale = AM.Scale;
10667     switch (VT.getSimpleVT().SimpleTy) {
10668     default: return false;
10669     case MVT::i1:
10670     case MVT::i8:
10671     case MVT::i32:
10672       if (Scale < 0) Scale = -Scale;
10673       if (Scale == 1)
10674         return true;
10675       // r + r << imm
10676       return isPowerOf2_32(Scale & ~1);
10677     case MVT::i16:
10678     case MVT::i64:
10679       // r + r
10680       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10681         return true;
10682       return false;
10683
10684     case MVT::isVoid:
10685       // Note, we allow "void" uses (basically, uses that aren't loads or
10686       // stores), because arm allows folding a scale into many arithmetic
10687       // operations.  This should be made more precise and revisited later.
10688
10689       // Allow r << imm, but the imm has to be a multiple of two.
10690       if (Scale & 1) return false;
10691       return isPowerOf2_32(Scale);
10692     }
10693   }
10694   return true;
10695 }
10696
10697 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10698 /// icmp immediate, that is the target has icmp instructions which can compare
10699 /// a register against the immediate without having to materialize the
10700 /// immediate into a register.
10701 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10702   // Thumb2 and ARM modes can use cmn for negative immediates.
10703   if (!Subtarget->isThumb())
10704     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10705   if (Subtarget->isThumb2())
10706     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10707   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10708   return Imm >= 0 && Imm <= 255;
10709 }
10710
10711 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10712 /// *or sub* immediate, that is the target has add or sub instructions which can
10713 /// add a register with the immediate without having to materialize the
10714 /// immediate into a register.
10715 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10716   // Same encoding for add/sub, just flip the sign.
10717   int64_t AbsImm = std::abs(Imm);
10718   if (!Subtarget->isThumb())
10719     return ARM_AM::getSOImmVal(AbsImm) != -1;
10720   if (Subtarget->isThumb2())
10721     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10722   // Thumb1 only has 8-bit unsigned immediate.
10723   return AbsImm >= 0 && AbsImm <= 255;
10724 }
10725
10726 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10727                                       bool isSEXTLoad, SDValue &Base,
10728                                       SDValue &Offset, bool &isInc,
10729                                       SelectionDAG &DAG) {
10730   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10731     return false;
10732
10733   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10734     // AddressingMode 3
10735     Base = Ptr->getOperand(0);
10736     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10737       int RHSC = (int)RHS->getZExtValue();
10738       if (RHSC < 0 && RHSC > -256) {
10739         assert(Ptr->getOpcode() == ISD::ADD);
10740         isInc = false;
10741         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10742         return true;
10743       }
10744     }
10745     isInc = (Ptr->getOpcode() == ISD::ADD);
10746     Offset = Ptr->getOperand(1);
10747     return true;
10748   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10749     // AddressingMode 2
10750     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10751       int RHSC = (int)RHS->getZExtValue();
10752       if (RHSC < 0 && RHSC > -0x1000) {
10753         assert(Ptr->getOpcode() == ISD::ADD);
10754         isInc = false;
10755         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10756         Base = Ptr->getOperand(0);
10757         return true;
10758       }
10759     }
10760
10761     if (Ptr->getOpcode() == ISD::ADD) {
10762       isInc = true;
10763       ARM_AM::ShiftOpc ShOpcVal=
10764         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10765       if (ShOpcVal != ARM_AM::no_shift) {
10766         Base = Ptr->getOperand(1);
10767         Offset = Ptr->getOperand(0);
10768       } else {
10769         Base = Ptr->getOperand(0);
10770         Offset = Ptr->getOperand(1);
10771       }
10772       return true;
10773     }
10774
10775     isInc = (Ptr->getOpcode() == ISD::ADD);
10776     Base = Ptr->getOperand(0);
10777     Offset = Ptr->getOperand(1);
10778     return true;
10779   }
10780
10781   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10782   return false;
10783 }
10784
10785 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10786                                      bool isSEXTLoad, SDValue &Base,
10787                                      SDValue &Offset, bool &isInc,
10788                                      SelectionDAG &DAG) {
10789   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10790     return false;
10791
10792   Base = Ptr->getOperand(0);
10793   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10794     int RHSC = (int)RHS->getZExtValue();
10795     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10796       assert(Ptr->getOpcode() == ISD::ADD);
10797       isInc = false;
10798       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10799       return true;
10800     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10801       isInc = Ptr->getOpcode() == ISD::ADD;
10802       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10803       return true;
10804     }
10805   }
10806
10807   return false;
10808 }
10809
10810 /// getPreIndexedAddressParts - returns true by value, base pointer and
10811 /// offset pointer and addressing mode by reference if the node's address
10812 /// can be legally represented as pre-indexed load / store address.
10813 bool
10814 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10815                                              SDValue &Offset,
10816                                              ISD::MemIndexedMode &AM,
10817                                              SelectionDAG &DAG) const {
10818   if (Subtarget->isThumb1Only())
10819     return false;
10820
10821   EVT VT;
10822   SDValue Ptr;
10823   bool isSEXTLoad = false;
10824   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10825     Ptr = LD->getBasePtr();
10826     VT  = LD->getMemoryVT();
10827     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10828   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10829     Ptr = ST->getBasePtr();
10830     VT  = ST->getMemoryVT();
10831   } else
10832     return false;
10833
10834   bool isInc;
10835   bool isLegal = false;
10836   if (Subtarget->isThumb2())
10837     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10838                                        Offset, isInc, DAG);
10839   else
10840     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10841                                         Offset, isInc, DAG);
10842   if (!isLegal)
10843     return false;
10844
10845   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10846   return true;
10847 }
10848
10849 /// getPostIndexedAddressParts - returns true by value, base pointer and
10850 /// offset pointer and addressing mode by reference if this node can be
10851 /// combined with a load / store to form a post-indexed load / store.
10852 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10853                                                    SDValue &Base,
10854                                                    SDValue &Offset,
10855                                                    ISD::MemIndexedMode &AM,
10856                                                    SelectionDAG &DAG) const {
10857   if (Subtarget->isThumb1Only())
10858     return false;
10859
10860   EVT VT;
10861   SDValue Ptr;
10862   bool isSEXTLoad = false;
10863   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10864     VT  = LD->getMemoryVT();
10865     Ptr = LD->getBasePtr();
10866     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10867   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10868     VT  = ST->getMemoryVT();
10869     Ptr = ST->getBasePtr();
10870   } else
10871     return false;
10872
10873   bool isInc;
10874   bool isLegal = false;
10875   if (Subtarget->isThumb2())
10876     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10877                                        isInc, DAG);
10878   else
10879     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10880                                         isInc, DAG);
10881   if (!isLegal)
10882     return false;
10883
10884   if (Ptr != Base) {
10885     // Swap base ptr and offset to catch more post-index load / store when
10886     // it's legal. In Thumb2 mode, offset must be an immediate.
10887     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10888         !Subtarget->isThumb2())
10889       std::swap(Base, Offset);
10890
10891     // Post-indexed load / store update the base pointer.
10892     if (Ptr != Base)
10893       return false;
10894   }
10895
10896   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10897   return true;
10898 }
10899
10900 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10901                                                       APInt &KnownZero,
10902                                                       APInt &KnownOne,
10903                                                       const SelectionDAG &DAG,
10904                                                       unsigned Depth) const {
10905   unsigned BitWidth = KnownOne.getBitWidth();
10906   KnownZero = KnownOne = APInt(BitWidth, 0);
10907   switch (Op.getOpcode()) {
10908   default: break;
10909   case ARMISD::ADDC:
10910   case ARMISD::ADDE:
10911   case ARMISD::SUBC:
10912   case ARMISD::SUBE:
10913     // These nodes' second result is a boolean
10914     if (Op.getResNo() == 0)
10915       break;
10916     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10917     break;
10918   case ARMISD::CMOV: {
10919     // Bits are known zero/one if known on the LHS and RHS.
10920     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10921     if (KnownZero == 0 && KnownOne == 0) return;
10922
10923     APInt KnownZeroRHS, KnownOneRHS;
10924     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10925     KnownZero &= KnownZeroRHS;
10926     KnownOne  &= KnownOneRHS;
10927     return;
10928   }
10929   case ISD::INTRINSIC_W_CHAIN: {
10930     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10931     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10932     switch (IntID) {
10933     default: return;
10934     case Intrinsic::arm_ldaex:
10935     case Intrinsic::arm_ldrex: {
10936       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10937       unsigned MemBits = VT.getScalarType().getSizeInBits();
10938       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10939       return;
10940     }
10941     }
10942   }
10943   }
10944 }
10945
10946 //===----------------------------------------------------------------------===//
10947 //                           ARM Inline Assembly Support
10948 //===----------------------------------------------------------------------===//
10949
10950 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10951   // Looking for "rev" which is V6+.
10952   if (!Subtarget->hasV6Ops())
10953     return false;
10954
10955   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10956   std::string AsmStr = IA->getAsmString();
10957   SmallVector<StringRef, 4> AsmPieces;
10958   SplitString(AsmStr, AsmPieces, ";\n");
10959
10960   switch (AsmPieces.size()) {
10961   default: return false;
10962   case 1:
10963     AsmStr = AsmPieces[0];
10964     AsmPieces.clear();
10965     SplitString(AsmStr, AsmPieces, " \t,");
10966
10967     // rev $0, $1
10968     if (AsmPieces.size() == 3 &&
10969         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10970         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10971       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10972       if (Ty && Ty->getBitWidth() == 32)
10973         return IntrinsicLowering::LowerToByteSwap(CI);
10974     }
10975     break;
10976   }
10977
10978   return false;
10979 }
10980
10981 /// getConstraintType - Given a constraint letter, return the type of
10982 /// constraint it is for this target.
10983 ARMTargetLowering::ConstraintType
10984 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10985   if (Constraint.size() == 1) {
10986     switch (Constraint[0]) {
10987     default:  break;
10988     case 'l': return C_RegisterClass;
10989     case 'w': return C_RegisterClass;
10990     case 'h': return C_RegisterClass;
10991     case 'x': return C_RegisterClass;
10992     case 't': return C_RegisterClass;
10993     case 'j': return C_Other; // Constant for movw.
10994       // An address with a single base register. Due to the way we
10995       // currently handle addresses it is the same as an 'r' memory constraint.
10996     case 'Q': return C_Memory;
10997     }
10998   } else if (Constraint.size() == 2) {
10999     switch (Constraint[0]) {
11000     default: break;
11001     // All 'U+' constraints are addresses.
11002     case 'U': return C_Memory;
11003     }
11004   }
11005   return TargetLowering::getConstraintType(Constraint);
11006 }
11007
11008 /// Examine constraint type and operand type and determine a weight value.
11009 /// This object must already have been set up with the operand type
11010 /// and the current alternative constraint selected.
11011 TargetLowering::ConstraintWeight
11012 ARMTargetLowering::getSingleConstraintMatchWeight(
11013     AsmOperandInfo &info, const char *constraint) const {
11014   ConstraintWeight weight = CW_Invalid;
11015   Value *CallOperandVal = info.CallOperandVal;
11016     // If we don't have a value, we can't do a match,
11017     // but allow it at the lowest weight.
11018   if (!CallOperandVal)
11019     return CW_Default;
11020   Type *type = CallOperandVal->getType();
11021   // Look at the constraint type.
11022   switch (*constraint) {
11023   default:
11024     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11025     break;
11026   case 'l':
11027     if (type->isIntegerTy()) {
11028       if (Subtarget->isThumb())
11029         weight = CW_SpecificReg;
11030       else
11031         weight = CW_Register;
11032     }
11033     break;
11034   case 'w':
11035     if (type->isFloatingPointTy())
11036       weight = CW_Register;
11037     break;
11038   }
11039   return weight;
11040 }
11041
11042 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11043 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11044     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11045   if (Constraint.size() == 1) {
11046     // GCC ARM Constraint Letters
11047     switch (Constraint[0]) {
11048     case 'l': // Low regs or general regs.
11049       if (Subtarget->isThumb())
11050         return RCPair(0U, &ARM::tGPRRegClass);
11051       return RCPair(0U, &ARM::GPRRegClass);
11052     case 'h': // High regs or no regs.
11053       if (Subtarget->isThumb())
11054         return RCPair(0U, &ARM::hGPRRegClass);
11055       break;
11056     case 'r':
11057       if (Subtarget->isThumb1Only())
11058         return RCPair(0U, &ARM::tGPRRegClass);
11059       return RCPair(0U, &ARM::GPRRegClass);
11060     case 'w':
11061       if (VT == MVT::Other)
11062         break;
11063       if (VT == MVT::f32)
11064         return RCPair(0U, &ARM::SPRRegClass);
11065       if (VT.getSizeInBits() == 64)
11066         return RCPair(0U, &ARM::DPRRegClass);
11067       if (VT.getSizeInBits() == 128)
11068         return RCPair(0U, &ARM::QPRRegClass);
11069       break;
11070     case 'x':
11071       if (VT == MVT::Other)
11072         break;
11073       if (VT == MVT::f32)
11074         return RCPair(0U, &ARM::SPR_8RegClass);
11075       if (VT.getSizeInBits() == 64)
11076         return RCPair(0U, &ARM::DPR_8RegClass);
11077       if (VT.getSizeInBits() == 128)
11078         return RCPair(0U, &ARM::QPR_8RegClass);
11079       break;
11080     case 't':
11081       if (VT == MVT::f32)
11082         return RCPair(0U, &ARM::SPRRegClass);
11083       break;
11084     }
11085   }
11086   if (StringRef("{cc}").equals_lower(Constraint))
11087     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11088
11089   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11090 }
11091
11092 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11093 /// vector.  If it is invalid, don't add anything to Ops.
11094 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11095                                                      std::string &Constraint,
11096                                                      std::vector<SDValue>&Ops,
11097                                                      SelectionDAG &DAG) const {
11098   SDValue Result;
11099
11100   // Currently only support length 1 constraints.
11101   if (Constraint.length() != 1) return;
11102
11103   char ConstraintLetter = Constraint[0];
11104   switch (ConstraintLetter) {
11105   default: break;
11106   case 'j':
11107   case 'I': case 'J': case 'K': case 'L':
11108   case 'M': case 'N': case 'O':
11109     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11110     if (!C)
11111       return;
11112
11113     int64_t CVal64 = C->getSExtValue();
11114     int CVal = (int) CVal64;
11115     // None of these constraints allow values larger than 32 bits.  Check
11116     // that the value fits in an int.
11117     if (CVal != CVal64)
11118       return;
11119
11120     switch (ConstraintLetter) {
11121       case 'j':
11122         // Constant suitable for movw, must be between 0 and
11123         // 65535.
11124         if (Subtarget->hasV6T2Ops())
11125           if (CVal >= 0 && CVal <= 65535)
11126             break;
11127         return;
11128       case 'I':
11129         if (Subtarget->isThumb1Only()) {
11130           // This must be a constant between 0 and 255, for ADD
11131           // immediates.
11132           if (CVal >= 0 && CVal <= 255)
11133             break;
11134         } else if (Subtarget->isThumb2()) {
11135           // A constant that can be used as an immediate value in a
11136           // data-processing instruction.
11137           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11138             break;
11139         } else {
11140           // A constant that can be used as an immediate value in a
11141           // data-processing instruction.
11142           if (ARM_AM::getSOImmVal(CVal) != -1)
11143             break;
11144         }
11145         return;
11146
11147       case 'J':
11148         if (Subtarget->isThumb()) {  // FIXME thumb2
11149           // This must be a constant between -255 and -1, for negated ADD
11150           // immediates. This can be used in GCC with an "n" modifier that
11151           // prints the negated value, for use with SUB instructions. It is
11152           // not useful otherwise but is implemented for compatibility.
11153           if (CVal >= -255 && CVal <= -1)
11154             break;
11155         } else {
11156           // This must be a constant between -4095 and 4095. It is not clear
11157           // what this constraint is intended for. Implemented for
11158           // compatibility with GCC.
11159           if (CVal >= -4095 && CVal <= 4095)
11160             break;
11161         }
11162         return;
11163
11164       case 'K':
11165         if (Subtarget->isThumb1Only()) {
11166           // A 32-bit value where only one byte has a nonzero value. Exclude
11167           // zero to match GCC. This constraint is used by GCC internally for
11168           // constants that can be loaded with a move/shift combination.
11169           // It is not useful otherwise but is implemented for compatibility.
11170           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11171             break;
11172         } else if (Subtarget->isThumb2()) {
11173           // A constant whose bitwise inverse can be used as an immediate
11174           // value in a data-processing instruction. This can be used in GCC
11175           // with a "B" modifier that prints the inverted value, for use with
11176           // BIC and MVN instructions. It is not useful otherwise but is
11177           // implemented for compatibility.
11178           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11179             break;
11180         } else {
11181           // A constant whose bitwise inverse can be used as an immediate
11182           // value in a data-processing instruction. This can be used in GCC
11183           // with a "B" modifier that prints the inverted value, for use with
11184           // BIC and MVN instructions. It is not useful otherwise but is
11185           // implemented for compatibility.
11186           if (ARM_AM::getSOImmVal(~CVal) != -1)
11187             break;
11188         }
11189         return;
11190
11191       case 'L':
11192         if (Subtarget->isThumb1Only()) {
11193           // This must be a constant between -7 and 7,
11194           // for 3-operand ADD/SUB immediate instructions.
11195           if (CVal >= -7 && CVal < 7)
11196             break;
11197         } else if (Subtarget->isThumb2()) {
11198           // A constant whose negation can be used as an immediate value in a
11199           // data-processing instruction. This can be used in GCC with an "n"
11200           // modifier that prints the negated value, for use with SUB
11201           // instructions. It is not useful otherwise but is implemented for
11202           // compatibility.
11203           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11204             break;
11205         } else {
11206           // A constant whose negation can be used as an immediate value in a
11207           // data-processing instruction. This can be used in GCC with an "n"
11208           // modifier that prints the negated value, for use with SUB
11209           // instructions. It is not useful otherwise but is implemented for
11210           // compatibility.
11211           if (ARM_AM::getSOImmVal(-CVal) != -1)
11212             break;
11213         }
11214         return;
11215
11216       case 'M':
11217         if (Subtarget->isThumb()) { // FIXME thumb2
11218           // This must be a multiple of 4 between 0 and 1020, for
11219           // ADD sp + immediate.
11220           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11221             break;
11222         } else {
11223           // A power of two or a constant between 0 and 32.  This is used in
11224           // GCC for the shift amount on shifted register operands, but it is
11225           // useful in general for any shift amounts.
11226           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11227             break;
11228         }
11229         return;
11230
11231       case 'N':
11232         if (Subtarget->isThumb()) {  // FIXME thumb2
11233           // This must be a constant between 0 and 31, for shift amounts.
11234           if (CVal >= 0 && CVal <= 31)
11235             break;
11236         }
11237         return;
11238
11239       case 'O':
11240         if (Subtarget->isThumb()) {  // FIXME thumb2
11241           // This must be a multiple of 4 between -508 and 508, for
11242           // ADD/SUB sp = sp + immediate.
11243           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11244             break;
11245         }
11246         return;
11247     }
11248     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11249     break;
11250   }
11251
11252   if (Result.getNode()) {
11253     Ops.push_back(Result);
11254     return;
11255   }
11256   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11257 }
11258
11259 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11260   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11261          "Register-based DivRem lowering only");
11262   unsigned Opcode = Op->getOpcode();
11263   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11264          "Invalid opcode for Div/Rem lowering");
11265   bool isSigned = (Opcode == ISD::SDIVREM);
11266   EVT VT = Op->getValueType(0);
11267   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11268
11269   RTLIB::Libcall LC;
11270   switch (VT.getSimpleVT().SimpleTy) {
11271   default: llvm_unreachable("Unexpected request for libcall!");
11272   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11273   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11274   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11275   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11276   }
11277
11278   SDValue InChain = DAG.getEntryNode();
11279
11280   TargetLowering::ArgListTy Args;
11281   TargetLowering::ArgListEntry Entry;
11282   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11283     EVT ArgVT = Op->getOperand(i).getValueType();
11284     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11285     Entry.Node = Op->getOperand(i);
11286     Entry.Ty = ArgTy;
11287     Entry.isSExt = isSigned;
11288     Entry.isZExt = !isSigned;
11289     Args.push_back(Entry);
11290   }
11291
11292   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11293                                          getPointerTy(DAG.getDataLayout()));
11294
11295   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11296
11297   SDLoc dl(Op);
11298   TargetLowering::CallLoweringInfo CLI(DAG);
11299   CLI.setDebugLoc(dl).setChain(InChain)
11300     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11301     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11302
11303   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11304   return CallInfo.first;
11305 }
11306
11307 SDValue
11308 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11309   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11310   SDLoc DL(Op);
11311
11312   // Get the inputs.
11313   SDValue Chain = Op.getOperand(0);
11314   SDValue Size  = Op.getOperand(1);
11315
11316   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11317                               DAG.getConstant(2, DL, MVT::i32));
11318
11319   SDValue Flag;
11320   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11321   Flag = Chain.getValue(1);
11322
11323   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11324   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11325
11326   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11327   Chain = NewSP.getValue(1);
11328
11329   SDValue Ops[2] = { NewSP, Chain };
11330   return DAG.getMergeValues(Ops, DL);
11331 }
11332
11333 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11334   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11335          "Unexpected type for custom-lowering FP_EXTEND");
11336
11337   RTLIB::Libcall LC;
11338   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11339
11340   SDValue SrcVal = Op.getOperand(0);
11341   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11342                      /*isSigned*/ false, SDLoc(Op)).first;
11343 }
11344
11345 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11346   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11347          Subtarget->isFPOnlySP() &&
11348          "Unexpected type for custom-lowering FP_ROUND");
11349
11350   RTLIB::Libcall LC;
11351   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11352
11353   SDValue SrcVal = Op.getOperand(0);
11354   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11355                      /*isSigned*/ false, SDLoc(Op)).first;
11356 }
11357
11358 bool
11359 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11360   // The ARM target isn't yet aware of offsets.
11361   return false;
11362 }
11363
11364 bool ARM::isBitFieldInvertedMask(unsigned v) {
11365   if (v == 0xffffffff)
11366     return false;
11367
11368   // there can be 1's on either or both "outsides", all the "inside"
11369   // bits must be 0's
11370   return isShiftedMask_32(~v);
11371 }
11372
11373 /// isFPImmLegal - Returns true if the target can instruction select the
11374 /// specified FP immediate natively. If false, the legalizer will
11375 /// materialize the FP immediate as a load from a constant pool.
11376 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11377   if (!Subtarget->hasVFP3())
11378     return false;
11379   if (VT == MVT::f32)
11380     return ARM_AM::getFP32Imm(Imm) != -1;
11381   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11382     return ARM_AM::getFP64Imm(Imm) != -1;
11383   return false;
11384 }
11385
11386 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11387 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11388 /// specified in the intrinsic calls.
11389 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11390                                            const CallInst &I,
11391                                            unsigned Intrinsic) const {
11392   switch (Intrinsic) {
11393   case Intrinsic::arm_neon_vld1:
11394   case Intrinsic::arm_neon_vld2:
11395   case Intrinsic::arm_neon_vld3:
11396   case Intrinsic::arm_neon_vld4:
11397   case Intrinsic::arm_neon_vld2lane:
11398   case Intrinsic::arm_neon_vld3lane:
11399   case Intrinsic::arm_neon_vld4lane: {
11400     Info.opc = ISD::INTRINSIC_W_CHAIN;
11401     // Conservatively set memVT to the entire set of vectors loaded.
11402     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11403     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11404     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11405     Info.ptrVal = I.getArgOperand(0);
11406     Info.offset = 0;
11407     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11408     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11409     Info.vol = false; // volatile loads with NEON intrinsics not supported
11410     Info.readMem = true;
11411     Info.writeMem = false;
11412     return true;
11413   }
11414   case Intrinsic::arm_neon_vst1:
11415   case Intrinsic::arm_neon_vst2:
11416   case Intrinsic::arm_neon_vst3:
11417   case Intrinsic::arm_neon_vst4:
11418   case Intrinsic::arm_neon_vst2lane:
11419   case Intrinsic::arm_neon_vst3lane:
11420   case Intrinsic::arm_neon_vst4lane: {
11421     Info.opc = ISD::INTRINSIC_VOID;
11422     // Conservatively set memVT to the entire set of vectors stored.
11423     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11424     unsigned NumElts = 0;
11425     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11426       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11427       if (!ArgTy->isVectorTy())
11428         break;
11429       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11430     }
11431     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11432     Info.ptrVal = I.getArgOperand(0);
11433     Info.offset = 0;
11434     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11435     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11436     Info.vol = false; // volatile stores with NEON intrinsics not supported
11437     Info.readMem = false;
11438     Info.writeMem = true;
11439     return true;
11440   }
11441   case Intrinsic::arm_ldaex:
11442   case Intrinsic::arm_ldrex: {
11443     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11444     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11445     Info.opc = ISD::INTRINSIC_W_CHAIN;
11446     Info.memVT = MVT::getVT(PtrTy->getElementType());
11447     Info.ptrVal = I.getArgOperand(0);
11448     Info.offset = 0;
11449     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11450     Info.vol = true;
11451     Info.readMem = true;
11452     Info.writeMem = false;
11453     return true;
11454   }
11455   case Intrinsic::arm_stlex:
11456   case Intrinsic::arm_strex: {
11457     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11458     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11459     Info.opc = ISD::INTRINSIC_W_CHAIN;
11460     Info.memVT = MVT::getVT(PtrTy->getElementType());
11461     Info.ptrVal = I.getArgOperand(1);
11462     Info.offset = 0;
11463     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11464     Info.vol = true;
11465     Info.readMem = false;
11466     Info.writeMem = true;
11467     return true;
11468   }
11469   case Intrinsic::arm_stlexd:
11470   case Intrinsic::arm_strexd: {
11471     Info.opc = ISD::INTRINSIC_W_CHAIN;
11472     Info.memVT = MVT::i64;
11473     Info.ptrVal = I.getArgOperand(2);
11474     Info.offset = 0;
11475     Info.align = 8;
11476     Info.vol = true;
11477     Info.readMem = false;
11478     Info.writeMem = true;
11479     return true;
11480   }
11481   case Intrinsic::arm_ldaexd:
11482   case Intrinsic::arm_ldrexd: {
11483     Info.opc = ISD::INTRINSIC_W_CHAIN;
11484     Info.memVT = MVT::i64;
11485     Info.ptrVal = I.getArgOperand(0);
11486     Info.offset = 0;
11487     Info.align = 8;
11488     Info.vol = true;
11489     Info.readMem = true;
11490     Info.writeMem = false;
11491     return true;
11492   }
11493   default:
11494     break;
11495   }
11496
11497   return false;
11498 }
11499
11500 /// \brief Returns true if it is beneficial to convert a load of a constant
11501 /// to just the constant itself.
11502 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11503                                                           Type *Ty) const {
11504   assert(Ty->isIntegerTy());
11505
11506   unsigned Bits = Ty->getPrimitiveSizeInBits();
11507   if (Bits == 0 || Bits > 32)
11508     return false;
11509   return true;
11510 }
11511
11512 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11513
11514 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11515                                         ARM_MB::MemBOpt Domain) const {
11516   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11517
11518   // First, if the target has no DMB, see what fallback we can use.
11519   if (!Subtarget->hasDataBarrier()) {
11520     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11521     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11522     // here.
11523     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11524       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11525       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11526                         Builder.getInt32(0), Builder.getInt32(7),
11527                         Builder.getInt32(10), Builder.getInt32(5)};
11528       return Builder.CreateCall(MCR, args);
11529     } else {
11530       // Instead of using barriers, atomic accesses on these subtargets use
11531       // libcalls.
11532       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11533     }
11534   } else {
11535     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11536     // Only a full system barrier exists in the M-class architectures.
11537     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11538     Constant *CDomain = Builder.getInt32(Domain);
11539     return Builder.CreateCall(DMB, CDomain);
11540   }
11541 }
11542
11543 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11544 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11545                                          AtomicOrdering Ord, bool IsStore,
11546                                          bool IsLoad) const {
11547   if (!getInsertFencesForAtomic())
11548     return nullptr;
11549
11550   switch (Ord) {
11551   case NotAtomic:
11552   case Unordered:
11553     llvm_unreachable("Invalid fence: unordered/non-atomic");
11554   case Monotonic:
11555   case Acquire:
11556     return nullptr; // Nothing to do
11557   case SequentiallyConsistent:
11558     if (!IsStore)
11559       return nullptr; // Nothing to do
11560     /*FALLTHROUGH*/
11561   case Release:
11562   case AcquireRelease:
11563     if (Subtarget->isSwift())
11564       return makeDMB(Builder, ARM_MB::ISHST);
11565     // FIXME: add a comment with a link to documentation justifying this.
11566     else
11567       return makeDMB(Builder, ARM_MB::ISH);
11568   }
11569   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11570 }
11571
11572 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11573                                           AtomicOrdering Ord, bool IsStore,
11574                                           bool IsLoad) const {
11575   if (!getInsertFencesForAtomic())
11576     return nullptr;
11577
11578   switch (Ord) {
11579   case NotAtomic:
11580   case Unordered:
11581     llvm_unreachable("Invalid fence: unordered/not-atomic");
11582   case Monotonic:
11583   case Release:
11584     return nullptr; // Nothing to do
11585   case Acquire:
11586   case AcquireRelease:
11587   case SequentiallyConsistent:
11588     return makeDMB(Builder, ARM_MB::ISH);
11589   }
11590   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11591 }
11592
11593 // Loads and stores less than 64-bits are already atomic; ones above that
11594 // are doomed anyway, so defer to the default libcall and blame the OS when
11595 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11596 // anything for those.
11597 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11598   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11599   return (Size == 64) && !Subtarget->isMClass();
11600 }
11601
11602 // Loads and stores less than 64-bits are already atomic; ones above that
11603 // are doomed anyway, so defer to the default libcall and blame the OS when
11604 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11605 // anything for those.
11606 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11607 // guarantee, see DDI0406C ARM architecture reference manual,
11608 // sections A8.8.72-74 LDRD)
11609 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11610   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11611   return (Size == 64) && !Subtarget->isMClass();
11612 }
11613
11614 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11615 // and up to 64 bits on the non-M profiles
11616 TargetLoweringBase::AtomicRMWExpansionKind
11617 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11618   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11619   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11620              ? AtomicRMWExpansionKind::LLSC
11621              : AtomicRMWExpansionKind::None;
11622 }
11623
11624 // This has so far only been implemented for MachO.
11625 bool ARMTargetLowering::useLoadStackGuardNode() const {
11626   return Subtarget->isTargetMachO();
11627 }
11628
11629 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11630                                                   unsigned &Cost) const {
11631   // If we do not have NEON, vector types are not natively supported.
11632   if (!Subtarget->hasNEON())
11633     return false;
11634
11635   // Floating point values and vector values map to the same register file.
11636   // Therefore, although we could do a store extract of a vector type, this is
11637   // better to leave at float as we have more freedom in the addressing mode for
11638   // those.
11639   if (VectorTy->isFPOrFPVectorTy())
11640     return false;
11641
11642   // If the index is unknown at compile time, this is very expensive to lower
11643   // and it is not possible to combine the store with the extract.
11644   if (!isa<ConstantInt>(Idx))
11645     return false;
11646
11647   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11648   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11649   // We can do a store + vector extract on any vector that fits perfectly in a D
11650   // or Q register.
11651   if (BitWidth == 64 || BitWidth == 128) {
11652     Cost = 0;
11653     return true;
11654   }
11655   return false;
11656 }
11657
11658 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11659                                          AtomicOrdering Ord) const {
11660   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11661   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11662   bool IsAcquire = isAtLeastAcquire(Ord);
11663
11664   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11665   // intrinsic must return {i32, i32} and we have to recombine them into a
11666   // single i64 here.
11667   if (ValTy->getPrimitiveSizeInBits() == 64) {
11668     Intrinsic::ID Int =
11669         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11670     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11671
11672     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11673     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11674
11675     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11676     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11677     if (!Subtarget->isLittle())
11678       std::swap (Lo, Hi);
11679     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11680     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11681     return Builder.CreateOr(
11682         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11683   }
11684
11685   Type *Tys[] = { Addr->getType() };
11686   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11687   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11688
11689   return Builder.CreateTruncOrBitCast(
11690       Builder.CreateCall(Ldrex, Addr),
11691       cast<PointerType>(Addr->getType())->getElementType());
11692 }
11693
11694 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11695                                                Value *Addr,
11696                                                AtomicOrdering Ord) const {
11697   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11698   bool IsRelease = isAtLeastRelease(Ord);
11699
11700   // Since the intrinsics must have legal type, the i64 intrinsics take two
11701   // parameters: "i32, i32". We must marshal Val into the appropriate form
11702   // before the call.
11703   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11704     Intrinsic::ID Int =
11705         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11706     Function *Strex = Intrinsic::getDeclaration(M, Int);
11707     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11708
11709     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11710     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11711     if (!Subtarget->isLittle())
11712       std::swap (Lo, Hi);
11713     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11714     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11715   }
11716
11717   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11718   Type *Tys[] = { Addr->getType() };
11719   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11720
11721   return Builder.CreateCall(
11722       Strex, {Builder.CreateZExtOrBitCast(
11723                   Val, Strex->getFunctionType()->getParamType(0)),
11724               Addr});
11725 }
11726
11727 /// \brief Lower an interleaved load into a vldN intrinsic.
11728 ///
11729 /// E.g. Lower an interleaved load (Factor = 2):
11730 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11731 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11732 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11733 ///
11734 ///      Into:
11735 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11736 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11737 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11738 bool ARMTargetLowering::lowerInterleavedLoad(
11739     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11740     ArrayRef<unsigned> Indices, unsigned Factor) const {
11741   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11742          "Invalid interleave factor");
11743   assert(!Shuffles.empty() && "Empty shufflevector input");
11744   assert(Shuffles.size() == Indices.size() &&
11745          "Unmatched number of shufflevectors and indices");
11746
11747   VectorType *VecTy = Shuffles[0]->getType();
11748   Type *EltTy = VecTy->getVectorElementType();
11749
11750   const DataLayout &DL = LI->getModule()->getDataLayout();
11751   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11752   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11753
11754   // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11755   // support i64/f64 element).
11756   if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11757     return false;
11758
11759   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11760   // load integer vectors first and then convert to pointer vectors.
11761   if (EltTy->isPointerTy())
11762     VecTy =
11763         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11764
11765   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11766                                             Intrinsic::arm_neon_vld3,
11767                                             Intrinsic::arm_neon_vld4};
11768
11769   Function *VldnFunc =
11770       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11771
11772   IRBuilder<> Builder(LI);
11773   SmallVector<Value *, 2> Ops;
11774
11775   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11776   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11777   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11778
11779   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11780
11781   // Replace uses of each shufflevector with the corresponding vector loaded
11782   // by ldN.
11783   for (unsigned i = 0; i < Shuffles.size(); i++) {
11784     ShuffleVectorInst *SV = Shuffles[i];
11785     unsigned Index = Indices[i];
11786
11787     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11788
11789     // Convert the integer vector to pointer vector if the element is pointer.
11790     if (EltTy->isPointerTy())
11791       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11792
11793     SV->replaceAllUsesWith(SubVec);
11794   }
11795
11796   return true;
11797 }
11798
11799 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11800 ///
11801 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11802 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11803                                    unsigned NumElts) {
11804   SmallVector<Constant *, 16> Mask;
11805   for (unsigned i = 0; i < NumElts; i++)
11806     Mask.push_back(Builder.getInt32(Start + i));
11807
11808   return ConstantVector::get(Mask);
11809 }
11810
11811 /// \brief Lower an interleaved store into a vstN intrinsic.
11812 ///
11813 /// E.g. Lower an interleaved store (Factor = 3):
11814 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11815 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11816 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11817 ///
11818 ///      Into:
11819 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11820 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11821 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11822 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11823 ///
11824 /// Note that the new shufflevectors will be removed and we'll only generate one
11825 /// vst3 instruction in CodeGen.
11826 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11827                                               ShuffleVectorInst *SVI,
11828                                               unsigned Factor) const {
11829   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11830          "Invalid interleave factor");
11831
11832   VectorType *VecTy = SVI->getType();
11833   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11834          "Invalid interleaved store");
11835
11836   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11837   Type *EltTy = VecTy->getVectorElementType();
11838   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11839
11840   const DataLayout &DL = SI->getModule()->getDataLayout();
11841   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11842   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11843
11844   // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11845   // doesn't support i64/f64 element).
11846   if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11847     return false;
11848
11849   Value *Op0 = SVI->getOperand(0);
11850   Value *Op1 = SVI->getOperand(1);
11851   IRBuilder<> Builder(SI);
11852
11853   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11854   // vectors to integer vectors.
11855   if (EltTy->isPointerTy()) {
11856     Type *IntTy = DL.getIntPtrType(EltTy);
11857
11858     // Convert to the corresponding integer vector.
11859     Type *IntVecTy =
11860         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11861     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11862     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11863
11864     SubVecTy = VectorType::get(IntTy, NumSubElts);
11865   }
11866
11867   static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11868                                        Intrinsic::arm_neon_vst3,
11869                                        Intrinsic::arm_neon_vst4};
11870   Function *VstNFunc = Intrinsic::getDeclaration(
11871       SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11872
11873   SmallVector<Value *, 6> Ops;
11874
11875   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11876   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11877
11878   // Split the shufflevector operands into sub vectors for the new vstN call.
11879   for (unsigned i = 0; i < Factor; i++)
11880     Ops.push_back(Builder.CreateShuffleVector(
11881         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11882
11883   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11884   Builder.CreateCall(VstNFunc, Ops);
11885   return true;
11886 }
11887
11888 enum HABaseType {
11889   HA_UNKNOWN = 0,
11890   HA_FLOAT,
11891   HA_DOUBLE,
11892   HA_VECT64,
11893   HA_VECT128
11894 };
11895
11896 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11897                                    uint64_t &Members) {
11898   if (auto *ST = dyn_cast<StructType>(Ty)) {
11899     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11900       uint64_t SubMembers = 0;
11901       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11902         return false;
11903       Members += SubMembers;
11904     }
11905   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11906     uint64_t SubMembers = 0;
11907     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11908       return false;
11909     Members += SubMembers * AT->getNumElements();
11910   } else if (Ty->isFloatTy()) {
11911     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11912       return false;
11913     Members = 1;
11914     Base = HA_FLOAT;
11915   } else if (Ty->isDoubleTy()) {
11916     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11917       return false;
11918     Members = 1;
11919     Base = HA_DOUBLE;
11920   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11921     Members = 1;
11922     switch (Base) {
11923     case HA_FLOAT:
11924     case HA_DOUBLE:
11925       return false;
11926     case HA_VECT64:
11927       return VT->getBitWidth() == 64;
11928     case HA_VECT128:
11929       return VT->getBitWidth() == 128;
11930     case HA_UNKNOWN:
11931       switch (VT->getBitWidth()) {
11932       case 64:
11933         Base = HA_VECT64;
11934         return true;
11935       case 128:
11936         Base = HA_VECT128;
11937         return true;
11938       default:
11939         return false;
11940       }
11941     }
11942   }
11943
11944   return (Members > 0 && Members <= 4);
11945 }
11946
11947 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11948 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11949 /// passing according to AAPCS rules.
11950 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11951     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11952   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11953       CallingConv::ARM_AAPCS_VFP)
11954     return false;
11955
11956   HABaseType Base = HA_UNKNOWN;
11957   uint64_t Members = 0;
11958   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11959   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11960
11961   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11962   return IsHA || IsIntArray;
11963 }