[LLVM - ARM/AArch64] Add ACLE special register intrinsics
[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 cl::opt<bool>
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65   cl::desc("Generate calls via indirect call instructions"),
66   cl::init(false));
67
68 static cl::opt<bool>
69 ARMInterworking("arm-interworking", cl::Hidden,
70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
71   cl::init(true));
72
73 namespace {
74   class ARMCCState : public CCState {
75   public:
76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
78                ParmContext PC)
79         : CCState(CC, isVarArg, MF, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const MCPhysReg GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94                                        MVT PromotedBitwiseVT) {
95   if (VT != PromotedLdStVT) {
96     setOperationAction(ISD::LOAD, VT, Promote);
97     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98
99     setOperationAction(ISD::STORE, VT, Promote);
100     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101   }
102
103   MVT ElemTy = VT.getVectorElementType();
104   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105     setOperationAction(ISD::SETCC, VT, Custom);
106   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108   if (ElemTy == MVT::i32) {
109     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113   } else {
114     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118   }
119   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
120   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
121   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
122   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123   setOperationAction(ISD::SELECT,            VT, Expand);
124   setOperationAction(ISD::SELECT_CC,         VT, Expand);
125   setOperationAction(ISD::VSELECT,           VT, Expand);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127   if (VT.isInteger()) {
128     setOperationAction(ISD::SHL, VT, Custom);
129     setOperationAction(ISD::SRA, VT, Custom);
130     setOperationAction(ISD::SRL, VT, Custom);
131   }
132
133   // Promote all bit-wise operations.
134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
135     setOperationAction(ISD::AND, VT, Promote);
136     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137     setOperationAction(ISD::OR,  VT, Promote);
138     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
139     setOperationAction(ISD::XOR, VT, Promote);
140     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141   }
142
143   // Neon does not support vector divide/remainder operations.
144   setOperationAction(ISD::SDIV, VT, Expand);
145   setOperationAction(ISD::UDIV, VT, Expand);
146   setOperationAction(ISD::FDIV, VT, Expand);
147   setOperationAction(ISD::SREM, VT, Expand);
148   setOperationAction(ISD::UREM, VT, Expand);
149   setOperationAction(ISD::FREM, VT, Expand);
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       // Single-precision floating-point arithmetic.
175       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
176       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
177       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
178       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
179
180       // Double-precision floating-point arithmetic.
181       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
182       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
183       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
184       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
185
186       // Single-precision comparisons.
187       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
188       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
189       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
190       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
191       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
192       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
193       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
194       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
195
196       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
197       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
198       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
199       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
200       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
203       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
204
205       // Double-precision comparisons.
206       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
207       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
208       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
209       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
210       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
211       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
212       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
213       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
214
215       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
216       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
217       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
218       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
219       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
222       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
223
224       // Floating-point to integer conversions.
225       // i64 conversions are done via library routines even when generating VFP
226       // instructions, so use the same ones.
227       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
228       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
229       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
230       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
231
232       // Conversions between floating types.
233       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
234       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
235
236       // Integer to floating-point conversions.
237       // i64 conversions are done via library routines even when generating VFP
238       // instructions, so use the same ones.
239       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
240       // e.g., __floatunsidf vs. __floatunssidfvfp.
241       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
242       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
243       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
244       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
245     }
246   }
247
248   // These libcalls are not available in 32-bit.
249   setLibcallName(RTLIB::SHL_I128, nullptr);
250   setLibcallName(RTLIB::SRL_I128, nullptr);
251   setLibcallName(RTLIB::SRA_I128, nullptr);
252
253   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
254       !Subtarget->isTargetWindows()) {
255     static const struct {
256       const RTLIB::Libcall Op;
257       const char * const Name;
258       const CallingConv::ID CC;
259       const ISD::CondCode Cond;
260     } LibraryCalls[] = {
261       // Double-precision floating-point arithmetic helper functions
262       // RTABI chapter 4.1.2, Table 2
263       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
266       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
267
268       // Double-precision floating-point comparison helper functions
269       // RTABI chapter 4.1.2, Table 3
270       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
271       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
272       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
273       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
274       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
276       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
277       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
278
279       // Single-precision floating-point arithmetic helper functions
280       // RTABI chapter 4.1.2, Table 4
281       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
284       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
285
286       // Single-precision floating-point comparison helper functions
287       // RTABI chapter 4.1.2, Table 5
288       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
289       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
290       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
291       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
292       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
294       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
295       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
296
297       // Floating-point to integer conversions.
298       // RTABI chapter 4.1.2, Table 6
299       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307
308       // Conversions between floating types.
309       // RTABI chapter 4.1.2, Table 7
310       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313
314       // Integer to floating-point conversions.
315       // RTABI chapter 4.1.2, Table 8
316       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324
325       // Long long helper functions
326       // RTABI chapter 4.2, Table 9
327       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331
332       // Integer division functions
333       // RTABI chapter 4.3.1
334       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342
343       // Memory operations
344       // RTABI chapter 4.3.4
345       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348     };
349
350     for (const auto &LC : LibraryCalls) {
351       setLibcallName(LC.Op, LC.Name);
352       setLibcallCallingConv(LC.Op, LC.CC);
353       if (LC.Cond != ISD::SETCC_INVALID)
354         setCmpLibcallCC(LC.Op, LC.Cond);
355     }
356   }
357
358   if (Subtarget->isTargetWindows()) {
359     static const struct {
360       const RTLIB::Libcall Op;
361       const char * const Name;
362       const CallingConv::ID CC;
363     } LibraryCalls[] = {
364       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
366       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
367       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
372     };
373
374     for (const auto &LC : LibraryCalls) {
375       setLibcallName(LC.Op, LC.Name);
376       setLibcallCallingConv(LC.Op, LC.CC);
377     }
378   }
379
380   // Use divmod compiler-rt calls for iOS 5.0 and later.
381   if (Subtarget->getTargetTriple().isiOS() &&
382       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
383     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
384     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
385   }
386
387   // The half <-> float conversion functions are always soft-float, but are
388   // needed for some targets which use a hard-float calling convention by
389   // default.
390   if (Subtarget->isAAPCS_ABI()) {
391     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
393     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
394   } else {
395     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
396     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
397     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
398   }
399
400   if (Subtarget->isThumb1Only())
401     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
402   else
403     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
404   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
405       !Subtarget->isThumb1Only()) {
406     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
407     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
408   }
409
410   for (MVT VT : MVT::vector_valuetypes()) {
411     for (MVT InnerVT : MVT::vector_valuetypes()) {
412       setTruncStoreAction(VT, InnerVT, Expand);
413       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
414       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
415       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
416     }
417
418     setOperationAction(ISD::MULHS, VT, Expand);
419     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
420     setOperationAction(ISD::MULHU, VT, Expand);
421     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
422
423     setOperationAction(ISD::BSWAP, VT, Expand);
424   }
425
426   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
427   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
428
429   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
430   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
431
432   if (Subtarget->hasNEON()) {
433     addDRTypeForNEON(MVT::v2f32);
434     addDRTypeForNEON(MVT::v8i8);
435     addDRTypeForNEON(MVT::v4i16);
436     addDRTypeForNEON(MVT::v2i32);
437     addDRTypeForNEON(MVT::v1i64);
438
439     addQRTypeForNEON(MVT::v4f32);
440     addQRTypeForNEON(MVT::v2f64);
441     addQRTypeForNEON(MVT::v16i8);
442     addQRTypeForNEON(MVT::v8i16);
443     addQRTypeForNEON(MVT::v4i32);
444     addQRTypeForNEON(MVT::v2i64);
445
446     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
447     // neither Neon nor VFP support any arithmetic operations on it.
448     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
449     // supported for v4f32.
450     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
451     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
452     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
453     // FIXME: Code duplication: FDIV and FREM are expanded always, see
454     // ARMTargetLowering::addTypeForNEON method for details.
455     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
456     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
457     // FIXME: Create unittest.
458     // In another words, find a way when "copysign" appears in DAG with vector
459     // operands.
460     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
461     // FIXME: Code duplication: SETCC has custom operation action, see
462     // ARMTargetLowering::addTypeForNEON method for details.
463     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
464     // FIXME: Create unittest for FNEG and for FABS.
465     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
466     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
467     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
468     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
469     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
470     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
471     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
472     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
473     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
474     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
475     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
476     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
477     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
478     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
479     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
480     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
481     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
482     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
483     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
484
485     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
486     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
487     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
488     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
489     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
490     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
491     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
492     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
493     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
494     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
495     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
496     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
497     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
498     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
499     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
500
501     // Mark v2f32 intrinsics.
502     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
503     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
504     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
505     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
506     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
507     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
508     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
509     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
510     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
511     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
512     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
513     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
514     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
515     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
516     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
517
518     // Neon does not support some operations on v1i64 and v2i64 types.
519     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
520     // Custom handling for some quad-vector types to detect VMULL.
521     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
522     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
523     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
524     // Custom handling for some vector types to avoid expensive expansions
525     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
526     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
527     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
528     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
529     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
530     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
531     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
532     // a destination type that is wider than the source, and nor does
533     // it have a FP_TO_[SU]INT instruction with a narrower destination than
534     // source.
535     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
536     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
537     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
538     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
539
540     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
541     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
542
543     // NEON does not have single instruction CTPOP for vectors with element
544     // types wider than 8-bits.  However, custom lowering can leverage the
545     // v8i8/v16i8 vcnt instruction.
546     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
547     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
548     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
549     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
550
551     // NEON only has FMA instructions as of VFP4.
552     if (!Subtarget->hasVFP4()) {
553       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
554       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
555     }
556
557     setTargetDAGCombine(ISD::INTRINSIC_VOID);
558     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
559     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
560     setTargetDAGCombine(ISD::SHL);
561     setTargetDAGCombine(ISD::SRL);
562     setTargetDAGCombine(ISD::SRA);
563     setTargetDAGCombine(ISD::SIGN_EXTEND);
564     setTargetDAGCombine(ISD::ZERO_EXTEND);
565     setTargetDAGCombine(ISD::ANY_EXTEND);
566     setTargetDAGCombine(ISD::SELECT_CC);
567     setTargetDAGCombine(ISD::BUILD_VECTOR);
568     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
569     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
570     setTargetDAGCombine(ISD::STORE);
571     setTargetDAGCombine(ISD::FP_TO_SINT);
572     setTargetDAGCombine(ISD::FP_TO_UINT);
573     setTargetDAGCombine(ISD::FDIV);
574     setTargetDAGCombine(ISD::LOAD);
575
576     // It is legal to extload from v4i8 to v4i16 or v4i32.
577     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
578                    MVT::v2i32}) {
579       for (MVT VT : MVT::integer_vector_valuetypes()) {
580         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
581         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
582         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
583       }
584     }
585   }
586
587   // ARM and Thumb2 support UMLAL/SMLAL.
588   if (!Subtarget->isThumb1Only())
589     setTargetDAGCombine(ISD::ADDC);
590
591   if (Subtarget->isFPOnlySP()) {
592     // When targetting a floating-point unit with only single-precision
593     // operations, f64 is legal for the few double-precision instructions which
594     // are present However, no double-precision operations other than moves,
595     // loads and stores are provided by the hardware.
596     setOperationAction(ISD::FADD,       MVT::f64, Expand);
597     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
598     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
599     setOperationAction(ISD::FMA,        MVT::f64, Expand);
600     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
601     setOperationAction(ISD::FREM,       MVT::f64, Expand);
602     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
603     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
604     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
605     setOperationAction(ISD::FABS,       MVT::f64, Expand);
606     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
607     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
608     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
609     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
610     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
611     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
612     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
613     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
614     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
615     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
616     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
617     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
618     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
619     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
620     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
621     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
622     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
623     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
624     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
625     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
626     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
627     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
628     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
629   }
630
631   computeRegisterProperties(Subtarget->getRegisterInfo());
632
633   // ARM does not have floating-point extending loads.
634   for (MVT VT : MVT::fp_valuetypes()) {
635     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
636     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
637   }
638
639   // ... or truncating stores
640   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
641   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
642   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
643
644   // ARM does not have i1 sign extending load.
645   for (MVT VT : MVT::integer_valuetypes())
646     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
647
648   // ARM supports all 4 flavors of integer indexed load / store.
649   if (!Subtarget->isThumb1Only()) {
650     for (unsigned im = (unsigned)ISD::PRE_INC;
651          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
652       setIndexedLoadAction(im,  MVT::i1,  Legal);
653       setIndexedLoadAction(im,  MVT::i8,  Legal);
654       setIndexedLoadAction(im,  MVT::i16, Legal);
655       setIndexedLoadAction(im,  MVT::i32, Legal);
656       setIndexedStoreAction(im, MVT::i1,  Legal);
657       setIndexedStoreAction(im, MVT::i8,  Legal);
658       setIndexedStoreAction(im, MVT::i16, Legal);
659       setIndexedStoreAction(im, MVT::i32, Legal);
660     }
661   }
662
663   setOperationAction(ISD::SADDO, MVT::i32, Custom);
664   setOperationAction(ISD::UADDO, MVT::i32, Custom);
665   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
666   setOperationAction(ISD::USUBO, MVT::i32, Custom);
667
668   // i64 operation support.
669   setOperationAction(ISD::MUL,     MVT::i64, Expand);
670   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
671   if (Subtarget->isThumb1Only()) {
672     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
673     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
674   }
675   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
676       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
677     setOperationAction(ISD::MULHS, MVT::i32, Expand);
678
679   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
680   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
681   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
682   setOperationAction(ISD::SRL,       MVT::i64, Custom);
683   setOperationAction(ISD::SRA,       MVT::i64, Custom);
684
685   if (!Subtarget->isThumb1Only()) {
686     // FIXME: We should do this for Thumb1 as well.
687     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
688     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
689     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
690     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
691   }
692
693   // ARM does not have ROTL.
694   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
695   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
696   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
697   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
698     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
699
700   // These just redirect to CTTZ and CTLZ on ARM.
701   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
702   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
703
704   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
705
706   // Only ARMv6 has BSWAP.
707   if (!Subtarget->hasV6Ops())
708     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
709
710   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
711       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
712     // These are expanded into libcalls if the cpu doesn't have HW divider.
713     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
714     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
715   }
716
717   // FIXME: Also set divmod for SREM on EABI
718   setOperationAction(ISD::SREM,  MVT::i32, Expand);
719   setOperationAction(ISD::UREM,  MVT::i32, Expand);
720   // Register based DivRem for AEABI (RTABI 4.2)
721   if (Subtarget->isTargetAEABI()) {
722     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
723     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
724     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
725     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
726     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
727     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
728     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
729     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
730
731     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
732     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
733     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
734     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
735     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
736     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
737     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
738     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
739
740     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
741     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
742   } else {
743     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
744     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
745   }
746
747   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
748   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
749   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
750   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
751   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
752
753   setOperationAction(ISD::TRAP, MVT::Other, Legal);
754
755   // Use the default implementation.
756   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
757   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
758   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
759   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
760   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
761   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
762
763   if (!Subtarget->isTargetMachO()) {
764     // Non-MachO platforms may return values in these registers via the
765     // personality function.
766     setExceptionPointerRegister(ARM::R0);
767     setExceptionSelectorRegister(ARM::R1);
768   }
769
770   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
771     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
772   else
773     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
774
775   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
776   // the default expansion. If we are targeting a single threaded system,
777   // then set them all for expand so we can lower them later into their
778   // non-atomic form.
779   if (TM.Options.ThreadModel == ThreadModel::Single)
780     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
781   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
782     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
783     // to ldrex/strex loops already.
784     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
785
786     // On v8, we have particularly efficient implementations of atomic fences
787     // if they can be combined with nearby atomic loads and stores.
788     if (!Subtarget->hasV8Ops()) {
789       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
790       setInsertFencesForAtomic(true);
791     }
792   } else {
793     // If there's anything we can use as a barrier, go through custom lowering
794     // for ATOMIC_FENCE.
795     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
796                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
797
798     // Set them all for expansion, which will force libcalls.
799     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
801     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
802     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
803     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
804     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
805     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
806     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
807     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
808     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
809     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
810     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
811     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
812     // Unordered/Monotonic case.
813     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
814     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
815   }
816
817   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
818
819   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
820   if (!Subtarget->hasV6Ops()) {
821     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
822     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
823   }
824   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
825
826   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
827       !Subtarget->isThumb1Only()) {
828     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
829     // iff target supports vfp2.
830     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
831     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
832   }
833
834   // We want to custom lower some of our intrinsics.
835   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
836   if (Subtarget->isTargetDarwin()) {
837     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
838     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
839     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
840   }
841
842   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
843   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
844   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
845   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
846   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
847   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
848   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
849   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
850   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
851
852   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
853   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
854   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
855   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
856   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
857
858   // We don't support sin/cos/fmod/copysign/pow
859   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
860   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
861   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
862   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
863   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
864   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
865   setOperationAction(ISD::FREM,      MVT::f64, Expand);
866   setOperationAction(ISD::FREM,      MVT::f32, Expand);
867   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
868       !Subtarget->isThumb1Only()) {
869     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
870     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
871   }
872   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
873   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
874
875   if (!Subtarget->hasVFP4()) {
876     setOperationAction(ISD::FMA, MVT::f64, Expand);
877     setOperationAction(ISD::FMA, MVT::f32, Expand);
878   }
879
880   // Various VFP goodness
881   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
882     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
883     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
884       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
885       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
886     }
887
888     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
889     if (!Subtarget->hasFP16()) {
890       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
891       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
892     }
893   }
894
895   // Combine sin / cos into one node or libcall if possible.
896   if (Subtarget->hasSinCos()) {
897     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
898     setLibcallName(RTLIB::SINCOS_F64, "sincos");
899     if (Subtarget->getTargetTriple().isiOS()) {
900       // For iOS, we don't want to the normal expansion of a libcall to
901       // sincos. We want to issue a libcall to __sincos_stret.
902       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
903       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
904     }
905   }
906
907   // FP-ARMv8 implements a lot of rounding-like FP operations.
908   if (Subtarget->hasFPARMv8()) {
909     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
910     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
911     setOperationAction(ISD::FROUND, MVT::f32, Legal);
912     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
913     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
914     setOperationAction(ISD::FRINT, MVT::f32, Legal);
915     if (!Subtarget->isFPOnlySP()) {
916       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
917       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
918       setOperationAction(ISD::FROUND, MVT::f64, Legal);
919       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
920       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
921       setOperationAction(ISD::FRINT, MVT::f64, Legal);
922     }
923   }
924   // We have target-specific dag combine patterns for the following nodes:
925   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
926   setTargetDAGCombine(ISD::ADD);
927   setTargetDAGCombine(ISD::SUB);
928   setTargetDAGCombine(ISD::MUL);
929   setTargetDAGCombine(ISD::AND);
930   setTargetDAGCombine(ISD::OR);
931   setTargetDAGCombine(ISD::XOR);
932
933   if (Subtarget->hasV6Ops())
934     setTargetDAGCombine(ISD::SRL);
935
936   setStackPointerRegisterToSaveRestore(ARM::SP);
937
938   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
939       !Subtarget->hasVFP2())
940     setSchedulingPreference(Sched::RegPressure);
941   else
942     setSchedulingPreference(Sched::Hybrid);
943
944   //// temporary - rewrite interface to use type
945   MaxStoresPerMemset = 8;
946   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
947   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
948   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
949   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
950   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
951
952   // On ARM arguments smaller than 4 bytes are extended, so all arguments
953   // are at least 4 bytes aligned.
954   setMinStackArgumentAlignment(4);
955
956   // Prefer likely predicted branches to selects on out-of-order cores.
957   PredictableSelectIsExpensive = Subtarget->isLikeA9();
958
959   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
960 }
961
962 bool ARMTargetLowering::useSoftFloat() const {
963   return Subtarget->useSoftFloat();
964 }
965
966 // FIXME: It might make sense to define the representative register class as the
967 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
968 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
969 // SPR's representative would be DPR_VFP2. This should work well if register
970 // pressure tracking were modified such that a register use would increment the
971 // pressure of the register class's representative and all of it's super
972 // classes' representatives transitively. We have not implemented this because
973 // of the difficulty prior to coalescing of modeling operand register classes
974 // due to the common occurrence of cross class copies and subregister insertions
975 // and extractions.
976 std::pair<const TargetRegisterClass *, uint8_t>
977 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
978                                            MVT VT) const {
979   const TargetRegisterClass *RRC = nullptr;
980   uint8_t Cost = 1;
981   switch (VT.SimpleTy) {
982   default:
983     return TargetLowering::findRepresentativeClass(TRI, VT);
984   // Use DPR as representative register class for all floating point
985   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
986   // the cost is 1 for both f32 and f64.
987   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
988   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
989     RRC = &ARM::DPRRegClass;
990     // When NEON is used for SP, only half of the register file is available
991     // because operations that define both SP and DP results will be constrained
992     // to the VFP2 class (D0-D15). We currently model this constraint prior to
993     // coalescing by double-counting the SP regs. See the FIXME above.
994     if (Subtarget->useNEONForSinglePrecisionFP())
995       Cost = 2;
996     break;
997   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
998   case MVT::v4f32: case MVT::v2f64:
999     RRC = &ARM::DPRRegClass;
1000     Cost = 2;
1001     break;
1002   case MVT::v4i64:
1003     RRC = &ARM::DPRRegClass;
1004     Cost = 4;
1005     break;
1006   case MVT::v8i64:
1007     RRC = &ARM::DPRRegClass;
1008     Cost = 8;
1009     break;
1010   }
1011   return std::make_pair(RRC, Cost);
1012 }
1013
1014 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1015   switch ((ARMISD::NodeType)Opcode) {
1016   case ARMISD::FIRST_NUMBER:  break;
1017   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1018   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1019   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1020   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1021   case ARMISD::CALL:          return "ARMISD::CALL";
1022   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1023   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1024   case ARMISD::tCALL:         return "ARMISD::tCALL";
1025   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1026   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1027   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1028   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1029   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1030   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1031   case ARMISD::CMP:           return "ARMISD::CMP";
1032   case ARMISD::CMN:           return "ARMISD::CMN";
1033   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1034   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1035   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1036   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1037   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1038
1039   case ARMISD::CMOV:          return "ARMISD::CMOV";
1040
1041   case ARMISD::RBIT:          return "ARMISD::RBIT";
1042
1043   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1044   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1045   case ARMISD::RRX:           return "ARMISD::RRX";
1046
1047   case ARMISD::ADDC:          return "ARMISD::ADDC";
1048   case ARMISD::ADDE:          return "ARMISD::ADDE";
1049   case ARMISD::SUBC:          return "ARMISD::SUBC";
1050   case ARMISD::SUBE:          return "ARMISD::SUBE";
1051
1052   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1053   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1054
1055   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1056   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1057
1058   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1059
1060   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1061
1062   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1063
1064   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1065
1066   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1067
1068   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1069
1070   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1071   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1072   case ARMISD::VCGE:          return "ARMISD::VCGE";
1073   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1074   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1075   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1076   case ARMISD::VCGT:          return "ARMISD::VCGT";
1077   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1078   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1079   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1080   case ARMISD::VTST:          return "ARMISD::VTST";
1081
1082   case ARMISD::VSHL:          return "ARMISD::VSHL";
1083   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1084   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1085   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1086   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1087   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1088   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1089   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1090   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1091   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1092   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1093   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1094   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1095   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1096   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1097   case ARMISD::VSLI:          return "ARMISD::VSLI";
1098   case ARMISD::VSRI:          return "ARMISD::VSRI";
1099   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1100   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1101   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1102   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1103   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1104   case ARMISD::VDUP:          return "ARMISD::VDUP";
1105   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1106   case ARMISD::VEXT:          return "ARMISD::VEXT";
1107   case ARMISD::VREV64:        return "ARMISD::VREV64";
1108   case ARMISD::VREV32:        return "ARMISD::VREV32";
1109   case ARMISD::VREV16:        return "ARMISD::VREV16";
1110   case ARMISD::VZIP:          return "ARMISD::VZIP";
1111   case ARMISD::VUZP:          return "ARMISD::VUZP";
1112   case ARMISD::VTRN:          return "ARMISD::VTRN";
1113   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1114   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1115   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1116   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1117   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1118   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1119   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1120   case ARMISD::FMAX:          return "ARMISD::FMAX";
1121   case ARMISD::FMIN:          return "ARMISD::FMIN";
1122   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1123   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1124   case ARMISD::BFI:           return "ARMISD::BFI";
1125   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1126   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1127   case ARMISD::VBSL:          return "ARMISD::VBSL";
1128   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1129   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1130   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1131   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1132   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1133   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1134   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1135   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1136   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1137   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1138   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1139   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1140   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1141   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1142   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1143   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1144   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1145   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1146   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1147   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1148   }
1149   return nullptr;
1150 }
1151
1152 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1153   if (!VT.isVector()) return getPointerTy();
1154   return VT.changeVectorElementTypeToInteger();
1155 }
1156
1157 /// getRegClassFor - Return the register class that should be used for the
1158 /// specified value type.
1159 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1160   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1161   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1162   // load / store 4 to 8 consecutive D registers.
1163   if (Subtarget->hasNEON()) {
1164     if (VT == MVT::v4i64)
1165       return &ARM::QQPRRegClass;
1166     if (VT == MVT::v8i64)
1167       return &ARM::QQQQPRRegClass;
1168   }
1169   return TargetLowering::getRegClassFor(VT);
1170 }
1171
1172 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1173 // source/dest is aligned and the copy size is large enough. We therefore want
1174 // to align such objects passed to memory intrinsics.
1175 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1176                                                unsigned &PrefAlign) const {
1177   if (!isa<MemIntrinsic>(CI))
1178     return false;
1179   MinSize = 8;
1180   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1181   // cycle faster than 4-byte aligned LDM.
1182   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1183   return true;
1184 }
1185
1186 // Create a fast isel object.
1187 FastISel *
1188 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1189                                   const TargetLibraryInfo *libInfo) const {
1190   return ARM::createFastISel(funcInfo, libInfo);
1191 }
1192
1193 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1194   unsigned NumVals = N->getNumValues();
1195   if (!NumVals)
1196     return Sched::RegPressure;
1197
1198   for (unsigned i = 0; i != NumVals; ++i) {
1199     EVT VT = N->getValueType(i);
1200     if (VT == MVT::Glue || VT == MVT::Other)
1201       continue;
1202     if (VT.isFloatingPoint() || VT.isVector())
1203       return Sched::ILP;
1204   }
1205
1206   if (!N->isMachineOpcode())
1207     return Sched::RegPressure;
1208
1209   // Load are scheduled for latency even if there instruction itinerary
1210   // is not available.
1211   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1212   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1213
1214   if (MCID.getNumDefs() == 0)
1215     return Sched::RegPressure;
1216   if (!Itins->isEmpty() &&
1217       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1218     return Sched::ILP;
1219
1220   return Sched::RegPressure;
1221 }
1222
1223 //===----------------------------------------------------------------------===//
1224 // Lowering Code
1225 //===----------------------------------------------------------------------===//
1226
1227 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1228 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1229   switch (CC) {
1230   default: llvm_unreachable("Unknown condition code!");
1231   case ISD::SETNE:  return ARMCC::NE;
1232   case ISD::SETEQ:  return ARMCC::EQ;
1233   case ISD::SETGT:  return ARMCC::GT;
1234   case ISD::SETGE:  return ARMCC::GE;
1235   case ISD::SETLT:  return ARMCC::LT;
1236   case ISD::SETLE:  return ARMCC::LE;
1237   case ISD::SETUGT: return ARMCC::HI;
1238   case ISD::SETUGE: return ARMCC::HS;
1239   case ISD::SETULT: return ARMCC::LO;
1240   case ISD::SETULE: return ARMCC::LS;
1241   }
1242 }
1243
1244 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1245 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1246                         ARMCC::CondCodes &CondCode2) {
1247   CondCode2 = ARMCC::AL;
1248   switch (CC) {
1249   default: llvm_unreachable("Unknown FP condition!");
1250   case ISD::SETEQ:
1251   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1252   case ISD::SETGT:
1253   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1254   case ISD::SETGE:
1255   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1256   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1257   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1258   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1259   case ISD::SETO:   CondCode = ARMCC::VC; break;
1260   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1261   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1262   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1263   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1264   case ISD::SETLT:
1265   case ISD::SETULT: CondCode = ARMCC::LT; break;
1266   case ISD::SETLE:
1267   case ISD::SETULE: CondCode = ARMCC::LE; break;
1268   case ISD::SETNE:
1269   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1270   }
1271 }
1272
1273 //===----------------------------------------------------------------------===//
1274 //                      Calling Convention Implementation
1275 //===----------------------------------------------------------------------===//
1276
1277 #include "ARMGenCallingConv.inc"
1278
1279 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1280 /// account presence of floating point hardware and calling convention
1281 /// limitations, such as support for variadic functions.
1282 CallingConv::ID
1283 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1284                                            bool isVarArg) const {
1285   switch (CC) {
1286   default:
1287     llvm_unreachable("Unsupported calling convention");
1288   case CallingConv::ARM_AAPCS:
1289   case CallingConv::ARM_APCS:
1290   case CallingConv::GHC:
1291     return CC;
1292   case CallingConv::ARM_AAPCS_VFP:
1293     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1294   case CallingConv::C:
1295     if (!Subtarget->isAAPCS_ABI())
1296       return CallingConv::ARM_APCS;
1297     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1298              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1299              !isVarArg)
1300       return CallingConv::ARM_AAPCS_VFP;
1301     else
1302       return CallingConv::ARM_AAPCS;
1303   case CallingConv::Fast:
1304     if (!Subtarget->isAAPCS_ABI()) {
1305       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1306         return CallingConv::Fast;
1307       return CallingConv::ARM_APCS;
1308     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1309       return CallingConv::ARM_AAPCS_VFP;
1310     else
1311       return CallingConv::ARM_AAPCS;
1312   }
1313 }
1314
1315 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1316 /// CallingConvention.
1317 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1318                                                  bool Return,
1319                                                  bool isVarArg) const {
1320   switch (getEffectiveCallingConv(CC, isVarArg)) {
1321   default:
1322     llvm_unreachable("Unsupported calling convention");
1323   case CallingConv::ARM_APCS:
1324     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1325   case CallingConv::ARM_AAPCS:
1326     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1327   case CallingConv::ARM_AAPCS_VFP:
1328     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1329   case CallingConv::Fast:
1330     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1331   case CallingConv::GHC:
1332     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1333   }
1334 }
1335
1336 /// LowerCallResult - Lower the result values of a call into the
1337 /// appropriate copies out of appropriate physical registers.
1338 SDValue
1339 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1340                                    CallingConv::ID CallConv, bool isVarArg,
1341                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1342                                    SDLoc dl, SelectionDAG &DAG,
1343                                    SmallVectorImpl<SDValue> &InVals,
1344                                    bool isThisReturn, SDValue ThisVal) const {
1345
1346   // Assign locations to each value returned by this call.
1347   SmallVector<CCValAssign, 16> RVLocs;
1348   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1349                     *DAG.getContext(), Call);
1350   CCInfo.AnalyzeCallResult(Ins,
1351                            CCAssignFnForNode(CallConv, /* Return*/ true,
1352                                              isVarArg));
1353
1354   // Copy all of the result registers out of their specified physreg.
1355   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1356     CCValAssign VA = RVLocs[i];
1357
1358     // Pass 'this' value directly from the argument to return value, to avoid
1359     // reg unit interference
1360     if (i == 0 && isThisReturn) {
1361       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1362              "unexpected return calling convention register assignment");
1363       InVals.push_back(ThisVal);
1364       continue;
1365     }
1366
1367     SDValue Val;
1368     if (VA.needsCustom()) {
1369       // Handle f64 or half of a v2f64.
1370       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1371                                       InFlag);
1372       Chain = Lo.getValue(1);
1373       InFlag = Lo.getValue(2);
1374       VA = RVLocs[++i]; // skip ahead to next loc
1375       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1376                                       InFlag);
1377       Chain = Hi.getValue(1);
1378       InFlag = Hi.getValue(2);
1379       if (!Subtarget->isLittle())
1380         std::swap (Lo, Hi);
1381       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1382
1383       if (VA.getLocVT() == MVT::v2f64) {
1384         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1385         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1386                           DAG.getConstant(0, dl, MVT::i32));
1387
1388         VA = RVLocs[++i]; // skip ahead to next loc
1389         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1390         Chain = Lo.getValue(1);
1391         InFlag = Lo.getValue(2);
1392         VA = RVLocs[++i]; // skip ahead to next loc
1393         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1394         Chain = Hi.getValue(1);
1395         InFlag = Hi.getValue(2);
1396         if (!Subtarget->isLittle())
1397           std::swap (Lo, Hi);
1398         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1399         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1400                           DAG.getConstant(1, dl, MVT::i32));
1401       }
1402     } else {
1403       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1404                                InFlag);
1405       Chain = Val.getValue(1);
1406       InFlag = Val.getValue(2);
1407     }
1408
1409     switch (VA.getLocInfo()) {
1410     default: llvm_unreachable("Unknown loc info!");
1411     case CCValAssign::Full: break;
1412     case CCValAssign::BCvt:
1413       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1414       break;
1415     }
1416
1417     InVals.push_back(Val);
1418   }
1419
1420   return Chain;
1421 }
1422
1423 /// LowerMemOpCallTo - Store the argument to the stack.
1424 SDValue
1425 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1426                                     SDValue StackPtr, SDValue Arg,
1427                                     SDLoc dl, SelectionDAG &DAG,
1428                                     const CCValAssign &VA,
1429                                     ISD::ArgFlagsTy Flags) const {
1430   unsigned LocMemOffset = VA.getLocMemOffset();
1431   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1432   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1433   return DAG.getStore(Chain, dl, Arg, PtrOff,
1434                       MachinePointerInfo::getStack(LocMemOffset),
1435                       false, false, 0);
1436 }
1437
1438 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1439                                          SDValue Chain, SDValue &Arg,
1440                                          RegsToPassVector &RegsToPass,
1441                                          CCValAssign &VA, CCValAssign &NextVA,
1442                                          SDValue &StackPtr,
1443                                          SmallVectorImpl<SDValue> &MemOpChains,
1444                                          ISD::ArgFlagsTy Flags) const {
1445
1446   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1447                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1448   unsigned id = Subtarget->isLittle() ? 0 : 1;
1449   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1450
1451   if (NextVA.isRegLoc())
1452     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1453   else {
1454     assert(NextVA.isMemLoc());
1455     if (!StackPtr.getNode())
1456       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1457
1458     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1459                                            dl, DAG, NextVA,
1460                                            Flags));
1461   }
1462 }
1463
1464 /// LowerCall - Lowering a call into a callseq_start <-
1465 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1466 /// nodes.
1467 SDValue
1468 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1469                              SmallVectorImpl<SDValue> &InVals) const {
1470   SelectionDAG &DAG                     = CLI.DAG;
1471   SDLoc &dl                             = CLI.DL;
1472   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1473   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1474   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1475   SDValue Chain                         = CLI.Chain;
1476   SDValue Callee                        = CLI.Callee;
1477   bool &isTailCall                      = CLI.IsTailCall;
1478   CallingConv::ID CallConv              = CLI.CallConv;
1479   bool doesNotRet                       = CLI.DoesNotReturn;
1480   bool isVarArg                         = CLI.IsVarArg;
1481
1482   MachineFunction &MF = DAG.getMachineFunction();
1483   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1484   bool isThisReturn   = false;
1485   bool isSibCall      = false;
1486
1487   // Disable tail calls if they're not supported.
1488   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1489     isTailCall = false;
1490
1491   if (isTailCall) {
1492     // Check if it's really possible to do a tail call.
1493     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1494                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1495                                                    Outs, OutVals, Ins, DAG);
1496     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1497       report_fatal_error("failed to perform tail call elimination on a call "
1498                          "site marked musttail");
1499     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1500     // detected sibcalls.
1501     if (isTailCall) {
1502       ++NumTailCalls;
1503       isSibCall = true;
1504     }
1505   }
1506
1507   // Analyze operands of the call, assigning locations to each operand.
1508   SmallVector<CCValAssign, 16> ArgLocs;
1509   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1510                     *DAG.getContext(), Call);
1511   CCInfo.AnalyzeCallOperands(Outs,
1512                              CCAssignFnForNode(CallConv, /* Return*/ false,
1513                                                isVarArg));
1514
1515   // Get a count of how many bytes are to be pushed on the stack.
1516   unsigned NumBytes = CCInfo.getNextStackOffset();
1517
1518   // For tail calls, memory operands are available in our caller's stack.
1519   if (isSibCall)
1520     NumBytes = 0;
1521
1522   // Adjust the stack pointer for the new arguments...
1523   // These operations are automatically eliminated by the prolog/epilog pass
1524   if (!isSibCall)
1525     Chain = DAG.getCALLSEQ_START(Chain,
1526                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1527
1528   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1529
1530   RegsToPassVector RegsToPass;
1531   SmallVector<SDValue, 8> MemOpChains;
1532
1533   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1534   // of tail call optimization, arguments are handled later.
1535   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1536        i != e;
1537        ++i, ++realArgIdx) {
1538     CCValAssign &VA = ArgLocs[i];
1539     SDValue Arg = OutVals[realArgIdx];
1540     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1541     bool isByVal = Flags.isByVal();
1542
1543     // Promote the value if needed.
1544     switch (VA.getLocInfo()) {
1545     default: llvm_unreachable("Unknown loc info!");
1546     case CCValAssign::Full: break;
1547     case CCValAssign::SExt:
1548       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1549       break;
1550     case CCValAssign::ZExt:
1551       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1552       break;
1553     case CCValAssign::AExt:
1554       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1555       break;
1556     case CCValAssign::BCvt:
1557       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1558       break;
1559     }
1560
1561     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1562     if (VA.needsCustom()) {
1563       if (VA.getLocVT() == MVT::v2f64) {
1564         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1565                                   DAG.getConstant(0, dl, MVT::i32));
1566         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1567                                   DAG.getConstant(1, dl, MVT::i32));
1568
1569         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1570                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1571
1572         VA = ArgLocs[++i]; // skip ahead to next loc
1573         if (VA.isRegLoc()) {
1574           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1575                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1576         } else {
1577           assert(VA.isMemLoc());
1578
1579           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1580                                                  dl, DAG, VA, Flags));
1581         }
1582       } else {
1583         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1584                          StackPtr, MemOpChains, Flags);
1585       }
1586     } else if (VA.isRegLoc()) {
1587       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1588         assert(VA.getLocVT() == MVT::i32 &&
1589                "unexpected calling convention register assignment");
1590         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1591                "unexpected use of 'returned'");
1592         isThisReturn = true;
1593       }
1594       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1595     } else if (isByVal) {
1596       assert(VA.isMemLoc());
1597       unsigned offset = 0;
1598
1599       // True if this byval aggregate will be split between registers
1600       // and memory.
1601       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1602       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1603
1604       if (CurByValIdx < ByValArgsCount) {
1605
1606         unsigned RegBegin, RegEnd;
1607         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1608
1609         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1610         unsigned int i, j;
1611         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1612           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1613           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1614           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1615                                      MachinePointerInfo(),
1616                                      false, false, false,
1617                                      DAG.InferPtrAlignment(AddArg));
1618           MemOpChains.push_back(Load.getValue(1));
1619           RegsToPass.push_back(std::make_pair(j, Load));
1620         }
1621
1622         // If parameter size outsides register area, "offset" value
1623         // helps us to calculate stack slot for remained part properly.
1624         offset = RegEnd - RegBegin;
1625
1626         CCInfo.nextInRegsParam();
1627       }
1628
1629       if (Flags.getByValSize() > 4*offset) {
1630         unsigned LocMemOffset = VA.getLocMemOffset();
1631         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1632         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1633                                   StkPtrOff);
1634         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1635         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1636         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1637                                            MVT::i32);
1638         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1639                                             MVT::i32);
1640
1641         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1642         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1643         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1644                                           Ops));
1645       }
1646     } else if (!isSibCall) {
1647       assert(VA.isMemLoc());
1648
1649       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1650                                              dl, DAG, VA, Flags));
1651     }
1652   }
1653
1654   if (!MemOpChains.empty())
1655     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1656
1657   // Build a sequence of copy-to-reg nodes chained together with token chain
1658   // and flag operands which copy the outgoing args into the appropriate regs.
1659   SDValue InFlag;
1660   // Tail call byval lowering might overwrite argument registers so in case of
1661   // tail call optimization the copies to registers are lowered later.
1662   if (!isTailCall)
1663     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1664       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1665                                RegsToPass[i].second, InFlag);
1666       InFlag = Chain.getValue(1);
1667     }
1668
1669   // For tail calls lower the arguments to the 'real' stack slot.
1670   if (isTailCall) {
1671     // Force all the incoming stack arguments to be loaded from the stack
1672     // before any new outgoing arguments are stored to the stack, because the
1673     // outgoing stack slots may alias the incoming argument stack slots, and
1674     // the alias isn't otherwise explicit. This is slightly more conservative
1675     // than necessary, because it means that each store effectively depends
1676     // on every argument instead of just those arguments it would clobber.
1677
1678     // Do not flag preceding copytoreg stuff together with the following stuff.
1679     InFlag = SDValue();
1680     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1681       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1682                                RegsToPass[i].second, InFlag);
1683       InFlag = Chain.getValue(1);
1684     }
1685     InFlag = SDValue();
1686   }
1687
1688   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1689   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1690   // node so that legalize doesn't hack it.
1691   bool isDirect = false;
1692   bool isARMFunc = false;
1693   bool isLocalARMFunc = false;
1694   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1695
1696   if (EnableARMLongCalls) {
1697     assert((Subtarget->isTargetWindows() ||
1698             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1699            "long-calls with non-static relocation model!");
1700     // Handle a global address or an external symbol. If it's not one of
1701     // those, the target's already in a register, so we don't need to do
1702     // anything extra.
1703     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1704       const GlobalValue *GV = G->getGlobal();
1705       // Create a constant pool entry for the callee address
1706       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1707       ARMConstantPoolValue *CPV =
1708         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1709
1710       // Get the address of the callee into a register
1711       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1712       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1713       Callee = DAG.getLoad(getPointerTy(), dl,
1714                            DAG.getEntryNode(), CPAddr,
1715                            MachinePointerInfo::getConstantPool(),
1716                            false, false, false, 0);
1717     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1718       const char *Sym = S->getSymbol();
1719
1720       // Create a constant pool entry for the callee address
1721       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1722       ARMConstantPoolValue *CPV =
1723         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1724                                       ARMPCLabelIndex, 0);
1725       // Get the address of the callee into a register
1726       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1727       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1728       Callee = DAG.getLoad(getPointerTy(), dl,
1729                            DAG.getEntryNode(), CPAddr,
1730                            MachinePointerInfo::getConstantPool(),
1731                            false, false, false, 0);
1732     }
1733   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1734     const GlobalValue *GV = G->getGlobal();
1735     isDirect = true;
1736     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1737     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1738                    getTargetMachine().getRelocationModel() != Reloc::Static;
1739     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1740     // ARM call to a local ARM function is predicable.
1741     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1742     // tBX takes a register source operand.
1743     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1744       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1745       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1746                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1747                                                       0, ARMII::MO_NONLAZY));
1748       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1749                            MachinePointerInfo::getGOT(), false, false, true, 0);
1750     } else if (Subtarget->isTargetCOFF()) {
1751       assert(Subtarget->isTargetWindows() &&
1752              "Windows is the only supported COFF target");
1753       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1754                                  ? ARMII::MO_DLLIMPORT
1755                                  : ARMII::MO_NO_FLAG;
1756       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1757                                           TargetFlags);
1758       if (GV->hasDLLImportStorageClass())
1759         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1760                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1761                                          Callee), MachinePointerInfo::getGOT(),
1762                              false, false, false, 0);
1763     } else {
1764       // On ELF targets for PIC code, direct calls should go through the PLT
1765       unsigned OpFlags = 0;
1766       if (Subtarget->isTargetELF() &&
1767           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1768         OpFlags = ARMII::MO_PLT;
1769       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1770     }
1771   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1772     isDirect = true;
1773     bool isStub = Subtarget->isTargetMachO() &&
1774                   getTargetMachine().getRelocationModel() != Reloc::Static;
1775     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1776     // tBX takes a register source operand.
1777     const char *Sym = S->getSymbol();
1778     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1779       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1780       ARMConstantPoolValue *CPV =
1781         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1782                                       ARMPCLabelIndex, 4);
1783       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1784       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1785       Callee = DAG.getLoad(getPointerTy(), dl,
1786                            DAG.getEntryNode(), CPAddr,
1787                            MachinePointerInfo::getConstantPool(),
1788                            false, false, false, 0);
1789       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1790       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1791                            getPointerTy(), Callee, PICLabel);
1792     } else {
1793       unsigned OpFlags = 0;
1794       // On ELF targets for PIC code, direct calls should go through the PLT
1795       if (Subtarget->isTargetELF() &&
1796                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1797         OpFlags = ARMII::MO_PLT;
1798       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1799     }
1800   }
1801
1802   // FIXME: handle tail calls differently.
1803   unsigned CallOpc;
1804   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1805   if (Subtarget->isThumb()) {
1806     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1807       CallOpc = ARMISD::CALL_NOLINK;
1808     else
1809       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1810   } else {
1811     if (!isDirect && !Subtarget->hasV5TOps())
1812       CallOpc = ARMISD::CALL_NOLINK;
1813     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1814                // Emit regular call when code size is the priority
1815                !HasMinSizeAttr)
1816       // "mov lr, pc; b _foo" to avoid confusing the RSP
1817       CallOpc = ARMISD::CALL_NOLINK;
1818     else
1819       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1820   }
1821
1822   std::vector<SDValue> Ops;
1823   Ops.push_back(Chain);
1824   Ops.push_back(Callee);
1825
1826   // Add argument registers to the end of the list so that they are known live
1827   // into the call.
1828   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1829     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1830                                   RegsToPass[i].second.getValueType()));
1831
1832   // Add a register mask operand representing the call-preserved registers.
1833   if (!isTailCall) {
1834     const uint32_t *Mask;
1835     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1836     if (isThisReturn) {
1837       // For 'this' returns, use the R0-preserving mask if applicable
1838       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1839       if (!Mask) {
1840         // Set isThisReturn to false if the calling convention is not one that
1841         // allows 'returned' to be modeled in this way, so LowerCallResult does
1842         // not try to pass 'this' straight through
1843         isThisReturn = false;
1844         Mask = ARI->getCallPreservedMask(MF, CallConv);
1845       }
1846     } else
1847       Mask = ARI->getCallPreservedMask(MF, CallConv);
1848
1849     assert(Mask && "Missing call preserved mask for calling convention");
1850     Ops.push_back(DAG.getRegisterMask(Mask));
1851   }
1852
1853   if (InFlag.getNode())
1854     Ops.push_back(InFlag);
1855
1856   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1857   if (isTailCall) {
1858     MF.getFrameInfo()->setHasTailCall();
1859     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1860   }
1861
1862   // Returns a chain and a flag for retval copy to use.
1863   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1864   InFlag = Chain.getValue(1);
1865
1866   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1867                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1868   if (!Ins.empty())
1869     InFlag = Chain.getValue(1);
1870
1871   // Handle result values, copying them out of physregs into vregs that we
1872   // return.
1873   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1874                          InVals, isThisReturn,
1875                          isThisReturn ? OutVals[0] : SDValue());
1876 }
1877
1878 /// HandleByVal - Every parameter *after* a byval parameter is passed
1879 /// on the stack.  Remember the next parameter register to allocate,
1880 /// and then confiscate the rest of the parameter registers to insure
1881 /// this.
1882 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1883                                     unsigned Align) const {
1884   assert((State->getCallOrPrologue() == Prologue ||
1885           State->getCallOrPrologue() == Call) &&
1886          "unhandled ParmContext");
1887
1888   // Byval (as with any stack) slots are always at least 4 byte aligned.
1889   Align = std::max(Align, 4U);
1890
1891   unsigned Reg = State->AllocateReg(GPRArgRegs);
1892   if (!Reg)
1893     return;
1894
1895   unsigned AlignInRegs = Align / 4;
1896   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1897   for (unsigned i = 0; i < Waste; ++i)
1898     Reg = State->AllocateReg(GPRArgRegs);
1899
1900   if (!Reg)
1901     return;
1902
1903   unsigned Excess = 4 * (ARM::R4 - Reg);
1904
1905   // Special case when NSAA != SP and parameter size greater than size of
1906   // all remained GPR regs. In that case we can't split parameter, we must
1907   // send it to stack. We also must set NCRN to R4, so waste all
1908   // remained registers.
1909   const unsigned NSAAOffset = State->getNextStackOffset();
1910   if (NSAAOffset != 0 && Size > Excess) {
1911     while (State->AllocateReg(GPRArgRegs))
1912       ;
1913     return;
1914   }
1915
1916   // First register for byval parameter is the first register that wasn't
1917   // allocated before this method call, so it would be "reg".
1918   // If parameter is small enough to be saved in range [reg, r4), then
1919   // the end (first after last) register would be reg + param-size-in-regs,
1920   // else parameter would be splitted between registers and stack,
1921   // end register would be r4 in this case.
1922   unsigned ByValRegBegin = Reg;
1923   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1924   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1925   // Note, first register is allocated in the beginning of function already,
1926   // allocate remained amount of registers we need.
1927   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1928     State->AllocateReg(GPRArgRegs);
1929   // A byval parameter that is split between registers and memory needs its
1930   // size truncated here.
1931   // In the case where the entire structure fits in registers, we set the
1932   // size in memory to zero.
1933   Size = std::max<int>(Size - Excess, 0);
1934 }
1935
1936
1937 /// MatchingStackOffset - Return true if the given stack call argument is
1938 /// already available in the same position (relatively) of the caller's
1939 /// incoming argument stack.
1940 static
1941 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1942                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1943                          const TargetInstrInfo *TII) {
1944   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1945   int FI = INT_MAX;
1946   if (Arg.getOpcode() == ISD::CopyFromReg) {
1947     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1948     if (!TargetRegisterInfo::isVirtualRegister(VR))
1949       return false;
1950     MachineInstr *Def = MRI->getVRegDef(VR);
1951     if (!Def)
1952       return false;
1953     if (!Flags.isByVal()) {
1954       if (!TII->isLoadFromStackSlot(Def, FI))
1955         return false;
1956     } else {
1957       return false;
1958     }
1959   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1960     if (Flags.isByVal())
1961       // ByVal argument is passed in as a pointer but it's now being
1962       // dereferenced. e.g.
1963       // define @foo(%struct.X* %A) {
1964       //   tail call @bar(%struct.X* byval %A)
1965       // }
1966       return false;
1967     SDValue Ptr = Ld->getBasePtr();
1968     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1969     if (!FINode)
1970       return false;
1971     FI = FINode->getIndex();
1972   } else
1973     return false;
1974
1975   assert(FI != INT_MAX);
1976   if (!MFI->isFixedObjectIndex(FI))
1977     return false;
1978   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1979 }
1980
1981 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1982 /// for tail call optimization. Targets which want to do tail call
1983 /// optimization should implement this function.
1984 bool
1985 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1986                                                      CallingConv::ID CalleeCC,
1987                                                      bool isVarArg,
1988                                                      bool isCalleeStructRet,
1989                                                      bool isCallerStructRet,
1990                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1991                                     const SmallVectorImpl<SDValue> &OutVals,
1992                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1993                                                      SelectionDAG& DAG) const {
1994   const Function *CallerF = DAG.getMachineFunction().getFunction();
1995   CallingConv::ID CallerCC = CallerF->getCallingConv();
1996   bool CCMatch = CallerCC == CalleeCC;
1997
1998   // Look for obvious safe cases to perform tail call optimization that do not
1999   // require ABI changes. This is what gcc calls sibcall.
2000
2001   // Do not sibcall optimize vararg calls unless the call site is not passing
2002   // any arguments.
2003   if (isVarArg && !Outs.empty())
2004     return false;
2005
2006   // Exception-handling functions need a special set of instructions to indicate
2007   // a return to the hardware. Tail-calling another function would probably
2008   // break this.
2009   if (CallerF->hasFnAttribute("interrupt"))
2010     return false;
2011
2012   // Also avoid sibcall optimization if either caller or callee uses struct
2013   // return semantics.
2014   if (isCalleeStructRet || isCallerStructRet)
2015     return false;
2016
2017   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2018   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2019   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2020   // support in the assembler and linker to be used. This would need to be
2021   // fixed to fully support tail calls in Thumb1.
2022   //
2023   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2024   // LR.  This means if we need to reload LR, it takes an extra instructions,
2025   // which outweighs the value of the tail call; but here we don't know yet
2026   // whether LR is going to be used.  Probably the right approach is to
2027   // generate the tail call here and turn it back into CALL/RET in
2028   // emitEpilogue if LR is used.
2029
2030   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2031   // but we need to make sure there are enough registers; the only valid
2032   // registers are the 4 used for parameters.  We don't currently do this
2033   // case.
2034   if (Subtarget->isThumb1Only())
2035     return false;
2036
2037   // Externally-defined functions with weak linkage should not be
2038   // tail-called on ARM when the OS does not support dynamic
2039   // pre-emption of symbols, as the AAELF spec requires normal calls
2040   // to undefined weak functions to be replaced with a NOP or jump to the
2041   // next instruction. The behaviour of branch instructions in this
2042   // situation (as used for tail calls) is implementation-defined, so we
2043   // cannot rely on the linker replacing the tail call with a return.
2044   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2045     const GlobalValue *GV = G->getGlobal();
2046     const Triple TT(getTargetMachine().getTargetTriple());
2047     if (GV->hasExternalWeakLinkage() &&
2048         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2049       return false;
2050   }
2051
2052   // If the calling conventions do not match, then we'd better make sure the
2053   // results are returned in the same way as what the caller expects.
2054   if (!CCMatch) {
2055     SmallVector<CCValAssign, 16> RVLocs1;
2056     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2057                        *DAG.getContext(), Call);
2058     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2059
2060     SmallVector<CCValAssign, 16> RVLocs2;
2061     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2062                        *DAG.getContext(), Call);
2063     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2064
2065     if (RVLocs1.size() != RVLocs2.size())
2066       return false;
2067     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2068       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2069         return false;
2070       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2071         return false;
2072       if (RVLocs1[i].isRegLoc()) {
2073         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2074           return false;
2075       } else {
2076         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2077           return false;
2078       }
2079     }
2080   }
2081
2082   // If Caller's vararg or byval argument has been split between registers and
2083   // stack, do not perform tail call, since part of the argument is in caller's
2084   // local frame.
2085   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2086                                       getInfo<ARMFunctionInfo>();
2087   if (AFI_Caller->getArgRegsSaveSize())
2088     return false;
2089
2090   // If the callee takes no arguments then go on to check the results of the
2091   // call.
2092   if (!Outs.empty()) {
2093     // Check if stack adjustment is needed. For now, do not do this if any
2094     // argument is passed on the stack.
2095     SmallVector<CCValAssign, 16> ArgLocs;
2096     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2097                       *DAG.getContext(), Call);
2098     CCInfo.AnalyzeCallOperands(Outs,
2099                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2100     if (CCInfo.getNextStackOffset()) {
2101       MachineFunction &MF = DAG.getMachineFunction();
2102
2103       // Check if the arguments are already laid out in the right way as
2104       // the caller's fixed stack objects.
2105       MachineFrameInfo *MFI = MF.getFrameInfo();
2106       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2107       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2108       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2109            i != e;
2110            ++i, ++realArgIdx) {
2111         CCValAssign &VA = ArgLocs[i];
2112         EVT RegVT = VA.getLocVT();
2113         SDValue Arg = OutVals[realArgIdx];
2114         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2115         if (VA.getLocInfo() == CCValAssign::Indirect)
2116           return false;
2117         if (VA.needsCustom()) {
2118           // f64 and vector types are split into multiple registers or
2119           // register/stack-slot combinations.  The types will not match
2120           // the registers; give up on memory f64 refs until we figure
2121           // out what to do about this.
2122           if (!VA.isRegLoc())
2123             return false;
2124           if (!ArgLocs[++i].isRegLoc())
2125             return false;
2126           if (RegVT == MVT::v2f64) {
2127             if (!ArgLocs[++i].isRegLoc())
2128               return false;
2129             if (!ArgLocs[++i].isRegLoc())
2130               return false;
2131           }
2132         } else if (!VA.isRegLoc()) {
2133           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2134                                    MFI, MRI, TII))
2135             return false;
2136         }
2137       }
2138     }
2139   }
2140
2141   return true;
2142 }
2143
2144 bool
2145 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2146                                   MachineFunction &MF, bool isVarArg,
2147                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2148                                   LLVMContext &Context) const {
2149   SmallVector<CCValAssign, 16> RVLocs;
2150   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2151   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2152                                                     isVarArg));
2153 }
2154
2155 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2156                                     SDLoc DL, SelectionDAG &DAG) {
2157   const MachineFunction &MF = DAG.getMachineFunction();
2158   const Function *F = MF.getFunction();
2159
2160   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2161
2162   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2163   // version of the "preferred return address". These offsets affect the return
2164   // instruction if this is a return from PL1 without hypervisor extensions.
2165   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2166   //    SWI:     0      "subs pc, lr, #0"
2167   //    ABORT:   +4     "subs pc, lr, #4"
2168   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2169   // UNDEF varies depending on where the exception came from ARM or Thumb
2170   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2171
2172   int64_t LROffset;
2173   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2174       IntKind == "ABORT")
2175     LROffset = 4;
2176   else if (IntKind == "SWI" || IntKind == "UNDEF")
2177     LROffset = 0;
2178   else
2179     report_fatal_error("Unsupported interrupt attribute. If present, value "
2180                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2181
2182   RetOps.insert(RetOps.begin() + 1,
2183                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2184
2185   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2186 }
2187
2188 SDValue
2189 ARMTargetLowering::LowerReturn(SDValue Chain,
2190                                CallingConv::ID CallConv, bool isVarArg,
2191                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2192                                const SmallVectorImpl<SDValue> &OutVals,
2193                                SDLoc dl, SelectionDAG &DAG) const {
2194
2195   // CCValAssign - represent the assignment of the return value to a location.
2196   SmallVector<CCValAssign, 16> RVLocs;
2197
2198   // CCState - Info about the registers and stack slots.
2199   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2200                     *DAG.getContext(), Call);
2201
2202   // Analyze outgoing return values.
2203   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2204                                                isVarArg));
2205
2206   SDValue Flag;
2207   SmallVector<SDValue, 4> RetOps;
2208   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2209   bool isLittleEndian = Subtarget->isLittle();
2210
2211   MachineFunction &MF = DAG.getMachineFunction();
2212   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2213   AFI->setReturnRegsCount(RVLocs.size());
2214
2215   // Copy the result values into the output registers.
2216   for (unsigned i = 0, realRVLocIdx = 0;
2217        i != RVLocs.size();
2218        ++i, ++realRVLocIdx) {
2219     CCValAssign &VA = RVLocs[i];
2220     assert(VA.isRegLoc() && "Can only return in registers!");
2221
2222     SDValue Arg = OutVals[realRVLocIdx];
2223
2224     switch (VA.getLocInfo()) {
2225     default: llvm_unreachable("Unknown loc info!");
2226     case CCValAssign::Full: break;
2227     case CCValAssign::BCvt:
2228       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2229       break;
2230     }
2231
2232     if (VA.needsCustom()) {
2233       if (VA.getLocVT() == MVT::v2f64) {
2234         // Extract the first half and return it in two registers.
2235         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2236                                    DAG.getConstant(0, dl, MVT::i32));
2237         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2238                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2239
2240         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2241                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2242                                  Flag);
2243         Flag = Chain.getValue(1);
2244         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2245         VA = RVLocs[++i]; // skip ahead to next loc
2246         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2247                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2248                                  Flag);
2249         Flag = Chain.getValue(1);
2250         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2251         VA = RVLocs[++i]; // skip ahead to next loc
2252
2253         // Extract the 2nd half and fall through to handle it as an f64 value.
2254         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2255                           DAG.getConstant(1, dl, MVT::i32));
2256       }
2257       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2258       // available.
2259       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2260                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2261       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2262                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2263                                Flag);
2264       Flag = Chain.getValue(1);
2265       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2266       VA = RVLocs[++i]; // skip ahead to next loc
2267       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2268                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2269                                Flag);
2270     } else
2271       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2272
2273     // Guarantee that all emitted copies are
2274     // stuck together, avoiding something bad.
2275     Flag = Chain.getValue(1);
2276     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2277   }
2278
2279   // Update chain and glue.
2280   RetOps[0] = Chain;
2281   if (Flag.getNode())
2282     RetOps.push_back(Flag);
2283
2284   // CPUs which aren't M-class use a special sequence to return from
2285   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2286   // though we use "subs pc, lr, #N").
2287   //
2288   // M-class CPUs actually use a normal return sequence with a special
2289   // (hardware-provided) value in LR, so the normal code path works.
2290   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2291       !Subtarget->isMClass()) {
2292     if (Subtarget->isThumb1Only())
2293       report_fatal_error("interrupt attribute is not supported in Thumb1");
2294     return LowerInterruptReturn(RetOps, dl, DAG);
2295   }
2296
2297   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2298 }
2299
2300 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2301   if (N->getNumValues() != 1)
2302     return false;
2303   if (!N->hasNUsesOfValue(1, 0))
2304     return false;
2305
2306   SDValue TCChain = Chain;
2307   SDNode *Copy = *N->use_begin();
2308   if (Copy->getOpcode() == ISD::CopyToReg) {
2309     // If the copy has a glue operand, we conservatively assume it isn't safe to
2310     // perform a tail call.
2311     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2312       return false;
2313     TCChain = Copy->getOperand(0);
2314   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2315     SDNode *VMov = Copy;
2316     // f64 returned in a pair of GPRs.
2317     SmallPtrSet<SDNode*, 2> Copies;
2318     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2319          UI != UE; ++UI) {
2320       if (UI->getOpcode() != ISD::CopyToReg)
2321         return false;
2322       Copies.insert(*UI);
2323     }
2324     if (Copies.size() > 2)
2325       return false;
2326
2327     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2328          UI != UE; ++UI) {
2329       SDValue UseChain = UI->getOperand(0);
2330       if (Copies.count(UseChain.getNode()))
2331         // Second CopyToReg
2332         Copy = *UI;
2333       else {
2334         // We are at the top of this chain.
2335         // If the copy has a glue operand, we conservatively assume it
2336         // isn't safe to perform a tail call.
2337         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2338           return false;
2339         // First CopyToReg
2340         TCChain = UseChain;
2341       }
2342     }
2343   } else if (Copy->getOpcode() == ISD::BITCAST) {
2344     // f32 returned in a single GPR.
2345     if (!Copy->hasOneUse())
2346       return false;
2347     Copy = *Copy->use_begin();
2348     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2349       return false;
2350     // If the copy has a glue operand, we conservatively assume it isn't safe to
2351     // perform a tail call.
2352     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2353       return false;
2354     TCChain = Copy->getOperand(0);
2355   } else {
2356     return false;
2357   }
2358
2359   bool HasRet = false;
2360   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2361        UI != UE; ++UI) {
2362     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2363         UI->getOpcode() != ARMISD::INTRET_FLAG)
2364       return false;
2365     HasRet = true;
2366   }
2367
2368   if (!HasRet)
2369     return false;
2370
2371   Chain = TCChain;
2372   return true;
2373 }
2374
2375 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2376   if (!Subtarget->supportsTailCall())
2377     return false;
2378
2379   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2380     return false;
2381
2382   return !Subtarget->isThumb1Only();
2383 }
2384
2385 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2386 // and pass the lower and high parts through.
2387 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2388   SDLoc DL(Op);
2389   SDValue WriteValue = Op->getOperand(2);
2390
2391   // This function is only supposed to be called for i64 type argument.
2392   assert(WriteValue.getValueType() == MVT::i64
2393           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2394
2395   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2396                            DAG.getConstant(0, DL, MVT::i32));
2397   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2398                            DAG.getConstant(1, DL, MVT::i32));
2399   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2400   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2401 }
2402
2403 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2404 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2405 // one of the above mentioned nodes. It has to be wrapped because otherwise
2406 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2407 // be used to form addressing mode. These wrapped nodes will be selected
2408 // into MOVi.
2409 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2410   EVT PtrVT = Op.getValueType();
2411   // FIXME there is no actual debug info here
2412   SDLoc dl(Op);
2413   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2414   SDValue Res;
2415   if (CP->isMachineConstantPoolEntry())
2416     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2417                                     CP->getAlignment());
2418   else
2419     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2420                                     CP->getAlignment());
2421   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2422 }
2423
2424 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2425   return MachineJumpTableInfo::EK_Inline;
2426 }
2427
2428 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2429                                              SelectionDAG &DAG) const {
2430   MachineFunction &MF = DAG.getMachineFunction();
2431   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2432   unsigned ARMPCLabelIndex = 0;
2433   SDLoc DL(Op);
2434   EVT PtrVT = getPointerTy();
2435   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2436   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2437   SDValue CPAddr;
2438   if (RelocM == Reloc::Static) {
2439     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2440   } else {
2441     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2442     ARMPCLabelIndex = AFI->createPICLabelUId();
2443     ARMConstantPoolValue *CPV =
2444       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2445                                       ARMCP::CPBlockAddress, PCAdj);
2446     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2447   }
2448   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2449   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2450                                MachinePointerInfo::getConstantPool(),
2451                                false, false, false, 0);
2452   if (RelocM == Reloc::Static)
2453     return Result;
2454   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2455   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2456 }
2457
2458 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2459 SDValue
2460 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2461                                                  SelectionDAG &DAG) const {
2462   SDLoc dl(GA);
2463   EVT PtrVT = getPointerTy();
2464   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2465   MachineFunction &MF = DAG.getMachineFunction();
2466   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2467   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2468   ARMConstantPoolValue *CPV =
2469     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2470                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2471   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2472   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2473   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2474                          MachinePointerInfo::getConstantPool(),
2475                          false, false, false, 0);
2476   SDValue Chain = Argument.getValue(1);
2477
2478   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2479   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2480
2481   // call __tls_get_addr.
2482   ArgListTy Args;
2483   ArgListEntry Entry;
2484   Entry.Node = Argument;
2485   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2486   Args.push_back(Entry);
2487
2488   // FIXME: is there useful debug info available here?
2489   TargetLowering::CallLoweringInfo CLI(DAG);
2490   CLI.setDebugLoc(dl).setChain(Chain)
2491     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2492                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2493                0);
2494
2495   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2496   return CallResult.first;
2497 }
2498
2499 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2500 // "local exec" model.
2501 SDValue
2502 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2503                                         SelectionDAG &DAG,
2504                                         TLSModel::Model model) const {
2505   const GlobalValue *GV = GA->getGlobal();
2506   SDLoc dl(GA);
2507   SDValue Offset;
2508   SDValue Chain = DAG.getEntryNode();
2509   EVT PtrVT = getPointerTy();
2510   // Get the Thread Pointer
2511   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2512
2513   if (model == TLSModel::InitialExec) {
2514     MachineFunction &MF = DAG.getMachineFunction();
2515     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2516     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2517     // Initial exec model.
2518     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2519     ARMConstantPoolValue *CPV =
2520       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2521                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2522                                       true);
2523     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2524     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2525     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2526                          MachinePointerInfo::getConstantPool(),
2527                          false, false, false, 0);
2528     Chain = Offset.getValue(1);
2529
2530     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2531     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2532
2533     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2534                          MachinePointerInfo::getConstantPool(),
2535                          false, false, false, 0);
2536   } else {
2537     // local exec model
2538     assert(model == TLSModel::LocalExec);
2539     ARMConstantPoolValue *CPV =
2540       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2541     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2542     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2543     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2544                          MachinePointerInfo::getConstantPool(),
2545                          false, false, false, 0);
2546   }
2547
2548   // The address of the thread local variable is the add of the thread
2549   // pointer with the offset of the variable.
2550   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2551 }
2552
2553 SDValue
2554 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2555   // TODO: implement the "local dynamic" model
2556   assert(Subtarget->isTargetELF() &&
2557          "TLS not implemented for non-ELF targets");
2558   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2559
2560   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2561
2562   switch (model) {
2563     case TLSModel::GeneralDynamic:
2564     case TLSModel::LocalDynamic:
2565       return LowerToTLSGeneralDynamicModel(GA, DAG);
2566     case TLSModel::InitialExec:
2567     case TLSModel::LocalExec:
2568       return LowerToTLSExecModels(GA, DAG, model);
2569   }
2570   llvm_unreachable("bogus TLS model");
2571 }
2572
2573 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2574                                                  SelectionDAG &DAG) const {
2575   EVT PtrVT = getPointerTy();
2576   SDLoc dl(Op);
2577   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2578   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2579     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2580     ARMConstantPoolValue *CPV =
2581       ARMConstantPoolConstant::Create(GV,
2582                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2583     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2584     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2585     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2586                                  CPAddr,
2587                                  MachinePointerInfo::getConstantPool(),
2588                                  false, false, false, 0);
2589     SDValue Chain = Result.getValue(1);
2590     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2591     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2592     if (!UseGOTOFF)
2593       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2594                            MachinePointerInfo::getGOT(),
2595                            false, false, false, 0);
2596     return Result;
2597   }
2598
2599   // If we have T2 ops, we can materialize the address directly via movt/movw
2600   // pair. This is always cheaper.
2601   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2602     ++NumMovwMovt;
2603     // FIXME: Once remat is capable of dealing with instructions with register
2604     // operands, expand this into two nodes.
2605     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2606                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2607   } else {
2608     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2609     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2610     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2611                        MachinePointerInfo::getConstantPool(),
2612                        false, false, false, 0);
2613   }
2614 }
2615
2616 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2617                                                     SelectionDAG &DAG) const {
2618   EVT PtrVT = getPointerTy();
2619   SDLoc dl(Op);
2620   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2621   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2622
2623   if (Subtarget->useMovt(DAG.getMachineFunction()))
2624     ++NumMovwMovt;
2625
2626   // FIXME: Once remat is capable of dealing with instructions with register
2627   // operands, expand this into multiple nodes
2628   unsigned Wrapper =
2629       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2630
2631   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2632   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2633
2634   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2635     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2636                          MachinePointerInfo::getGOT(), false, false, false, 0);
2637   return Result;
2638 }
2639
2640 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2641                                                      SelectionDAG &DAG) const {
2642   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2643   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2644          "Windows on ARM expects to use movw/movt");
2645
2646   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2647   const ARMII::TOF TargetFlags =
2648     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2649   EVT PtrVT = getPointerTy();
2650   SDValue Result;
2651   SDLoc DL(Op);
2652
2653   ++NumMovwMovt;
2654
2655   // FIXME: Once remat is capable of dealing with instructions with register
2656   // operands, expand this into two nodes.
2657   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2658                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2659                                                   TargetFlags));
2660   if (GV->hasDLLImportStorageClass())
2661     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2662                          MachinePointerInfo::getGOT(), false, false, false, 0);
2663   return Result;
2664 }
2665
2666 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2667                                                     SelectionDAG &DAG) const {
2668   assert(Subtarget->isTargetELF() &&
2669          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2670   MachineFunction &MF = DAG.getMachineFunction();
2671   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2672   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2673   EVT PtrVT = getPointerTy();
2674   SDLoc dl(Op);
2675   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2676   ARMConstantPoolValue *CPV =
2677     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2678                                   ARMPCLabelIndex, PCAdj);
2679   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2680   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2681   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2682                                MachinePointerInfo::getConstantPool(),
2683                                false, false, false, 0);
2684   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2685   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2686 }
2687
2688 SDValue
2689 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2690   SDLoc dl(Op);
2691   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2692   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2693                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2694                      Op.getOperand(1), Val);
2695 }
2696
2697 SDValue
2698 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2699   SDLoc dl(Op);
2700   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2701                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2702 }
2703
2704 SDValue
2705 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2706                                           const ARMSubtarget *Subtarget) const {
2707   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2708   SDLoc dl(Op);
2709   switch (IntNo) {
2710   default: return SDValue();    // Don't custom lower most intrinsics.
2711   case Intrinsic::arm_rbit: {
2712     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2713            "RBIT intrinsic must have i32 type!");
2714     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2715   }
2716   case Intrinsic::arm_thread_pointer: {
2717     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2718     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2719   }
2720   case Intrinsic::eh_sjlj_lsda: {
2721     MachineFunction &MF = DAG.getMachineFunction();
2722     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2723     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2724     EVT PtrVT = getPointerTy();
2725     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2726     SDValue CPAddr;
2727     unsigned PCAdj = (RelocM != Reloc::PIC_)
2728       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2729     ARMConstantPoolValue *CPV =
2730       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2731                                       ARMCP::CPLSDA, PCAdj);
2732     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2733     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2734     SDValue Result =
2735       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2736                   MachinePointerInfo::getConstantPool(),
2737                   false, false, false, 0);
2738
2739     if (RelocM == Reloc::PIC_) {
2740       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2741       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2742     }
2743     return Result;
2744   }
2745   case Intrinsic::arm_neon_vmulls:
2746   case Intrinsic::arm_neon_vmullu: {
2747     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2748       ? ARMISD::VMULLs : ARMISD::VMULLu;
2749     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2750                        Op.getOperand(1), Op.getOperand(2));
2751   }
2752   }
2753 }
2754
2755 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2756                                  const ARMSubtarget *Subtarget) {
2757   // FIXME: handle "fence singlethread" more efficiently.
2758   SDLoc dl(Op);
2759   if (!Subtarget->hasDataBarrier()) {
2760     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2761     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2762     // here.
2763     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2764            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2765     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2766                        DAG.getConstant(0, dl, MVT::i32));
2767   }
2768
2769   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2770   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2771   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2772   if (Subtarget->isMClass()) {
2773     // Only a full system barrier exists in the M-class architectures.
2774     Domain = ARM_MB::SY;
2775   } else if (Subtarget->isSwift() && Ord == Release) {
2776     // Swift happens to implement ISHST barriers in a way that's compatible with
2777     // Release semantics but weaker than ISH so we'd be fools not to use
2778     // it. Beware: other processors probably don't!
2779     Domain = ARM_MB::ISHST;
2780   }
2781
2782   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2783                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2784                      DAG.getConstant(Domain, dl, MVT::i32));
2785 }
2786
2787 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2788                              const ARMSubtarget *Subtarget) {
2789   // ARM pre v5TE and Thumb1 does not have preload instructions.
2790   if (!(Subtarget->isThumb2() ||
2791         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2792     // Just preserve the chain.
2793     return Op.getOperand(0);
2794
2795   SDLoc dl(Op);
2796   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2797   if (!isRead &&
2798       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2799     // ARMv7 with MP extension has PLDW.
2800     return Op.getOperand(0);
2801
2802   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2803   if (Subtarget->isThumb()) {
2804     // Invert the bits.
2805     isRead = ~isRead & 1;
2806     isData = ~isData & 1;
2807   }
2808
2809   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2810                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2811                      DAG.getConstant(isData, dl, MVT::i32));
2812 }
2813
2814 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2815   MachineFunction &MF = DAG.getMachineFunction();
2816   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2817
2818   // vastart just stores the address of the VarArgsFrameIndex slot into the
2819   // memory location argument.
2820   SDLoc dl(Op);
2821   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2822   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2823   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2824   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2825                       MachinePointerInfo(SV), false, false, 0);
2826 }
2827
2828 SDValue
2829 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2830                                         SDValue &Root, SelectionDAG &DAG,
2831                                         SDLoc dl) const {
2832   MachineFunction &MF = DAG.getMachineFunction();
2833   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2834
2835   const TargetRegisterClass *RC;
2836   if (AFI->isThumb1OnlyFunction())
2837     RC = &ARM::tGPRRegClass;
2838   else
2839     RC = &ARM::GPRRegClass;
2840
2841   // Transform the arguments stored in physical registers into virtual ones.
2842   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2843   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2844
2845   SDValue ArgValue2;
2846   if (NextVA.isMemLoc()) {
2847     MachineFrameInfo *MFI = MF.getFrameInfo();
2848     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2849
2850     // Create load node to retrieve arguments from the stack.
2851     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2852     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2853                             MachinePointerInfo::getFixedStack(FI),
2854                             false, false, false, 0);
2855   } else {
2856     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2857     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2858   }
2859   if (!Subtarget->isLittle())
2860     std::swap (ArgValue, ArgValue2);
2861   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2862 }
2863
2864 // The remaining GPRs hold either the beginning of variable-argument
2865 // data, or the beginning of an aggregate passed by value (usually
2866 // byval).  Either way, we allocate stack slots adjacent to the data
2867 // provided by our caller, and store the unallocated registers there.
2868 // If this is a variadic function, the va_list pointer will begin with
2869 // these values; otherwise, this reassembles a (byval) structure that
2870 // was split between registers and memory.
2871 // Return: The frame index registers were stored into.
2872 int
2873 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2874                                   SDLoc dl, SDValue &Chain,
2875                                   const Value *OrigArg,
2876                                   unsigned InRegsParamRecordIdx,
2877                                   int ArgOffset,
2878                                   unsigned ArgSize) const {
2879   // Currently, two use-cases possible:
2880   // Case #1. Non-var-args function, and we meet first byval parameter.
2881   //          Setup first unallocated register as first byval register;
2882   //          eat all remained registers
2883   //          (these two actions are performed by HandleByVal method).
2884   //          Then, here, we initialize stack frame with
2885   //          "store-reg" instructions.
2886   // Case #2. Var-args function, that doesn't contain byval parameters.
2887   //          The same: eat all remained unallocated registers,
2888   //          initialize stack frame.
2889
2890   MachineFunction &MF = DAG.getMachineFunction();
2891   MachineFrameInfo *MFI = MF.getFrameInfo();
2892   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2893   unsigned RBegin, REnd;
2894   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2895     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2896   } else {
2897     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2898     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2899     REnd = ARM::R4;
2900   }
2901
2902   if (REnd != RBegin)
2903     ArgOffset = -4 * (ARM::R4 - RBegin);
2904
2905   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2906   SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2907
2908   SmallVector<SDValue, 4> MemOps;
2909   const TargetRegisterClass *RC =
2910       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2911
2912   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2913     unsigned VReg = MF.addLiveIn(Reg, RC);
2914     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2915     SDValue Store =
2916         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2917                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2918     MemOps.push_back(Store);
2919     FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2920                       DAG.getConstant(4, dl, getPointerTy()));
2921   }
2922
2923   if (!MemOps.empty())
2924     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2925   return FrameIndex;
2926 }
2927
2928 // Setup stack frame, the va_list pointer will start from.
2929 void
2930 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2931                                         SDLoc dl, SDValue &Chain,
2932                                         unsigned ArgOffset,
2933                                         unsigned TotalArgRegsSaveSize,
2934                                         bool ForceMutable) const {
2935   MachineFunction &MF = DAG.getMachineFunction();
2936   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2937
2938   // Try to store any remaining integer argument regs
2939   // to their spots on the stack so that they may be loaded by deferencing
2940   // the result of va_next.
2941   // If there is no regs to be stored, just point address after last
2942   // argument passed via stack.
2943   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2944                                   CCInfo.getInRegsParamsCount(),
2945                                   CCInfo.getNextStackOffset(), 4);
2946   AFI->setVarArgsFrameIndex(FrameIndex);
2947 }
2948
2949 SDValue
2950 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2951                                         CallingConv::ID CallConv, bool isVarArg,
2952                                         const SmallVectorImpl<ISD::InputArg>
2953                                           &Ins,
2954                                         SDLoc dl, SelectionDAG &DAG,
2955                                         SmallVectorImpl<SDValue> &InVals)
2956                                           const {
2957   MachineFunction &MF = DAG.getMachineFunction();
2958   MachineFrameInfo *MFI = MF.getFrameInfo();
2959
2960   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2961
2962   // Assign locations to all of the incoming arguments.
2963   SmallVector<CCValAssign, 16> ArgLocs;
2964   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2965                     *DAG.getContext(), Prologue);
2966   CCInfo.AnalyzeFormalArguments(Ins,
2967                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2968                                                   isVarArg));
2969
2970   SmallVector<SDValue, 16> ArgValues;
2971   SDValue ArgValue;
2972   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2973   unsigned CurArgIdx = 0;
2974
2975   // Initially ArgRegsSaveSize is zero.
2976   // Then we increase this value each time we meet byval parameter.
2977   // We also increase this value in case of varargs function.
2978   AFI->setArgRegsSaveSize(0);
2979
2980   // Calculate the amount of stack space that we need to allocate to store
2981   // byval and variadic arguments that are passed in registers.
2982   // We need to know this before we allocate the first byval or variadic
2983   // argument, as they will be allocated a stack slot below the CFA (Canonical
2984   // Frame Address, the stack pointer at entry to the function).
2985   unsigned ArgRegBegin = ARM::R4;
2986   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2987     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
2988       break;
2989
2990     CCValAssign &VA = ArgLocs[i];
2991     unsigned Index = VA.getValNo();
2992     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
2993     if (!Flags.isByVal())
2994       continue;
2995
2996     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
2997     unsigned RBegin, REnd;
2998     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
2999     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3000
3001     CCInfo.nextInRegsParam();
3002   }
3003   CCInfo.rewindByValRegsInfo();
3004
3005   int lastInsIndex = -1;
3006   if (isVarArg && MFI->hasVAStart()) {
3007     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3008     if (RegIdx != array_lengthof(GPRArgRegs))
3009       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3010   }
3011
3012   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3013   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3014
3015   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3016     CCValAssign &VA = ArgLocs[i];
3017     if (Ins[VA.getValNo()].isOrigArg()) {
3018       std::advance(CurOrigArg,
3019                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3020       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3021     }
3022     // Arguments stored in registers.
3023     if (VA.isRegLoc()) {
3024       EVT RegVT = VA.getLocVT();
3025
3026       if (VA.needsCustom()) {
3027         // f64 and vector types are split up into multiple registers or
3028         // combinations of registers and stack slots.
3029         if (VA.getLocVT() == MVT::v2f64) {
3030           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3031                                                    Chain, DAG, dl);
3032           VA = ArgLocs[++i]; // skip ahead to next loc
3033           SDValue ArgValue2;
3034           if (VA.isMemLoc()) {
3035             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3036             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3037             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3038                                     MachinePointerInfo::getFixedStack(FI),
3039                                     false, false, false, 0);
3040           } else {
3041             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3042                                              Chain, DAG, dl);
3043           }
3044           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3045           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3046                                  ArgValue, ArgValue1,
3047                                  DAG.getIntPtrConstant(0, dl));
3048           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3049                                  ArgValue, ArgValue2,
3050                                  DAG.getIntPtrConstant(1, dl));
3051         } else
3052           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3053
3054       } else {
3055         const TargetRegisterClass *RC;
3056
3057         if (RegVT == MVT::f32)
3058           RC = &ARM::SPRRegClass;
3059         else if (RegVT == MVT::f64)
3060           RC = &ARM::DPRRegClass;
3061         else if (RegVT == MVT::v2f64)
3062           RC = &ARM::QPRRegClass;
3063         else if (RegVT == MVT::i32)
3064           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3065                                            : &ARM::GPRRegClass;
3066         else
3067           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3068
3069         // Transform the arguments in physical registers into virtual ones.
3070         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3071         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3072       }
3073
3074       // If this is an 8 or 16-bit value, it is really passed promoted
3075       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3076       // truncate to the right size.
3077       switch (VA.getLocInfo()) {
3078       default: llvm_unreachable("Unknown loc info!");
3079       case CCValAssign::Full: break;
3080       case CCValAssign::BCvt:
3081         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3082         break;
3083       case CCValAssign::SExt:
3084         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3085                                DAG.getValueType(VA.getValVT()));
3086         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3087         break;
3088       case CCValAssign::ZExt:
3089         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3090                                DAG.getValueType(VA.getValVT()));
3091         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3092         break;
3093       }
3094
3095       InVals.push_back(ArgValue);
3096
3097     } else { // VA.isRegLoc()
3098
3099       // sanity check
3100       assert(VA.isMemLoc());
3101       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3102
3103       int index = VA.getValNo();
3104
3105       // Some Ins[] entries become multiple ArgLoc[] entries.
3106       // Process them only once.
3107       if (index != lastInsIndex)
3108         {
3109           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3110           // FIXME: For now, all byval parameter objects are marked mutable.
3111           // This can be changed with more analysis.
3112           // In case of tail call optimization mark all arguments mutable.
3113           // Since they could be overwritten by lowering of arguments in case of
3114           // a tail call.
3115           if (Flags.isByVal()) {
3116             assert(Ins[index].isOrigArg() &&
3117                    "Byval arguments cannot be implicit");
3118             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3119
3120             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3121                                             CurByValIndex, VA.getLocMemOffset(),
3122                                             Flags.getByValSize());
3123             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3124             CCInfo.nextInRegsParam();
3125           } else {
3126             unsigned FIOffset = VA.getLocMemOffset();
3127             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3128                                             FIOffset, true);
3129
3130             // Create load nodes to retrieve arguments from the stack.
3131             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3132             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3133                                          MachinePointerInfo::getFixedStack(FI),
3134                                          false, false, false, 0));
3135           }
3136           lastInsIndex = index;
3137         }
3138     }
3139   }
3140
3141   // varargs
3142   if (isVarArg && MFI->hasVAStart())
3143     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3144                          CCInfo.getNextStackOffset(),
3145                          TotalArgRegsSaveSize);
3146
3147   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3148
3149   return Chain;
3150 }
3151
3152 /// isFloatingPointZero - Return true if this is +0.0.
3153 static bool isFloatingPointZero(SDValue Op) {
3154   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3155     return CFP->getValueAPF().isPosZero();
3156   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3157     // Maybe this has already been legalized into the constant pool?
3158     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3159       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3160       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3161         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3162           return CFP->getValueAPF().isPosZero();
3163     }
3164   } else if (Op->getOpcode() == ISD::BITCAST &&
3165              Op->getValueType(0) == MVT::f64) {
3166     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3167     // created by LowerConstantFP().
3168     SDValue BitcastOp = Op->getOperand(0);
3169     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3170       SDValue MoveOp = BitcastOp->getOperand(0);
3171       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3172           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3173         return true;
3174       }
3175     }
3176   }
3177   return false;
3178 }
3179
3180 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3181 /// the given operands.
3182 SDValue
3183 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3184                              SDValue &ARMcc, SelectionDAG &DAG,
3185                              SDLoc dl) const {
3186   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3187     unsigned C = RHSC->getZExtValue();
3188     if (!isLegalICmpImmediate(C)) {
3189       // Constant does not fit, try adjusting it by one?
3190       switch (CC) {
3191       default: break;
3192       case ISD::SETLT:
3193       case ISD::SETGE:
3194         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3195           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3196           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3197         }
3198         break;
3199       case ISD::SETULT:
3200       case ISD::SETUGE:
3201         if (C != 0 && isLegalICmpImmediate(C-1)) {
3202           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3203           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3204         }
3205         break;
3206       case ISD::SETLE:
3207       case ISD::SETGT:
3208         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3209           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3210           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3211         }
3212         break;
3213       case ISD::SETULE:
3214       case ISD::SETUGT:
3215         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3216           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3217           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3218         }
3219         break;
3220       }
3221     }
3222   }
3223
3224   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3225   ARMISD::NodeType CompareType;
3226   switch (CondCode) {
3227   default:
3228     CompareType = ARMISD::CMP;
3229     break;
3230   case ARMCC::EQ:
3231   case ARMCC::NE:
3232     // Uses only Z Flag
3233     CompareType = ARMISD::CMPZ;
3234     break;
3235   }
3236   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3237   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3238 }
3239
3240 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3241 SDValue
3242 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3243                              SDLoc dl) const {
3244   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3245   SDValue Cmp;
3246   if (!isFloatingPointZero(RHS))
3247     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3248   else
3249     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3250   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3251 }
3252
3253 /// duplicateCmp - Glue values can have only one use, so this function
3254 /// duplicates a comparison node.
3255 SDValue
3256 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3257   unsigned Opc = Cmp.getOpcode();
3258   SDLoc DL(Cmp);
3259   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3260     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3261
3262   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3263   Cmp = Cmp.getOperand(0);
3264   Opc = Cmp.getOpcode();
3265   if (Opc == ARMISD::CMPFP)
3266     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3267   else {
3268     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3269     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3270   }
3271   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3272 }
3273
3274 std::pair<SDValue, SDValue>
3275 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3276                                  SDValue &ARMcc) const {
3277   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3278
3279   SDValue Value, OverflowCmp;
3280   SDValue LHS = Op.getOperand(0);
3281   SDValue RHS = Op.getOperand(1);
3282   SDLoc dl(Op);
3283
3284   // FIXME: We are currently always generating CMPs because we don't support
3285   // generating CMN through the backend. This is not as good as the natural
3286   // CMP case because it causes a register dependency and cannot be folded
3287   // later.
3288
3289   switch (Op.getOpcode()) {
3290   default:
3291     llvm_unreachable("Unknown overflow instruction!");
3292   case ISD::SADDO:
3293     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3294     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3295     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3296     break;
3297   case ISD::UADDO:
3298     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3299     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3300     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3301     break;
3302   case ISD::SSUBO:
3303     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3304     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3305     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3306     break;
3307   case ISD::USUBO:
3308     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3309     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3310     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3311     break;
3312   } // switch (...)
3313
3314   return std::make_pair(Value, OverflowCmp);
3315 }
3316
3317
3318 SDValue
3319 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3320   // Let legalize expand this if it isn't a legal type yet.
3321   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3322     return SDValue();
3323
3324   SDValue Value, OverflowCmp;
3325   SDValue ARMcc;
3326   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3327   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3328   SDLoc dl(Op);
3329   // We use 0 and 1 as false and true values.
3330   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3331   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3332   EVT VT = Op.getValueType();
3333
3334   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3335                                  ARMcc, CCR, OverflowCmp);
3336
3337   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3338   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3339 }
3340
3341
3342 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3343   SDValue Cond = Op.getOperand(0);
3344   SDValue SelectTrue = Op.getOperand(1);
3345   SDValue SelectFalse = Op.getOperand(2);
3346   SDLoc dl(Op);
3347   unsigned Opc = Cond.getOpcode();
3348
3349   if (Cond.getResNo() == 1 &&
3350       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3351        Opc == ISD::USUBO)) {
3352     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3353       return SDValue();
3354
3355     SDValue Value, OverflowCmp;
3356     SDValue ARMcc;
3357     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3358     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3359     EVT VT = Op.getValueType();
3360
3361     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3362                    OverflowCmp, DAG);
3363   }
3364
3365   // Convert:
3366   //
3367   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3368   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3369   //
3370   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3371     const ConstantSDNode *CMOVTrue =
3372       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3373     const ConstantSDNode *CMOVFalse =
3374       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3375
3376     if (CMOVTrue && CMOVFalse) {
3377       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3378       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3379
3380       SDValue True;
3381       SDValue False;
3382       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3383         True = SelectTrue;
3384         False = SelectFalse;
3385       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3386         True = SelectFalse;
3387         False = SelectTrue;
3388       }
3389
3390       if (True.getNode() && False.getNode()) {
3391         EVT VT = Op.getValueType();
3392         SDValue ARMcc = Cond.getOperand(2);
3393         SDValue CCR = Cond.getOperand(3);
3394         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3395         assert(True.getValueType() == VT);
3396         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3397       }
3398     }
3399   }
3400
3401   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3402   // undefined bits before doing a full-word comparison with zero.
3403   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3404                      DAG.getConstant(1, dl, Cond.getValueType()));
3405
3406   return DAG.getSelectCC(dl, Cond,
3407                          DAG.getConstant(0, dl, Cond.getValueType()),
3408                          SelectTrue, SelectFalse, ISD::SETNE);
3409 }
3410
3411 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3412                                  bool &swpCmpOps, bool &swpVselOps) {
3413   // Start by selecting the GE condition code for opcodes that return true for
3414   // 'equality'
3415   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3416       CC == ISD::SETULE)
3417     CondCode = ARMCC::GE;
3418
3419   // and GT for opcodes that return false for 'equality'.
3420   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3421            CC == ISD::SETULT)
3422     CondCode = ARMCC::GT;
3423
3424   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3425   // to swap the compare operands.
3426   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3427       CC == ISD::SETULT)
3428     swpCmpOps = true;
3429
3430   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3431   // If we have an unordered opcode, we need to swap the operands to the VSEL
3432   // instruction (effectively negating the condition).
3433   //
3434   // This also has the effect of swapping which one of 'less' or 'greater'
3435   // returns true, so we also swap the compare operands. It also switches
3436   // whether we return true for 'equality', so we compensate by picking the
3437   // opposite condition code to our original choice.
3438   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3439       CC == ISD::SETUGT) {
3440     swpCmpOps = !swpCmpOps;
3441     swpVselOps = !swpVselOps;
3442     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3443   }
3444
3445   // 'ordered' is 'anything but unordered', so use the VS condition code and
3446   // swap the VSEL operands.
3447   if (CC == ISD::SETO) {
3448     CondCode = ARMCC::VS;
3449     swpVselOps = true;
3450   }
3451
3452   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3453   // code and swap the VSEL operands.
3454   if (CC == ISD::SETUNE) {
3455     CondCode = ARMCC::EQ;
3456     swpVselOps = true;
3457   }
3458 }
3459
3460 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3461                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3462                                    SDValue Cmp, SelectionDAG &DAG) const {
3463   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3464     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3465                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3466     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3467                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3468
3469     SDValue TrueLow = TrueVal.getValue(0);
3470     SDValue TrueHigh = TrueVal.getValue(1);
3471     SDValue FalseLow = FalseVal.getValue(0);
3472     SDValue FalseHigh = FalseVal.getValue(1);
3473
3474     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3475                               ARMcc, CCR, Cmp);
3476     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3477                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3478
3479     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3480   } else {
3481     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3482                        Cmp);
3483   }
3484 }
3485
3486 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3487   EVT VT = Op.getValueType();
3488   SDValue LHS = Op.getOperand(0);
3489   SDValue RHS = Op.getOperand(1);
3490   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3491   SDValue TrueVal = Op.getOperand(2);
3492   SDValue FalseVal = Op.getOperand(3);
3493   SDLoc dl(Op);
3494
3495   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3496     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3497                                                     dl);
3498
3499     // If softenSetCCOperands only returned one value, we should compare it to
3500     // zero.
3501     if (!RHS.getNode()) {
3502       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3503       CC = ISD::SETNE;
3504     }
3505   }
3506
3507   if (LHS.getValueType() == MVT::i32) {
3508     // Try to generate VSEL on ARMv8.
3509     // The VSEL instruction can't use all the usual ARM condition
3510     // codes: it only has two bits to select the condition code, so it's
3511     // constrained to use only GE, GT, VS and EQ.
3512     //
3513     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3514     // swap the operands of the previous compare instruction (effectively
3515     // inverting the compare condition, swapping 'less' and 'greater') and
3516     // sometimes need to swap the operands to the VSEL (which inverts the
3517     // condition in the sense of firing whenever the previous condition didn't)
3518     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3519                                     TrueVal.getValueType() == MVT::f64)) {
3520       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3521       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3522           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3523         CC = ISD::getSetCCInverse(CC, true);
3524         std::swap(TrueVal, FalseVal);
3525       }
3526     }
3527
3528     SDValue ARMcc;
3529     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3530     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3531     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3532   }
3533
3534   ARMCC::CondCodes CondCode, CondCode2;
3535   FPCCToARMCC(CC, CondCode, CondCode2);
3536
3537   // Try to generate VMAXNM/VMINNM on ARMv8.
3538   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3539                                   TrueVal.getValueType() == MVT::f64)) {
3540     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3541     // same operands, as follows:
3542     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3543     //   select c, a, b
3544     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3545     bool swapSides = false;
3546     if (!getTargetMachine().Options.NoNaNsFPMath) {
3547       // transformability may depend on which way around we compare
3548       switch (CC) {
3549       default:
3550         break;
3551       case ISD::SETOGT:
3552       case ISD::SETOGE:
3553       case ISD::SETOLT:
3554       case ISD::SETOLE:
3555         // the non-NaN should be RHS
3556         swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3557         break;
3558       case ISD::SETUGT:
3559       case ISD::SETUGE:
3560       case ISD::SETULT:
3561       case ISD::SETULE:
3562         // the non-NaN should be LHS
3563         swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3564         break;
3565       }
3566     }
3567     swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3568     if (swapSides) {
3569       CC = ISD::getSetCCSwappedOperands(CC);
3570       std::swap(LHS, RHS);
3571     }
3572     if (LHS == TrueVal && RHS == FalseVal) {
3573       bool canTransform = true;
3574       // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3575       if (!getTargetMachine().Options.UnsafeFPMath &&
3576           !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3577         const ConstantFPSDNode *Zero;
3578         switch (CC) {
3579         default:
3580           break;
3581         case ISD::SETOGT:
3582         case ISD::SETUGT:
3583         case ISD::SETGT:
3584           // RHS must not be -0
3585           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3586                          !Zero->isNegative();
3587           break;
3588         case ISD::SETOGE:
3589         case ISD::SETUGE:
3590         case ISD::SETGE:
3591           // LHS must not be -0
3592           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3593                          !Zero->isNegative();
3594           break;
3595         case ISD::SETOLT:
3596         case ISD::SETULT:
3597         case ISD::SETLT:
3598           // RHS must not be +0
3599           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3600                           Zero->isNegative();
3601           break;
3602         case ISD::SETOLE:
3603         case ISD::SETULE:
3604         case ISD::SETLE:
3605           // LHS must not be +0
3606           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3607                           Zero->isNegative();
3608           break;
3609         }
3610       }
3611       if (canTransform) {
3612         // Note: If one of the elements in a pair is a number and the other
3613         // element is NaN, the corresponding result element is the number.
3614         // This is consistent with the IEEE 754-2008 standard.
3615         // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3616         switch (CC) {
3617         default:
3618           break;
3619         case ISD::SETOGT:
3620         case ISD::SETOGE:
3621           if (!DAG.isKnownNeverNaN(RHS))
3622             break;
3623           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3624         case ISD::SETUGT:
3625         case ISD::SETUGE:
3626           if (!DAG.isKnownNeverNaN(LHS))
3627             break;
3628         case ISD::SETGT:
3629         case ISD::SETGE:
3630           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3631         case ISD::SETOLT:
3632         case ISD::SETOLE:
3633           if (!DAG.isKnownNeverNaN(RHS))
3634             break;
3635           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3636         case ISD::SETULT:
3637         case ISD::SETULE:
3638           if (!DAG.isKnownNeverNaN(LHS))
3639             break;
3640         case ISD::SETLT:
3641         case ISD::SETLE:
3642           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3643         }
3644       }
3645     }
3646
3647     bool swpCmpOps = false;
3648     bool swpVselOps = false;
3649     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3650
3651     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3652         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3653       if (swpCmpOps)
3654         std::swap(LHS, RHS);
3655       if (swpVselOps)
3656         std::swap(TrueVal, FalseVal);
3657     }
3658   }
3659
3660   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3661   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3662   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3663   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3664   if (CondCode2 != ARMCC::AL) {
3665     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3666     // FIXME: Needs another CMP because flag can have but one use.
3667     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3668     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3669   }
3670   return Result;
3671 }
3672
3673 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3674 /// to morph to an integer compare sequence.
3675 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3676                            const ARMSubtarget *Subtarget) {
3677   SDNode *N = Op.getNode();
3678   if (!N->hasOneUse())
3679     // Otherwise it requires moving the value from fp to integer registers.
3680     return false;
3681   if (!N->getNumValues())
3682     return false;
3683   EVT VT = Op.getValueType();
3684   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3685     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3686     // vmrs are very slow, e.g. cortex-a8.
3687     return false;
3688
3689   if (isFloatingPointZero(Op)) {
3690     SeenZero = true;
3691     return true;
3692   }
3693   return ISD::isNormalLoad(N);
3694 }
3695
3696 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3697   if (isFloatingPointZero(Op))
3698     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3699
3700   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3701     return DAG.getLoad(MVT::i32, SDLoc(Op),
3702                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3703                        Ld->isVolatile(), Ld->isNonTemporal(),
3704                        Ld->isInvariant(), Ld->getAlignment());
3705
3706   llvm_unreachable("Unknown VFP cmp argument!");
3707 }
3708
3709 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3710                            SDValue &RetVal1, SDValue &RetVal2) {
3711   SDLoc dl(Op);
3712
3713   if (isFloatingPointZero(Op)) {
3714     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3715     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3716     return;
3717   }
3718
3719   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3720     SDValue Ptr = Ld->getBasePtr();
3721     RetVal1 = DAG.getLoad(MVT::i32, dl,
3722                           Ld->getChain(), Ptr,
3723                           Ld->getPointerInfo(),
3724                           Ld->isVolatile(), Ld->isNonTemporal(),
3725                           Ld->isInvariant(), Ld->getAlignment());
3726
3727     EVT PtrType = Ptr.getValueType();
3728     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3729     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3730                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3731     RetVal2 = DAG.getLoad(MVT::i32, dl,
3732                           Ld->getChain(), NewPtr,
3733                           Ld->getPointerInfo().getWithOffset(4),
3734                           Ld->isVolatile(), Ld->isNonTemporal(),
3735                           Ld->isInvariant(), NewAlign);
3736     return;
3737   }
3738
3739   llvm_unreachable("Unknown VFP cmp argument!");
3740 }
3741
3742 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3743 /// f32 and even f64 comparisons to integer ones.
3744 SDValue
3745 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3746   SDValue Chain = Op.getOperand(0);
3747   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3748   SDValue LHS = Op.getOperand(2);
3749   SDValue RHS = Op.getOperand(3);
3750   SDValue Dest = Op.getOperand(4);
3751   SDLoc dl(Op);
3752
3753   bool LHSSeenZero = false;
3754   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3755   bool RHSSeenZero = false;
3756   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3757   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3758     // If unsafe fp math optimization is enabled and there are no other uses of
3759     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3760     // to an integer comparison.
3761     if (CC == ISD::SETOEQ)
3762       CC = ISD::SETEQ;
3763     else if (CC == ISD::SETUNE)
3764       CC = ISD::SETNE;
3765
3766     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3767     SDValue ARMcc;
3768     if (LHS.getValueType() == MVT::f32) {
3769       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3770                         bitcastf32Toi32(LHS, DAG), Mask);
3771       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3772                         bitcastf32Toi32(RHS, DAG), Mask);
3773       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3774       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3775       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3776                          Chain, Dest, ARMcc, CCR, Cmp);
3777     }
3778
3779     SDValue LHS1, LHS2;
3780     SDValue RHS1, RHS2;
3781     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3782     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3783     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3784     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3785     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3786     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3787     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3788     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3789     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3790   }
3791
3792   return SDValue();
3793 }
3794
3795 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3796   SDValue Chain = Op.getOperand(0);
3797   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3798   SDValue LHS = Op.getOperand(2);
3799   SDValue RHS = Op.getOperand(3);
3800   SDValue Dest = Op.getOperand(4);
3801   SDLoc dl(Op);
3802
3803   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3804     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3805                                                     dl);
3806
3807     // If softenSetCCOperands only returned one value, we should compare it to
3808     // zero.
3809     if (!RHS.getNode()) {
3810       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3811       CC = ISD::SETNE;
3812     }
3813   }
3814
3815   if (LHS.getValueType() == MVT::i32) {
3816     SDValue ARMcc;
3817     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3818     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3819     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3820                        Chain, Dest, ARMcc, CCR, Cmp);
3821   }
3822
3823   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3824
3825   if (getTargetMachine().Options.UnsafeFPMath &&
3826       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3827        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3828     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3829     if (Result.getNode())
3830       return Result;
3831   }
3832
3833   ARMCC::CondCodes CondCode, CondCode2;
3834   FPCCToARMCC(CC, CondCode, CondCode2);
3835
3836   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3837   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3838   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3839   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3840   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3841   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3842   if (CondCode2 != ARMCC::AL) {
3843     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3844     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3845     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3846   }
3847   return Res;
3848 }
3849
3850 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3851   SDValue Chain = Op.getOperand(0);
3852   SDValue Table = Op.getOperand(1);
3853   SDValue Index = Op.getOperand(2);
3854   SDLoc dl(Op);
3855
3856   EVT PTy = getPointerTy();
3857   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3858   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3859   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3860   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3861   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3862   if (Subtarget->isThumb2()) {
3863     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3864     // which does another jump to the destination. This also makes it easier
3865     // to translate it to TBB / TBH later.
3866     // FIXME: This might not work if the function is extremely large.
3867     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3868                        Addr, Op.getOperand(2), JTI);
3869   }
3870   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3871     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3872                        MachinePointerInfo::getJumpTable(),
3873                        false, false, false, 0);
3874     Chain = Addr.getValue(1);
3875     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3876     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3877   } else {
3878     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3879                        MachinePointerInfo::getJumpTable(),
3880                        false, false, false, 0);
3881     Chain = Addr.getValue(1);
3882     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3883   }
3884 }
3885
3886 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3887   EVT VT = Op.getValueType();
3888   SDLoc dl(Op);
3889
3890   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3891     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3892       return Op;
3893     return DAG.UnrollVectorOp(Op.getNode());
3894   }
3895
3896   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3897          "Invalid type for custom lowering!");
3898   if (VT != MVT::v4i16)
3899     return DAG.UnrollVectorOp(Op.getNode());
3900
3901   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3902   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3903 }
3904
3905 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3906   EVT VT = Op.getValueType();
3907   if (VT.isVector())
3908     return LowerVectorFP_TO_INT(Op, DAG);
3909   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3910     RTLIB::Libcall LC;
3911     if (Op.getOpcode() == ISD::FP_TO_SINT)
3912       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3913                               Op.getValueType());
3914     else
3915       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3916                               Op.getValueType());
3917     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3918                        /*isSigned*/ false, SDLoc(Op)).first;
3919   }
3920
3921   return Op;
3922 }
3923
3924 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3925   EVT VT = Op.getValueType();
3926   SDLoc dl(Op);
3927
3928   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3929     if (VT.getVectorElementType() == MVT::f32)
3930       return Op;
3931     return DAG.UnrollVectorOp(Op.getNode());
3932   }
3933
3934   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3935          "Invalid type for custom lowering!");
3936   if (VT != MVT::v4f32)
3937     return DAG.UnrollVectorOp(Op.getNode());
3938
3939   unsigned CastOpc;
3940   unsigned Opc;
3941   switch (Op.getOpcode()) {
3942   default: llvm_unreachable("Invalid opcode!");
3943   case ISD::SINT_TO_FP:
3944     CastOpc = ISD::SIGN_EXTEND;
3945     Opc = ISD::SINT_TO_FP;
3946     break;
3947   case ISD::UINT_TO_FP:
3948     CastOpc = ISD::ZERO_EXTEND;
3949     Opc = ISD::UINT_TO_FP;
3950     break;
3951   }
3952
3953   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3954   return DAG.getNode(Opc, dl, VT, Op);
3955 }
3956
3957 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3958   EVT VT = Op.getValueType();
3959   if (VT.isVector())
3960     return LowerVectorINT_TO_FP(Op, DAG);
3961   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3962     RTLIB::Libcall LC;
3963     if (Op.getOpcode() == ISD::SINT_TO_FP)
3964       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3965                               Op.getValueType());
3966     else
3967       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3968                               Op.getValueType());
3969     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3970                        /*isSigned*/ false, SDLoc(Op)).first;
3971   }
3972
3973   return Op;
3974 }
3975
3976 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3977   // Implement fcopysign with a fabs and a conditional fneg.
3978   SDValue Tmp0 = Op.getOperand(0);
3979   SDValue Tmp1 = Op.getOperand(1);
3980   SDLoc dl(Op);
3981   EVT VT = Op.getValueType();
3982   EVT SrcVT = Tmp1.getValueType();
3983   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3984     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3985   bool UseNEON = !InGPR && Subtarget->hasNEON();
3986
3987   if (UseNEON) {
3988     // Use VBSL to copy the sign bit.
3989     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3990     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3991                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3992     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3993     if (VT == MVT::f64)
3994       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3995                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3996                          DAG.getConstant(32, dl, MVT::i32));
3997     else /*if (VT == MVT::f32)*/
3998       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3999     if (SrcVT == MVT::f32) {
4000       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4001       if (VT == MVT::f64)
4002         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4003                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4004                            DAG.getConstant(32, dl, MVT::i32));
4005     } else if (VT == MVT::f32)
4006       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4007                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4008                          DAG.getConstant(32, dl, MVT::i32));
4009     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4010     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4011
4012     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4013                                             dl, MVT::i32);
4014     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4015     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4016                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4017
4018     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4019                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4020                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4021     if (VT == MVT::f32) {
4022       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4023       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4024                         DAG.getConstant(0, dl, MVT::i32));
4025     } else {
4026       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4027     }
4028
4029     return Res;
4030   }
4031
4032   // Bitcast operand 1 to i32.
4033   if (SrcVT == MVT::f64)
4034     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4035                        Tmp1).getValue(1);
4036   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4037
4038   // Or in the signbit with integer operations.
4039   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4040   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4041   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4042   if (VT == MVT::f32) {
4043     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4044                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4045     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4046                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4047   }
4048
4049   // f64: Or the high part with signbit and then combine two parts.
4050   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4051                      Tmp0);
4052   SDValue Lo = Tmp0.getValue(0);
4053   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4054   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4055   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4056 }
4057
4058 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4059   MachineFunction &MF = DAG.getMachineFunction();
4060   MachineFrameInfo *MFI = MF.getFrameInfo();
4061   MFI->setReturnAddressIsTaken(true);
4062
4063   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4064     return SDValue();
4065
4066   EVT VT = Op.getValueType();
4067   SDLoc dl(Op);
4068   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4069   if (Depth) {
4070     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4071     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4072     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4073                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4074                        MachinePointerInfo(), false, false, false, 0);
4075   }
4076
4077   // Return LR, which contains the return address. Mark it an implicit live-in.
4078   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4079   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4080 }
4081
4082 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4083   const ARMBaseRegisterInfo &ARI =
4084     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4085   MachineFunction &MF = DAG.getMachineFunction();
4086   MachineFrameInfo *MFI = MF.getFrameInfo();
4087   MFI->setFrameAddressIsTaken(true);
4088
4089   EVT VT = Op.getValueType();
4090   SDLoc dl(Op);  // FIXME probably not meaningful
4091   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4092   unsigned FrameReg = ARI.getFrameRegister(MF);
4093   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4094   while (Depth--)
4095     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4096                             MachinePointerInfo(),
4097                             false, false, false, 0);
4098   return FrameAddr;
4099 }
4100
4101 // FIXME? Maybe this could be a TableGen attribute on some registers and
4102 // this table could be generated automatically from RegInfo.
4103 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4104                                               EVT VT) const {
4105   unsigned Reg = StringSwitch<unsigned>(RegName)
4106                        .Case("sp", ARM::SP)
4107                        .Default(0);
4108   if (Reg)
4109     return Reg;
4110   report_fatal_error(Twine("Invalid register name \""
4111                               + StringRef(RegName)  + "\"."));
4112 }
4113
4114 // Result is 64 bit value so split into two 32 bit values and return as a
4115 // pair of values.
4116 static SDValue ExpandREAD_REGISTER(SDNode *N, SelectionDAG &DAG) {
4117   SDLoc DL(N);
4118   SDValue Op = N->getOperand(0);
4119
4120   // This function is only supposed to be called for i64 type destination.
4121   assert(N->getValueType(0) == MVT::i64
4122           && "ExpandREAD_REGISTER called for non-i64 type result.");
4123
4124   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4125                              DAG.getVTList(MVT::i32, MVT::i32), Op);
4126   return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4127                      Read.getValue(1));
4128 }
4129
4130
4131 /// ExpandBITCAST - If the target supports VFP, this function is called to
4132 /// expand a bit convert where either the source or destination type is i64 to
4133 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4134 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4135 /// vectors), since the legalizer won't know what to do with that.
4136 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4137   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4138   SDLoc dl(N);
4139   SDValue Op = N->getOperand(0);
4140
4141   // This function is only supposed to be called for i64 types, either as the
4142   // source or destination of the bit convert.
4143   EVT SrcVT = Op.getValueType();
4144   EVT DstVT = N->getValueType(0);
4145   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4146          "ExpandBITCAST called for non-i64 type");
4147
4148   // Turn i64->f64 into VMOVDRR.
4149   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4150     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4151                              DAG.getConstant(0, dl, MVT::i32));
4152     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4153                              DAG.getConstant(1, dl, MVT::i32));
4154     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4155                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4156   }
4157
4158   // Turn f64->i64 into VMOVRRD.
4159   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4160     SDValue Cvt;
4161     if (TLI.isBigEndian() && SrcVT.isVector() &&
4162         SrcVT.getVectorNumElements() > 1)
4163       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4164                         DAG.getVTList(MVT::i32, MVT::i32),
4165                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4166     else
4167       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4168                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4169     // Merge the pieces into a single i64 value.
4170     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4171   }
4172
4173   return SDValue();
4174 }
4175
4176 /// getZeroVector - Returns a vector of specified type with all zero elements.
4177 /// Zero vectors are used to represent vector negation and in those cases
4178 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4179 /// not support i64 elements, so sometimes the zero vectors will need to be
4180 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4181 /// zero vector.
4182 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4183   assert(VT.isVector() && "Expected a vector type");
4184   // The canonical modified immediate encoding of a zero vector is....0!
4185   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4186   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4187   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4188   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4189 }
4190
4191 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4192 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4193 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4194                                                 SelectionDAG &DAG) const {
4195   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4196   EVT VT = Op.getValueType();
4197   unsigned VTBits = VT.getSizeInBits();
4198   SDLoc dl(Op);
4199   SDValue ShOpLo = Op.getOperand(0);
4200   SDValue ShOpHi = Op.getOperand(1);
4201   SDValue ShAmt  = Op.getOperand(2);
4202   SDValue ARMcc;
4203   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4204
4205   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4206
4207   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4208                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4209   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4210   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4211                                    DAG.getConstant(VTBits, dl, MVT::i32));
4212   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4213   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4214   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4215
4216   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4217   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4218                           ISD::SETGE, ARMcc, DAG, dl);
4219   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4220   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4221                            CCR, Cmp);
4222
4223   SDValue Ops[2] = { Lo, Hi };
4224   return DAG.getMergeValues(Ops, dl);
4225 }
4226
4227 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4228 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4229 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4230                                                SelectionDAG &DAG) const {
4231   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4232   EVT VT = Op.getValueType();
4233   unsigned VTBits = VT.getSizeInBits();
4234   SDLoc dl(Op);
4235   SDValue ShOpLo = Op.getOperand(0);
4236   SDValue ShOpHi = Op.getOperand(1);
4237   SDValue ShAmt  = Op.getOperand(2);
4238   SDValue ARMcc;
4239
4240   assert(Op.getOpcode() == ISD::SHL_PARTS);
4241   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4242                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4243   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4244   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4245                                    DAG.getConstant(VTBits, dl, MVT::i32));
4246   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4247   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4248
4249   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4250   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4251   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4252                           ISD::SETGE, ARMcc, DAG, dl);
4253   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4254   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4255                            CCR, Cmp);
4256
4257   SDValue Ops[2] = { Lo, Hi };
4258   return DAG.getMergeValues(Ops, dl);
4259 }
4260
4261 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4262                                             SelectionDAG &DAG) const {
4263   // The rounding mode is in bits 23:22 of the FPSCR.
4264   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4265   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4266   // so that the shift + and get folded into a bitfield extract.
4267   SDLoc dl(Op);
4268   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4269                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4270                                               MVT::i32));
4271   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4272                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4273   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4274                               DAG.getConstant(22, dl, MVT::i32));
4275   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4276                      DAG.getConstant(3, dl, MVT::i32));
4277 }
4278
4279 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4280                          const ARMSubtarget *ST) {
4281   EVT VT = N->getValueType(0);
4282   SDLoc dl(N);
4283
4284   if (!ST->hasV6T2Ops())
4285     return SDValue();
4286
4287   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4288   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4289 }
4290
4291 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4292 /// for each 16-bit element from operand, repeated.  The basic idea is to
4293 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4294 ///
4295 /// Trace for v4i16:
4296 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4297 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4298 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4299 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4300 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4301 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4302 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4303 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4304 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4305   EVT VT = N->getValueType(0);
4306   SDLoc DL(N);
4307
4308   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4309   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4310   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4311   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4312   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4313   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4314 }
4315
4316 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4317 /// bit-count for each 16-bit element from the operand.  We need slightly
4318 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4319 /// 64/128-bit registers.
4320 ///
4321 /// Trace for v4i16:
4322 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4323 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4324 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4325 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4326 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4327   EVT VT = N->getValueType(0);
4328   SDLoc DL(N);
4329
4330   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4331   if (VT.is64BitVector()) {
4332     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4333     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4334                        DAG.getIntPtrConstant(0, DL));
4335   } else {
4336     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4337                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4338     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4339   }
4340 }
4341
4342 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4343 /// bit-count for each 32-bit element from the operand.  The idea here is
4344 /// to split the vector into 16-bit elements, leverage the 16-bit count
4345 /// routine, and then combine the results.
4346 ///
4347 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4348 /// input    = [v0    v1    ] (vi: 32-bit elements)
4349 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4350 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4351 /// vrev: N0 = [k1 k0 k3 k2 ]
4352 ///            [k0 k1 k2 k3 ]
4353 ///       N1 =+[k1 k0 k3 k2 ]
4354 ///            [k0 k2 k1 k3 ]
4355 ///       N2 =+[k1 k3 k0 k2 ]
4356 ///            [k0    k2    k1    k3    ]
4357 /// Extended =+[k1    k3    k0    k2    ]
4358 ///            [k0    k2    ]
4359 /// Extracted=+[k1    k3    ]
4360 ///
4361 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4362   EVT VT = N->getValueType(0);
4363   SDLoc DL(N);
4364
4365   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4366
4367   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4368   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4369   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4370   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4371   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4372
4373   if (VT.is64BitVector()) {
4374     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4375     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4376                        DAG.getIntPtrConstant(0, DL));
4377   } else {
4378     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4379                                     DAG.getIntPtrConstant(0, DL));
4380     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4381   }
4382 }
4383
4384 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4385                           const ARMSubtarget *ST) {
4386   EVT VT = N->getValueType(0);
4387
4388   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4389   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4390           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4391          "Unexpected type for custom ctpop lowering");
4392
4393   if (VT.getVectorElementType() == MVT::i32)
4394     return lowerCTPOP32BitElements(N, DAG);
4395   else
4396     return lowerCTPOP16BitElements(N, DAG);
4397 }
4398
4399 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4400                           const ARMSubtarget *ST) {
4401   EVT VT = N->getValueType(0);
4402   SDLoc dl(N);
4403
4404   if (!VT.isVector())
4405     return SDValue();
4406
4407   // Lower vector shifts on NEON to use VSHL.
4408   assert(ST->hasNEON() && "unexpected vector shift");
4409
4410   // Left shifts translate directly to the vshiftu intrinsic.
4411   if (N->getOpcode() == ISD::SHL)
4412     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4413                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4414                                        MVT::i32),
4415                        N->getOperand(0), N->getOperand(1));
4416
4417   assert((N->getOpcode() == ISD::SRA ||
4418           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4419
4420   // NEON uses the same intrinsics for both left and right shifts.  For
4421   // right shifts, the shift amounts are negative, so negate the vector of
4422   // shift amounts.
4423   EVT ShiftVT = N->getOperand(1).getValueType();
4424   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4425                                      getZeroVector(ShiftVT, DAG, dl),
4426                                      N->getOperand(1));
4427   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4428                              Intrinsic::arm_neon_vshifts :
4429                              Intrinsic::arm_neon_vshiftu);
4430   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4431                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4432                      N->getOperand(0), NegatedCount);
4433 }
4434
4435 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4436                                 const ARMSubtarget *ST) {
4437   EVT VT = N->getValueType(0);
4438   SDLoc dl(N);
4439
4440   // We can get here for a node like i32 = ISD::SHL i32, i64
4441   if (VT != MVT::i64)
4442     return SDValue();
4443
4444   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4445          "Unknown shift to lower!");
4446
4447   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4448   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4449       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4450     return SDValue();
4451
4452   // If we are in thumb mode, we don't have RRX.
4453   if (ST->isThumb1Only()) return SDValue();
4454
4455   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4456   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4457                            DAG.getConstant(0, dl, MVT::i32));
4458   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4459                            DAG.getConstant(1, dl, MVT::i32));
4460
4461   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4462   // captures the result into a carry flag.
4463   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4464   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4465
4466   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4467   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4468
4469   // Merge the pieces into a single i64 value.
4470  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4471 }
4472
4473 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4474   SDValue TmpOp0, TmpOp1;
4475   bool Invert = false;
4476   bool Swap = false;
4477   unsigned Opc = 0;
4478
4479   SDValue Op0 = Op.getOperand(0);
4480   SDValue Op1 = Op.getOperand(1);
4481   SDValue CC = Op.getOperand(2);
4482   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4483   EVT VT = Op.getValueType();
4484   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4485   SDLoc dl(Op);
4486
4487   if (Op1.getValueType().isFloatingPoint()) {
4488     switch (SetCCOpcode) {
4489     default: llvm_unreachable("Illegal FP comparison");
4490     case ISD::SETUNE:
4491     case ISD::SETNE:  Invert = true; // Fallthrough
4492     case ISD::SETOEQ:
4493     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4494     case ISD::SETOLT:
4495     case ISD::SETLT: Swap = true; // Fallthrough
4496     case ISD::SETOGT:
4497     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4498     case ISD::SETOLE:
4499     case ISD::SETLE:  Swap = true; // Fallthrough
4500     case ISD::SETOGE:
4501     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4502     case ISD::SETUGE: Swap = true; // Fallthrough
4503     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4504     case ISD::SETUGT: Swap = true; // Fallthrough
4505     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4506     case ISD::SETUEQ: Invert = true; // Fallthrough
4507     case ISD::SETONE:
4508       // Expand this to (OLT | OGT).
4509       TmpOp0 = Op0;
4510       TmpOp1 = Op1;
4511       Opc = ISD::OR;
4512       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4513       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4514       break;
4515     case ISD::SETUO: Invert = true; // Fallthrough
4516     case ISD::SETO:
4517       // Expand this to (OLT | OGE).
4518       TmpOp0 = Op0;
4519       TmpOp1 = Op1;
4520       Opc = ISD::OR;
4521       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4522       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4523       break;
4524     }
4525   } else {
4526     // Integer comparisons.
4527     switch (SetCCOpcode) {
4528     default: llvm_unreachable("Illegal integer comparison");
4529     case ISD::SETNE:  Invert = true;
4530     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4531     case ISD::SETLT:  Swap = true;
4532     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4533     case ISD::SETLE:  Swap = true;
4534     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4535     case ISD::SETULT: Swap = true;
4536     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4537     case ISD::SETULE: Swap = true;
4538     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4539     }
4540
4541     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4542     if (Opc == ARMISD::VCEQ) {
4543
4544       SDValue AndOp;
4545       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4546         AndOp = Op0;
4547       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4548         AndOp = Op1;
4549
4550       // Ignore bitconvert.
4551       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4552         AndOp = AndOp.getOperand(0);
4553
4554       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4555         Opc = ARMISD::VTST;
4556         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4557         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4558         Invert = !Invert;
4559       }
4560     }
4561   }
4562
4563   if (Swap)
4564     std::swap(Op0, Op1);
4565
4566   // If one of the operands is a constant vector zero, attempt to fold the
4567   // comparison to a specialized compare-against-zero form.
4568   SDValue SingleOp;
4569   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4570     SingleOp = Op0;
4571   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4572     if (Opc == ARMISD::VCGE)
4573       Opc = ARMISD::VCLEZ;
4574     else if (Opc == ARMISD::VCGT)
4575       Opc = ARMISD::VCLTZ;
4576     SingleOp = Op1;
4577   }
4578
4579   SDValue Result;
4580   if (SingleOp.getNode()) {
4581     switch (Opc) {
4582     case ARMISD::VCEQ:
4583       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4584     case ARMISD::VCGE:
4585       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4586     case ARMISD::VCLEZ:
4587       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4588     case ARMISD::VCGT:
4589       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4590     case ARMISD::VCLTZ:
4591       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4592     default:
4593       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4594     }
4595   } else {
4596      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4597   }
4598
4599   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4600
4601   if (Invert)
4602     Result = DAG.getNOT(dl, Result, VT);
4603
4604   return Result;
4605 }
4606
4607 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4608 /// valid vector constant for a NEON instruction with a "modified immediate"
4609 /// operand (e.g., VMOV).  If so, return the encoded value.
4610 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4611                                  unsigned SplatBitSize, SelectionDAG &DAG,
4612                                  SDLoc dl, EVT &VT, bool is128Bits,
4613                                  NEONModImmType type) {
4614   unsigned OpCmode, Imm;
4615
4616   // SplatBitSize is set to the smallest size that splats the vector, so a
4617   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4618   // immediate instructions others than VMOV do not support the 8-bit encoding
4619   // of a zero vector, and the default encoding of zero is supposed to be the
4620   // 32-bit version.
4621   if (SplatBits == 0)
4622     SplatBitSize = 32;
4623
4624   switch (SplatBitSize) {
4625   case 8:
4626     if (type != VMOVModImm)
4627       return SDValue();
4628     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4629     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4630     OpCmode = 0xe;
4631     Imm = SplatBits;
4632     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4633     break;
4634
4635   case 16:
4636     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4637     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4638     if ((SplatBits & ~0xff) == 0) {
4639       // Value = 0x00nn: Op=x, Cmode=100x.
4640       OpCmode = 0x8;
4641       Imm = SplatBits;
4642       break;
4643     }
4644     if ((SplatBits & ~0xff00) == 0) {
4645       // Value = 0xnn00: Op=x, Cmode=101x.
4646       OpCmode = 0xa;
4647       Imm = SplatBits >> 8;
4648       break;
4649     }
4650     return SDValue();
4651
4652   case 32:
4653     // NEON's 32-bit VMOV supports splat values where:
4654     // * only one byte is nonzero, or
4655     // * the least significant byte is 0xff and the second byte is nonzero, or
4656     // * the least significant 2 bytes are 0xff and the third is nonzero.
4657     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4658     if ((SplatBits & ~0xff) == 0) {
4659       // Value = 0x000000nn: Op=x, Cmode=000x.
4660       OpCmode = 0;
4661       Imm = SplatBits;
4662       break;
4663     }
4664     if ((SplatBits & ~0xff00) == 0) {
4665       // Value = 0x0000nn00: Op=x, Cmode=001x.
4666       OpCmode = 0x2;
4667       Imm = SplatBits >> 8;
4668       break;
4669     }
4670     if ((SplatBits & ~0xff0000) == 0) {
4671       // Value = 0x00nn0000: Op=x, Cmode=010x.
4672       OpCmode = 0x4;
4673       Imm = SplatBits >> 16;
4674       break;
4675     }
4676     if ((SplatBits & ~0xff000000) == 0) {
4677       // Value = 0xnn000000: Op=x, Cmode=011x.
4678       OpCmode = 0x6;
4679       Imm = SplatBits >> 24;
4680       break;
4681     }
4682
4683     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4684     if (type == OtherModImm) return SDValue();
4685
4686     if ((SplatBits & ~0xffff) == 0 &&
4687         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4688       // Value = 0x0000nnff: Op=x, Cmode=1100.
4689       OpCmode = 0xc;
4690       Imm = SplatBits >> 8;
4691       break;
4692     }
4693
4694     if ((SplatBits & ~0xffffff) == 0 &&
4695         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4696       // Value = 0x00nnffff: Op=x, Cmode=1101.
4697       OpCmode = 0xd;
4698       Imm = SplatBits >> 16;
4699       break;
4700     }
4701
4702     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4703     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4704     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4705     // and fall through here to test for a valid 64-bit splat.  But, then the
4706     // caller would also need to check and handle the change in size.
4707     return SDValue();
4708
4709   case 64: {
4710     if (type != VMOVModImm)
4711       return SDValue();
4712     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4713     uint64_t BitMask = 0xff;
4714     uint64_t Val = 0;
4715     unsigned ImmMask = 1;
4716     Imm = 0;
4717     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4718       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4719         Val |= BitMask;
4720         Imm |= ImmMask;
4721       } else if ((SplatBits & BitMask) != 0) {
4722         return SDValue();
4723       }
4724       BitMask <<= 8;
4725       ImmMask <<= 1;
4726     }
4727
4728     if (DAG.getTargetLoweringInfo().isBigEndian())
4729       // swap higher and lower 32 bit word
4730       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4731
4732     // Op=1, Cmode=1110.
4733     OpCmode = 0x1e;
4734     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4735     break;
4736   }
4737
4738   default:
4739     llvm_unreachable("unexpected size for isNEONModifiedImm");
4740   }
4741
4742   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4743   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4744 }
4745
4746 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4747                                            const ARMSubtarget *ST) const {
4748   if (!ST->hasVFP3())
4749     return SDValue();
4750
4751   bool IsDouble = Op.getValueType() == MVT::f64;
4752   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4753
4754   // Use the default (constant pool) lowering for double constants when we have
4755   // an SP-only FPU
4756   if (IsDouble && Subtarget->isFPOnlySP())
4757     return SDValue();
4758
4759   // Try splatting with a VMOV.f32...
4760   APFloat FPVal = CFP->getValueAPF();
4761   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4762
4763   if (ImmVal != -1) {
4764     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4765       // We have code in place to select a valid ConstantFP already, no need to
4766       // do any mangling.
4767       return Op;
4768     }
4769
4770     // It's a float and we are trying to use NEON operations where
4771     // possible. Lower it to a splat followed by an extract.
4772     SDLoc DL(Op);
4773     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4774     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4775                                       NewVal);
4776     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4777                        DAG.getConstant(0, DL, MVT::i32));
4778   }
4779
4780   // The rest of our options are NEON only, make sure that's allowed before
4781   // proceeding..
4782   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4783     return SDValue();
4784
4785   EVT VMovVT;
4786   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4787
4788   // It wouldn't really be worth bothering for doubles except for one very
4789   // important value, which does happen to match: 0.0. So make sure we don't do
4790   // anything stupid.
4791   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4792     return SDValue();
4793
4794   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4795   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4796                                      VMovVT, false, VMOVModImm);
4797   if (NewVal != SDValue()) {
4798     SDLoc DL(Op);
4799     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4800                                       NewVal);
4801     if (IsDouble)
4802       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4803
4804     // It's a float: cast and extract a vector element.
4805     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4806                                        VecConstant);
4807     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4808                        DAG.getConstant(0, DL, MVT::i32));
4809   }
4810
4811   // Finally, try a VMVN.i32
4812   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4813                              false, VMVNModImm);
4814   if (NewVal != SDValue()) {
4815     SDLoc DL(Op);
4816     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4817
4818     if (IsDouble)
4819       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4820
4821     // It's a float: cast and extract a vector element.
4822     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4823                                        VecConstant);
4824     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4825                        DAG.getConstant(0, DL, MVT::i32));
4826   }
4827
4828   return SDValue();
4829 }
4830
4831 // check if an VEXT instruction can handle the shuffle mask when the
4832 // vector sources of the shuffle are the same.
4833 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4834   unsigned NumElts = VT.getVectorNumElements();
4835
4836   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4837   if (M[0] < 0)
4838     return false;
4839
4840   Imm = M[0];
4841
4842   // If this is a VEXT shuffle, the immediate value is the index of the first
4843   // element.  The other shuffle indices must be the successive elements after
4844   // the first one.
4845   unsigned ExpectedElt = Imm;
4846   for (unsigned i = 1; i < NumElts; ++i) {
4847     // Increment the expected index.  If it wraps around, just follow it
4848     // back to index zero and keep going.
4849     ++ExpectedElt;
4850     if (ExpectedElt == NumElts)
4851       ExpectedElt = 0;
4852
4853     if (M[i] < 0) continue; // ignore UNDEF indices
4854     if (ExpectedElt != static_cast<unsigned>(M[i]))
4855       return false;
4856   }
4857
4858   return true;
4859 }
4860
4861
4862 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4863                        bool &ReverseVEXT, unsigned &Imm) {
4864   unsigned NumElts = VT.getVectorNumElements();
4865   ReverseVEXT = false;
4866
4867   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4868   if (M[0] < 0)
4869     return false;
4870
4871   Imm = M[0];
4872
4873   // If this is a VEXT shuffle, the immediate value is the index of the first
4874   // element.  The other shuffle indices must be the successive elements after
4875   // the first one.
4876   unsigned ExpectedElt = Imm;
4877   for (unsigned i = 1; i < NumElts; ++i) {
4878     // Increment the expected index.  If it wraps around, it may still be
4879     // a VEXT but the source vectors must be swapped.
4880     ExpectedElt += 1;
4881     if (ExpectedElt == NumElts * 2) {
4882       ExpectedElt = 0;
4883       ReverseVEXT = true;
4884     }
4885
4886     if (M[i] < 0) continue; // ignore UNDEF indices
4887     if (ExpectedElt != static_cast<unsigned>(M[i]))
4888       return false;
4889   }
4890
4891   // Adjust the index value if the source operands will be swapped.
4892   if (ReverseVEXT)
4893     Imm -= NumElts;
4894
4895   return true;
4896 }
4897
4898 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4899 /// instruction with the specified blocksize.  (The order of the elements
4900 /// within each block of the vector is reversed.)
4901 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4902   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4903          "Only possible block sizes for VREV are: 16, 32, 64");
4904
4905   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4906   if (EltSz == 64)
4907     return false;
4908
4909   unsigned NumElts = VT.getVectorNumElements();
4910   unsigned BlockElts = M[0] + 1;
4911   // If the first shuffle index is UNDEF, be optimistic.
4912   if (M[0] < 0)
4913     BlockElts = BlockSize / EltSz;
4914
4915   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4916     return false;
4917
4918   for (unsigned i = 0; i < NumElts; ++i) {
4919     if (M[i] < 0) continue; // ignore UNDEF indices
4920     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4921       return false;
4922   }
4923
4924   return true;
4925 }
4926
4927 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4928   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4929   // range, then 0 is placed into the resulting vector. So pretty much any mask
4930   // of 8 elements can work here.
4931   return VT == MVT::v8i8 && M.size() == 8;
4932 }
4933
4934 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4935   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4936   if (EltSz == 64)
4937     return false;
4938
4939   unsigned NumElts = VT.getVectorNumElements();
4940   WhichResult = (M[0] == 0 ? 0 : 1);
4941   for (unsigned i = 0; i < NumElts; i += 2) {
4942     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4943         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4944       return false;
4945   }
4946   return true;
4947 }
4948
4949 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4950 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4951 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4952 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4953   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4954   if (EltSz == 64)
4955     return false;
4956
4957   unsigned NumElts = VT.getVectorNumElements();
4958   WhichResult = (M[0] == 0 ? 0 : 1);
4959   for (unsigned i = 0; i < NumElts; i += 2) {
4960     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4961         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4962       return false;
4963   }
4964   return true;
4965 }
4966
4967 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4968   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4969   if (EltSz == 64)
4970     return false;
4971
4972   unsigned NumElts = VT.getVectorNumElements();
4973   WhichResult = (M[0] == 0 ? 0 : 1);
4974   for (unsigned i = 0; i != NumElts; ++i) {
4975     if (M[i] < 0) continue; // ignore UNDEF indices
4976     if ((unsigned) M[i] != 2 * i + WhichResult)
4977       return false;
4978   }
4979
4980   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4981   if (VT.is64BitVector() && EltSz == 32)
4982     return false;
4983
4984   return true;
4985 }
4986
4987 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4988 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4989 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4990 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4991   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4992   if (EltSz == 64)
4993     return false;
4994
4995   unsigned Half = VT.getVectorNumElements() / 2;
4996   WhichResult = (M[0] == 0 ? 0 : 1);
4997   for (unsigned j = 0; j != 2; ++j) {
4998     unsigned Idx = WhichResult;
4999     for (unsigned i = 0; i != Half; ++i) {
5000       int MIdx = M[i + j * Half];
5001       if (MIdx >= 0 && (unsigned) MIdx != Idx)
5002         return false;
5003       Idx += 2;
5004     }
5005   }
5006
5007   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5008   if (VT.is64BitVector() && EltSz == 32)
5009     return false;
5010
5011   return true;
5012 }
5013
5014 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5015   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5016   if (EltSz == 64)
5017     return false;
5018
5019   unsigned NumElts = VT.getVectorNumElements();
5020   WhichResult = (M[0] == 0 ? 0 : 1);
5021   unsigned Idx = WhichResult * NumElts / 2;
5022   for (unsigned i = 0; i != NumElts; i += 2) {
5023     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5024         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5025       return false;
5026     Idx += 1;
5027   }
5028
5029   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5030   if (VT.is64BitVector() && EltSz == 32)
5031     return false;
5032
5033   return true;
5034 }
5035
5036 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5037 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5038 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5039 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5040   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5041   if (EltSz == 64)
5042     return false;
5043
5044   unsigned NumElts = VT.getVectorNumElements();
5045   WhichResult = (M[0] == 0 ? 0 : 1);
5046   unsigned Idx = WhichResult * NumElts / 2;
5047   for (unsigned i = 0; i != NumElts; i += 2) {
5048     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5049         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5050       return false;
5051     Idx += 1;
5052   }
5053
5054   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5055   if (VT.is64BitVector() && EltSz == 32)
5056     return false;
5057
5058   return true;
5059 }
5060
5061 /// \return true if this is a reverse operation on an vector.
5062 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5063   unsigned NumElts = VT.getVectorNumElements();
5064   // Make sure the mask has the right size.
5065   if (NumElts != M.size())
5066       return false;
5067
5068   // Look for <15, ..., 3, -1, 1, 0>.
5069   for (unsigned i = 0; i != NumElts; ++i)
5070     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5071       return false;
5072
5073   return true;
5074 }
5075
5076 // If N is an integer constant that can be moved into a register in one
5077 // instruction, return an SDValue of such a constant (will become a MOV
5078 // instruction).  Otherwise return null.
5079 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5080                                      const ARMSubtarget *ST, SDLoc dl) {
5081   uint64_t Val;
5082   if (!isa<ConstantSDNode>(N))
5083     return SDValue();
5084   Val = cast<ConstantSDNode>(N)->getZExtValue();
5085
5086   if (ST->isThumb1Only()) {
5087     if (Val <= 255 || ~Val <= 255)
5088       return DAG.getConstant(Val, dl, MVT::i32);
5089   } else {
5090     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5091       return DAG.getConstant(Val, dl, MVT::i32);
5092   }
5093   return SDValue();
5094 }
5095
5096 // If this is a case we can't handle, return null and let the default
5097 // expansion code take care of it.
5098 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5099                                              const ARMSubtarget *ST) const {
5100   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5101   SDLoc dl(Op);
5102   EVT VT = Op.getValueType();
5103
5104   APInt SplatBits, SplatUndef;
5105   unsigned SplatBitSize;
5106   bool HasAnyUndefs;
5107   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5108     if (SplatBitSize <= 64) {
5109       // Check if an immediate VMOV works.
5110       EVT VmovVT;
5111       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5112                                       SplatUndef.getZExtValue(), SplatBitSize,
5113                                       DAG, dl, VmovVT, VT.is128BitVector(),
5114                                       VMOVModImm);
5115       if (Val.getNode()) {
5116         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5117         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5118       }
5119
5120       // Try an immediate VMVN.
5121       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5122       Val = isNEONModifiedImm(NegatedImm,
5123                                       SplatUndef.getZExtValue(), SplatBitSize,
5124                                       DAG, dl, VmovVT, VT.is128BitVector(),
5125                                       VMVNModImm);
5126       if (Val.getNode()) {
5127         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5128         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5129       }
5130
5131       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5132       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5133         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5134         if (ImmVal != -1) {
5135           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5136           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5137         }
5138       }
5139     }
5140   }
5141
5142   // Scan through the operands to see if only one value is used.
5143   //
5144   // As an optimisation, even if more than one value is used it may be more
5145   // profitable to splat with one value then change some lanes.
5146   //
5147   // Heuristically we decide to do this if the vector has a "dominant" value,
5148   // defined as splatted to more than half of the lanes.
5149   unsigned NumElts = VT.getVectorNumElements();
5150   bool isOnlyLowElement = true;
5151   bool usesOnlyOneValue = true;
5152   bool hasDominantValue = false;
5153   bool isConstant = true;
5154
5155   // Map of the number of times a particular SDValue appears in the
5156   // element list.
5157   DenseMap<SDValue, unsigned> ValueCounts;
5158   SDValue Value;
5159   for (unsigned i = 0; i < NumElts; ++i) {
5160     SDValue V = Op.getOperand(i);
5161     if (V.getOpcode() == ISD::UNDEF)
5162       continue;
5163     if (i > 0)
5164       isOnlyLowElement = false;
5165     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5166       isConstant = false;
5167
5168     ValueCounts.insert(std::make_pair(V, 0));
5169     unsigned &Count = ValueCounts[V];
5170
5171     // Is this value dominant? (takes up more than half of the lanes)
5172     if (++Count > (NumElts / 2)) {
5173       hasDominantValue = true;
5174       Value = V;
5175     }
5176   }
5177   if (ValueCounts.size() != 1)
5178     usesOnlyOneValue = false;
5179   if (!Value.getNode() && ValueCounts.size() > 0)
5180     Value = ValueCounts.begin()->first;
5181
5182   if (ValueCounts.size() == 0)
5183     return DAG.getUNDEF(VT);
5184
5185   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5186   // Keep going if we are hitting this case.
5187   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5188     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5189
5190   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5191
5192   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5193   // i32 and try again.
5194   if (hasDominantValue && EltSize <= 32) {
5195     if (!isConstant) {
5196       SDValue N;
5197
5198       // If we are VDUPing a value that comes directly from a vector, that will
5199       // cause an unnecessary move to and from a GPR, where instead we could
5200       // just use VDUPLANE. We can only do this if the lane being extracted
5201       // is at a constant index, as the VDUP from lane instructions only have
5202       // constant-index forms.
5203       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5204           isa<ConstantSDNode>(Value->getOperand(1))) {
5205         // We need to create a new undef vector to use for the VDUPLANE if the
5206         // size of the vector from which we get the value is different than the
5207         // size of the vector that we need to create. We will insert the element
5208         // such that the register coalescer will remove unnecessary copies.
5209         if (VT != Value->getOperand(0).getValueType()) {
5210           ConstantSDNode *constIndex;
5211           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5212           assert(constIndex && "The index is not a constant!");
5213           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5214                              VT.getVectorNumElements();
5215           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5216                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5217                         Value, DAG.getConstant(index, dl, MVT::i32)),
5218                            DAG.getConstant(index, dl, MVT::i32));
5219         } else
5220           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5221                         Value->getOperand(0), Value->getOperand(1));
5222       } else
5223         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5224
5225       if (!usesOnlyOneValue) {
5226         // The dominant value was splatted as 'N', but we now have to insert
5227         // all differing elements.
5228         for (unsigned I = 0; I < NumElts; ++I) {
5229           if (Op.getOperand(I) == Value)
5230             continue;
5231           SmallVector<SDValue, 3> Ops;
5232           Ops.push_back(N);
5233           Ops.push_back(Op.getOperand(I));
5234           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5235           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5236         }
5237       }
5238       return N;
5239     }
5240     if (VT.getVectorElementType().isFloatingPoint()) {
5241       SmallVector<SDValue, 8> Ops;
5242       for (unsigned i = 0; i < NumElts; ++i)
5243         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5244                                   Op.getOperand(i)));
5245       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5246       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5247       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5248       if (Val.getNode())
5249         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5250     }
5251     if (usesOnlyOneValue) {
5252       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5253       if (isConstant && Val.getNode())
5254         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5255     }
5256   }
5257
5258   // If all elements are constants and the case above didn't get hit, fall back
5259   // to the default expansion, which will generate a load from the constant
5260   // pool.
5261   if (isConstant)
5262     return SDValue();
5263
5264   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5265   if (NumElts >= 4) {
5266     SDValue shuffle = ReconstructShuffle(Op, DAG);
5267     if (shuffle != SDValue())
5268       return shuffle;
5269   }
5270
5271   // Vectors with 32- or 64-bit elements can be built by directly assigning
5272   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5273   // will be legalized.
5274   if (EltSize >= 32) {
5275     // Do the expansion with floating-point types, since that is what the VFP
5276     // registers are defined to use, and since i64 is not legal.
5277     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5278     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5279     SmallVector<SDValue, 8> Ops;
5280     for (unsigned i = 0; i < NumElts; ++i)
5281       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5282     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5283     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5284   }
5285
5286   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5287   // know the default expansion would otherwise fall back on something even
5288   // worse. For a vector with one or two non-undef values, that's
5289   // scalar_to_vector for the elements followed by a shuffle (provided the
5290   // shuffle is valid for the target) and materialization element by element
5291   // on the stack followed by a load for everything else.
5292   if (!isConstant && !usesOnlyOneValue) {
5293     SDValue Vec = DAG.getUNDEF(VT);
5294     for (unsigned i = 0 ; i < NumElts; ++i) {
5295       SDValue V = Op.getOperand(i);
5296       if (V.getOpcode() == ISD::UNDEF)
5297         continue;
5298       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5299       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5300     }
5301     return Vec;
5302   }
5303
5304   return SDValue();
5305 }
5306
5307 // Gather data to see if the operation can be modelled as a
5308 // shuffle in combination with VEXTs.
5309 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5310                                               SelectionDAG &DAG) const {
5311   SDLoc dl(Op);
5312   EVT VT = Op.getValueType();
5313   unsigned NumElts = VT.getVectorNumElements();
5314
5315   SmallVector<SDValue, 2> SourceVecs;
5316   SmallVector<unsigned, 2> MinElts;
5317   SmallVector<unsigned, 2> MaxElts;
5318
5319   for (unsigned i = 0; i < NumElts; ++i) {
5320     SDValue V = Op.getOperand(i);
5321     if (V.getOpcode() == ISD::UNDEF)
5322       continue;
5323     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5324       // A shuffle can only come from building a vector from various
5325       // elements of other vectors.
5326       return SDValue();
5327     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5328                VT.getVectorElementType()) {
5329       // This code doesn't know how to handle shuffles where the vector
5330       // element types do not match (this happens because type legalization
5331       // promotes the return type of EXTRACT_VECTOR_ELT).
5332       // FIXME: It might be appropriate to extend this code to handle
5333       // mismatched types.
5334       return SDValue();
5335     }
5336
5337     // Record this extraction against the appropriate vector if possible...
5338     SDValue SourceVec = V.getOperand(0);
5339     // If the element number isn't a constant, we can't effectively
5340     // analyze what's going on.
5341     if (!isa<ConstantSDNode>(V.getOperand(1)))
5342       return SDValue();
5343     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5344     bool FoundSource = false;
5345     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5346       if (SourceVecs[j] == SourceVec) {
5347         if (MinElts[j] > EltNo)
5348           MinElts[j] = EltNo;
5349         if (MaxElts[j] < EltNo)
5350           MaxElts[j] = EltNo;
5351         FoundSource = true;
5352         break;
5353       }
5354     }
5355
5356     // Or record a new source if not...
5357     if (!FoundSource) {
5358       SourceVecs.push_back(SourceVec);
5359       MinElts.push_back(EltNo);
5360       MaxElts.push_back(EltNo);
5361     }
5362   }
5363
5364   // Currently only do something sane when at most two source vectors
5365   // involved.
5366   if (SourceVecs.size() > 2)
5367     return SDValue();
5368
5369   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5370   int VEXTOffsets[2] = {0, 0};
5371
5372   // This loop extracts the usage patterns of the source vectors
5373   // and prepares appropriate SDValues for a shuffle if possible.
5374   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5375     if (SourceVecs[i].getValueType() == VT) {
5376       // No VEXT necessary
5377       ShuffleSrcs[i] = SourceVecs[i];
5378       VEXTOffsets[i] = 0;
5379       continue;
5380     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5381       // It probably isn't worth padding out a smaller vector just to
5382       // break it down again in a shuffle.
5383       return SDValue();
5384     }
5385
5386     // Since only 64-bit and 128-bit vectors are legal on ARM and
5387     // we've eliminated the other cases...
5388     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5389            "unexpected vector sizes in ReconstructShuffle");
5390
5391     if (MaxElts[i] - MinElts[i] >= NumElts) {
5392       // Span too large for a VEXT to cope
5393       return SDValue();
5394     }
5395
5396     if (MinElts[i] >= NumElts) {
5397       // The extraction can just take the second half
5398       VEXTOffsets[i] = NumElts;
5399       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5400                                    SourceVecs[i],
5401                                    DAG.getIntPtrConstant(NumElts, dl));
5402     } else if (MaxElts[i] < NumElts) {
5403       // The extraction can just take the first half
5404       VEXTOffsets[i] = 0;
5405       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5406                                    SourceVecs[i],
5407                                    DAG.getIntPtrConstant(0, dl));
5408     } else {
5409       // An actual VEXT is needed
5410       VEXTOffsets[i] = MinElts[i];
5411       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5412                                      SourceVecs[i],
5413                                      DAG.getIntPtrConstant(0, dl));
5414       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5415                                      SourceVecs[i],
5416                                      DAG.getIntPtrConstant(NumElts, dl));
5417       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5418                                    DAG.getConstant(VEXTOffsets[i], dl,
5419                                                    MVT::i32));
5420     }
5421   }
5422
5423   SmallVector<int, 8> Mask;
5424
5425   for (unsigned i = 0; i < NumElts; ++i) {
5426     SDValue Entry = Op.getOperand(i);
5427     if (Entry.getOpcode() == ISD::UNDEF) {
5428       Mask.push_back(-1);
5429       continue;
5430     }
5431
5432     SDValue ExtractVec = Entry.getOperand(0);
5433     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5434                                           .getOperand(1))->getSExtValue();
5435     if (ExtractVec == SourceVecs[0]) {
5436       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5437     } else {
5438       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5439     }
5440   }
5441
5442   // Final check before we try to produce nonsense...
5443   if (isShuffleMaskLegal(Mask, VT))
5444     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5445                                 &Mask[0]);
5446
5447   return SDValue();
5448 }
5449
5450 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5451 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5452 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5453 /// are assumed to be legal.
5454 bool
5455 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5456                                       EVT VT) const {
5457   if (VT.getVectorNumElements() == 4 &&
5458       (VT.is128BitVector() || VT.is64BitVector())) {
5459     unsigned PFIndexes[4];
5460     for (unsigned i = 0; i != 4; ++i) {
5461       if (M[i] < 0)
5462         PFIndexes[i] = 8;
5463       else
5464         PFIndexes[i] = M[i];
5465     }
5466
5467     // Compute the index in the perfect shuffle table.
5468     unsigned PFTableIndex =
5469       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5470     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5471     unsigned Cost = (PFEntry >> 30);
5472
5473     if (Cost <= 4)
5474       return true;
5475   }
5476
5477   bool ReverseVEXT;
5478   unsigned Imm, WhichResult;
5479
5480   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5481   return (EltSize >= 32 ||
5482           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5483           isVREVMask(M, VT, 64) ||
5484           isVREVMask(M, VT, 32) ||
5485           isVREVMask(M, VT, 16) ||
5486           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5487           isVTBLMask(M, VT) ||
5488           isVTRNMask(M, VT, WhichResult) ||
5489           isVUZPMask(M, VT, WhichResult) ||
5490           isVZIPMask(M, VT, WhichResult) ||
5491           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5492           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5493           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5494           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5495 }
5496
5497 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5498 /// the specified operations to build the shuffle.
5499 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5500                                       SDValue RHS, SelectionDAG &DAG,
5501                                       SDLoc dl) {
5502   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5503   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5504   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5505
5506   enum {
5507     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5508     OP_VREV,
5509     OP_VDUP0,
5510     OP_VDUP1,
5511     OP_VDUP2,
5512     OP_VDUP3,
5513     OP_VEXT1,
5514     OP_VEXT2,
5515     OP_VEXT3,
5516     OP_VUZPL, // VUZP, left result
5517     OP_VUZPR, // VUZP, right result
5518     OP_VZIPL, // VZIP, left result
5519     OP_VZIPR, // VZIP, right result
5520     OP_VTRNL, // VTRN, left result
5521     OP_VTRNR  // VTRN, right result
5522   };
5523
5524   if (OpNum == OP_COPY) {
5525     if (LHSID == (1*9+2)*9+3) return LHS;
5526     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5527     return RHS;
5528   }
5529
5530   SDValue OpLHS, OpRHS;
5531   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5532   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5533   EVT VT = OpLHS.getValueType();
5534
5535   switch (OpNum) {
5536   default: llvm_unreachable("Unknown shuffle opcode!");
5537   case OP_VREV:
5538     // VREV divides the vector in half and swaps within the half.
5539     if (VT.getVectorElementType() == MVT::i32 ||
5540         VT.getVectorElementType() == MVT::f32)
5541       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5542     // vrev <4 x i16> -> VREV32
5543     if (VT.getVectorElementType() == MVT::i16)
5544       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5545     // vrev <4 x i8> -> VREV16
5546     assert(VT.getVectorElementType() == MVT::i8);
5547     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5548   case OP_VDUP0:
5549   case OP_VDUP1:
5550   case OP_VDUP2:
5551   case OP_VDUP3:
5552     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5553                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5554   case OP_VEXT1:
5555   case OP_VEXT2:
5556   case OP_VEXT3:
5557     return DAG.getNode(ARMISD::VEXT, dl, VT,
5558                        OpLHS, OpRHS,
5559                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5560   case OP_VUZPL:
5561   case OP_VUZPR:
5562     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5563                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5564   case OP_VZIPL:
5565   case OP_VZIPR:
5566     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5567                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5568   case OP_VTRNL:
5569   case OP_VTRNR:
5570     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5571                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5572   }
5573 }
5574
5575 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5576                                        ArrayRef<int> ShuffleMask,
5577                                        SelectionDAG &DAG) {
5578   // Check to see if we can use the VTBL instruction.
5579   SDValue V1 = Op.getOperand(0);
5580   SDValue V2 = Op.getOperand(1);
5581   SDLoc DL(Op);
5582
5583   SmallVector<SDValue, 8> VTBLMask;
5584   for (ArrayRef<int>::iterator
5585          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5586     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5587
5588   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5589     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5590                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5591
5592   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5593                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5594 }
5595
5596 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5597                                                       SelectionDAG &DAG) {
5598   SDLoc DL(Op);
5599   SDValue OpLHS = Op.getOperand(0);
5600   EVT VT = OpLHS.getValueType();
5601
5602   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5603          "Expect an v8i16/v16i8 type");
5604   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5605   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5606   // extract the first 8 bytes into the top double word and the last 8 bytes
5607   // into the bottom double word. The v8i16 case is similar.
5608   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5609   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5610                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5611 }
5612
5613 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5614   SDValue V1 = Op.getOperand(0);
5615   SDValue V2 = Op.getOperand(1);
5616   SDLoc dl(Op);
5617   EVT VT = Op.getValueType();
5618   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5619
5620   // Convert shuffles that are directly supported on NEON to target-specific
5621   // DAG nodes, instead of keeping them as shuffles and matching them again
5622   // during code selection.  This is more efficient and avoids the possibility
5623   // of inconsistencies between legalization and selection.
5624   // FIXME: floating-point vectors should be canonicalized to integer vectors
5625   // of the same time so that they get CSEd properly.
5626   ArrayRef<int> ShuffleMask = SVN->getMask();
5627
5628   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5629   if (EltSize <= 32) {
5630     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5631       int Lane = SVN->getSplatIndex();
5632       // If this is undef splat, generate it via "just" vdup, if possible.
5633       if (Lane == -1) Lane = 0;
5634
5635       // Test if V1 is a SCALAR_TO_VECTOR.
5636       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5637         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5638       }
5639       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5640       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5641       // reaches it).
5642       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5643           !isa<ConstantSDNode>(V1.getOperand(0))) {
5644         bool IsScalarToVector = true;
5645         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5646           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5647             IsScalarToVector = false;
5648             break;
5649           }
5650         if (IsScalarToVector)
5651           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5652       }
5653       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5654                          DAG.getConstant(Lane, dl, MVT::i32));
5655     }
5656
5657     bool ReverseVEXT;
5658     unsigned Imm;
5659     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5660       if (ReverseVEXT)
5661         std::swap(V1, V2);
5662       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5663                          DAG.getConstant(Imm, dl, MVT::i32));
5664     }
5665
5666     if (isVREVMask(ShuffleMask, VT, 64))
5667       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5668     if (isVREVMask(ShuffleMask, VT, 32))
5669       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5670     if (isVREVMask(ShuffleMask, VT, 16))
5671       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5672
5673     if (V2->getOpcode() == ISD::UNDEF &&
5674         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5675       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5676                          DAG.getConstant(Imm, dl, MVT::i32));
5677     }
5678
5679     // Check for Neon shuffles that modify both input vectors in place.
5680     // If both results are used, i.e., if there are two shuffles with the same
5681     // source operands and with masks corresponding to both results of one of
5682     // these operations, DAG memoization will ensure that a single node is
5683     // used for both shuffles.
5684     unsigned WhichResult;
5685     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5686       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5687                          V1, V2).getValue(WhichResult);
5688     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5689       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5690                          V1, V2).getValue(WhichResult);
5691     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5692       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5693                          V1, V2).getValue(WhichResult);
5694
5695     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5696       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5697                          V1, V1).getValue(WhichResult);
5698     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5699       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5700                          V1, V1).getValue(WhichResult);
5701     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5702       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5703                          V1, V1).getValue(WhichResult);
5704   }
5705
5706   // If the shuffle is not directly supported and it has 4 elements, use
5707   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5708   unsigned NumElts = VT.getVectorNumElements();
5709   if (NumElts == 4) {
5710     unsigned PFIndexes[4];
5711     for (unsigned i = 0; i != 4; ++i) {
5712       if (ShuffleMask[i] < 0)
5713         PFIndexes[i] = 8;
5714       else
5715         PFIndexes[i] = ShuffleMask[i];
5716     }
5717
5718     // Compute the index in the perfect shuffle table.
5719     unsigned PFTableIndex =
5720       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5721     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5722     unsigned Cost = (PFEntry >> 30);
5723
5724     if (Cost <= 4)
5725       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5726   }
5727
5728   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5729   if (EltSize >= 32) {
5730     // Do the expansion with floating-point types, since that is what the VFP
5731     // registers are defined to use, and since i64 is not legal.
5732     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5733     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5734     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5735     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5736     SmallVector<SDValue, 8> Ops;
5737     for (unsigned i = 0; i < NumElts; ++i) {
5738       if (ShuffleMask[i] < 0)
5739         Ops.push_back(DAG.getUNDEF(EltVT));
5740       else
5741         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5742                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5743                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5744                                                   dl, MVT::i32)));
5745     }
5746     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5747     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5748   }
5749
5750   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5751     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5752
5753   if (VT == MVT::v8i8) {
5754     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5755     if (NewOp.getNode())
5756       return NewOp;
5757   }
5758
5759   return SDValue();
5760 }
5761
5762 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5763   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5764   SDValue Lane = Op.getOperand(2);
5765   if (!isa<ConstantSDNode>(Lane))
5766     return SDValue();
5767
5768   return Op;
5769 }
5770
5771 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5772   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5773   SDValue Lane = Op.getOperand(1);
5774   if (!isa<ConstantSDNode>(Lane))
5775     return SDValue();
5776
5777   SDValue Vec = Op.getOperand(0);
5778   if (Op.getValueType() == MVT::i32 &&
5779       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5780     SDLoc dl(Op);
5781     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5782   }
5783
5784   return Op;
5785 }
5786
5787 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5788   // The only time a CONCAT_VECTORS operation can have legal types is when
5789   // two 64-bit vectors are concatenated to a 128-bit vector.
5790   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5791          "unexpected CONCAT_VECTORS");
5792   SDLoc dl(Op);
5793   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5794   SDValue Op0 = Op.getOperand(0);
5795   SDValue Op1 = Op.getOperand(1);
5796   if (Op0.getOpcode() != ISD::UNDEF)
5797     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5798                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5799                       DAG.getIntPtrConstant(0, dl));
5800   if (Op1.getOpcode() != ISD::UNDEF)
5801     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5802                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5803                       DAG.getIntPtrConstant(1, dl));
5804   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5805 }
5806
5807 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5808 /// element has been zero/sign-extended, depending on the isSigned parameter,
5809 /// from an integer type half its size.
5810 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5811                                    bool isSigned) {
5812   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5813   EVT VT = N->getValueType(0);
5814   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5815     SDNode *BVN = N->getOperand(0).getNode();
5816     if (BVN->getValueType(0) != MVT::v4i32 ||
5817         BVN->getOpcode() != ISD::BUILD_VECTOR)
5818       return false;
5819     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5820     unsigned HiElt = 1 - LoElt;
5821     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5822     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5823     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5824     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5825     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5826       return false;
5827     if (isSigned) {
5828       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5829           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5830         return true;
5831     } else {
5832       if (Hi0->isNullValue() && Hi1->isNullValue())
5833         return true;
5834     }
5835     return false;
5836   }
5837
5838   if (N->getOpcode() != ISD::BUILD_VECTOR)
5839     return false;
5840
5841   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5842     SDNode *Elt = N->getOperand(i).getNode();
5843     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5844       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5845       unsigned HalfSize = EltSize / 2;
5846       if (isSigned) {
5847         if (!isIntN(HalfSize, C->getSExtValue()))
5848           return false;
5849       } else {
5850         if (!isUIntN(HalfSize, C->getZExtValue()))
5851           return false;
5852       }
5853       continue;
5854     }
5855     return false;
5856   }
5857
5858   return true;
5859 }
5860
5861 /// isSignExtended - Check if a node is a vector value that is sign-extended
5862 /// or a constant BUILD_VECTOR with sign-extended elements.
5863 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5864   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5865     return true;
5866   if (isExtendedBUILD_VECTOR(N, DAG, true))
5867     return true;
5868   return false;
5869 }
5870
5871 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5872 /// or a constant BUILD_VECTOR with zero-extended elements.
5873 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5874   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5875     return true;
5876   if (isExtendedBUILD_VECTOR(N, DAG, false))
5877     return true;
5878   return false;
5879 }
5880
5881 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5882   if (OrigVT.getSizeInBits() >= 64)
5883     return OrigVT;
5884
5885   assert(OrigVT.isSimple() && "Expecting a simple value type");
5886
5887   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5888   switch (OrigSimpleTy) {
5889   default: llvm_unreachable("Unexpected Vector Type");
5890   case MVT::v2i8:
5891   case MVT::v2i16:
5892      return MVT::v2i32;
5893   case MVT::v4i8:
5894     return  MVT::v4i16;
5895   }
5896 }
5897
5898 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5899 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5900 /// We insert the required extension here to get the vector to fill a D register.
5901 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5902                                             const EVT &OrigTy,
5903                                             const EVT &ExtTy,
5904                                             unsigned ExtOpcode) {
5905   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5906   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5907   // 64-bits we need to insert a new extension so that it will be 64-bits.
5908   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5909   if (OrigTy.getSizeInBits() >= 64)
5910     return N;
5911
5912   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5913   EVT NewVT = getExtensionTo64Bits(OrigTy);
5914
5915   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5916 }
5917
5918 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5919 /// does not do any sign/zero extension. If the original vector is less
5920 /// than 64 bits, an appropriate extension will be added after the load to
5921 /// reach a total size of 64 bits. We have to add the extension separately
5922 /// because ARM does not have a sign/zero extending load for vectors.
5923 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5924   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5925
5926   // The load already has the right type.
5927   if (ExtendedTy == LD->getMemoryVT())
5928     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5929                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5930                 LD->isNonTemporal(), LD->isInvariant(),
5931                 LD->getAlignment());
5932
5933   // We need to create a zextload/sextload. We cannot just create a load
5934   // followed by a zext/zext node because LowerMUL is also run during normal
5935   // operation legalization where we can't create illegal types.
5936   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5937                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5938                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5939                         LD->isNonTemporal(), LD->getAlignment());
5940 }
5941
5942 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5943 /// extending load, or BUILD_VECTOR with extended elements, return the
5944 /// unextended value. The unextended vector should be 64 bits so that it can
5945 /// be used as an operand to a VMULL instruction. If the original vector size
5946 /// before extension is less than 64 bits we add a an extension to resize
5947 /// the vector to 64 bits.
5948 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5949   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5950     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5951                                         N->getOperand(0)->getValueType(0),
5952                                         N->getValueType(0),
5953                                         N->getOpcode());
5954
5955   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5956     return SkipLoadExtensionForVMULL(LD, DAG);
5957
5958   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5959   // have been legalized as a BITCAST from v4i32.
5960   if (N->getOpcode() == ISD::BITCAST) {
5961     SDNode *BVN = N->getOperand(0).getNode();
5962     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5963            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5964     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5965     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5966                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5967   }
5968   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5969   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5970   EVT VT = N->getValueType(0);
5971   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5972   unsigned NumElts = VT.getVectorNumElements();
5973   MVT TruncVT = MVT::getIntegerVT(EltSize);
5974   SmallVector<SDValue, 8> Ops;
5975   SDLoc dl(N);
5976   for (unsigned i = 0; i != NumElts; ++i) {
5977     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5978     const APInt &CInt = C->getAPIntValue();
5979     // Element types smaller than 32 bits are not legal, so use i32 elements.
5980     // The values are implicitly truncated so sext vs. zext doesn't matter.
5981     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
5982   }
5983   return DAG.getNode(ISD::BUILD_VECTOR, dl,
5984                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5985 }
5986
5987 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5988   unsigned Opcode = N->getOpcode();
5989   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5990     SDNode *N0 = N->getOperand(0).getNode();
5991     SDNode *N1 = N->getOperand(1).getNode();
5992     return N0->hasOneUse() && N1->hasOneUse() &&
5993       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5994   }
5995   return false;
5996 }
5997
5998 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5999   unsigned Opcode = N->getOpcode();
6000   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6001     SDNode *N0 = N->getOperand(0).getNode();
6002     SDNode *N1 = N->getOperand(1).getNode();
6003     return N0->hasOneUse() && N1->hasOneUse() &&
6004       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6005   }
6006   return false;
6007 }
6008
6009 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6010   // Multiplications are only custom-lowered for 128-bit vectors so that
6011   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6012   EVT VT = Op.getValueType();
6013   assert(VT.is128BitVector() && VT.isInteger() &&
6014          "unexpected type for custom-lowering ISD::MUL");
6015   SDNode *N0 = Op.getOperand(0).getNode();
6016   SDNode *N1 = Op.getOperand(1).getNode();
6017   unsigned NewOpc = 0;
6018   bool isMLA = false;
6019   bool isN0SExt = isSignExtended(N0, DAG);
6020   bool isN1SExt = isSignExtended(N1, DAG);
6021   if (isN0SExt && isN1SExt)
6022     NewOpc = ARMISD::VMULLs;
6023   else {
6024     bool isN0ZExt = isZeroExtended(N0, DAG);
6025     bool isN1ZExt = isZeroExtended(N1, DAG);
6026     if (isN0ZExt && isN1ZExt)
6027       NewOpc = ARMISD::VMULLu;
6028     else if (isN1SExt || isN1ZExt) {
6029       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6030       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6031       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6032         NewOpc = ARMISD::VMULLs;
6033         isMLA = true;
6034       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6035         NewOpc = ARMISD::VMULLu;
6036         isMLA = true;
6037       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6038         std::swap(N0, N1);
6039         NewOpc = ARMISD::VMULLu;
6040         isMLA = true;
6041       }
6042     }
6043
6044     if (!NewOpc) {
6045       if (VT == MVT::v2i64)
6046         // Fall through to expand this.  It is not legal.
6047         return SDValue();
6048       else
6049         // Other vector multiplications are legal.
6050         return Op;
6051     }
6052   }
6053
6054   // Legalize to a VMULL instruction.
6055   SDLoc DL(Op);
6056   SDValue Op0;
6057   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6058   if (!isMLA) {
6059     Op0 = SkipExtensionForVMULL(N0, DAG);
6060     assert(Op0.getValueType().is64BitVector() &&
6061            Op1.getValueType().is64BitVector() &&
6062            "unexpected types for extended operands to VMULL");
6063     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6064   }
6065
6066   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6067   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6068   //   vmull q0, d4, d6
6069   //   vmlal q0, d5, d6
6070   // is faster than
6071   //   vaddl q0, d4, d5
6072   //   vmovl q1, d6
6073   //   vmul  q0, q0, q1
6074   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6075   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6076   EVT Op1VT = Op1.getValueType();
6077   return DAG.getNode(N0->getOpcode(), DL, VT,
6078                      DAG.getNode(NewOpc, DL, VT,
6079                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6080                      DAG.getNode(NewOpc, DL, VT,
6081                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6082 }
6083
6084 static SDValue
6085 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6086   // Convert to float
6087   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6088   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6089   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6090   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6091   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6092   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6093   // Get reciprocal estimate.
6094   // float4 recip = vrecpeq_f32(yf);
6095   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6096                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6097                    Y);
6098   // Because char has a smaller range than uchar, we can actually get away
6099   // without any newton steps.  This requires that we use a weird bias
6100   // of 0xb000, however (again, this has been exhaustively tested).
6101   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6102   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6103   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6104   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6105   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6106   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6107   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6108   // Convert back to short.
6109   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6110   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6111   return X;
6112 }
6113
6114 static SDValue
6115 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6116   SDValue N2;
6117   // Convert to float.
6118   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6119   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6120   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6121   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6122   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6123   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6124
6125   // Use reciprocal estimate and one refinement step.
6126   // float4 recip = vrecpeq_f32(yf);
6127   // recip *= vrecpsq_f32(yf, recip);
6128   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6129                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6130                    N1);
6131   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6132                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6133                    N1, N2);
6134   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6135   // Because short has a smaller range than ushort, we can actually get away
6136   // with only a single newton step.  This requires that we use a weird bias
6137   // of 89, however (again, this has been exhaustively tested).
6138   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6139   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6140   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6141   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6142   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6143   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6144   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6145   // Convert back to integer and return.
6146   // return vmovn_s32(vcvt_s32_f32(result));
6147   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6148   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6149   return N0;
6150 }
6151
6152 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6153   EVT VT = Op.getValueType();
6154   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6155          "unexpected type for custom-lowering ISD::SDIV");
6156
6157   SDLoc dl(Op);
6158   SDValue N0 = Op.getOperand(0);
6159   SDValue N1 = Op.getOperand(1);
6160   SDValue N2, N3;
6161
6162   if (VT == MVT::v8i8) {
6163     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6164     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6165
6166     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6167                      DAG.getIntPtrConstant(4, dl));
6168     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6169                      DAG.getIntPtrConstant(4, dl));
6170     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6171                      DAG.getIntPtrConstant(0, dl));
6172     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6173                      DAG.getIntPtrConstant(0, dl));
6174
6175     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6176     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6177
6178     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6179     N0 = LowerCONCAT_VECTORS(N0, DAG);
6180
6181     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6182     return N0;
6183   }
6184   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6185 }
6186
6187 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6188   EVT VT = Op.getValueType();
6189   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6190          "unexpected type for custom-lowering ISD::UDIV");
6191
6192   SDLoc dl(Op);
6193   SDValue N0 = Op.getOperand(0);
6194   SDValue N1 = Op.getOperand(1);
6195   SDValue N2, N3;
6196
6197   if (VT == MVT::v8i8) {
6198     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6199     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6200
6201     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6202                      DAG.getIntPtrConstant(4, dl));
6203     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6204                      DAG.getIntPtrConstant(4, dl));
6205     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6206                      DAG.getIntPtrConstant(0, dl));
6207     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6208                      DAG.getIntPtrConstant(0, dl));
6209
6210     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6211     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6212
6213     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6214     N0 = LowerCONCAT_VECTORS(N0, DAG);
6215
6216     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6217                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6218                                      MVT::i32),
6219                      N0);
6220     return N0;
6221   }
6222
6223   // v4i16 sdiv ... Convert to float.
6224   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6225   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6226   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6227   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6228   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6229   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6230
6231   // Use reciprocal estimate and two refinement steps.
6232   // float4 recip = vrecpeq_f32(yf);
6233   // recip *= vrecpsq_f32(yf, recip);
6234   // recip *= vrecpsq_f32(yf, recip);
6235   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6236                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6237                    BN1);
6238   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6239                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6240                    BN1, N2);
6241   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6242   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6243                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6244                    BN1, N2);
6245   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6246   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6247   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6248   // and that it will never cause us to return an answer too large).
6249   // float4 result = as_float4(as_int4(xf*recip) + 2);
6250   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6251   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6252   N1 = DAG.getConstant(2, dl, MVT::i32);
6253   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6254   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6255   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6256   // Convert back to integer and return.
6257   // return vmovn_u32(vcvt_s32_f32(result));
6258   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6259   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6260   return N0;
6261 }
6262
6263 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6264   EVT VT = Op.getNode()->getValueType(0);
6265   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6266
6267   unsigned Opc;
6268   bool ExtraOp = false;
6269   switch (Op.getOpcode()) {
6270   default: llvm_unreachable("Invalid code");
6271   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6272   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6273   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6274   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6275   }
6276
6277   if (!ExtraOp)
6278     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6279                        Op.getOperand(1));
6280   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6281                      Op.getOperand(1), Op.getOperand(2));
6282 }
6283
6284 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6285   assert(Subtarget->isTargetDarwin());
6286
6287   // For iOS, we want to call an alternative entry point: __sincos_stret,
6288   // return values are passed via sret.
6289   SDLoc dl(Op);
6290   SDValue Arg = Op.getOperand(0);
6291   EVT ArgVT = Arg.getValueType();
6292   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6293
6294   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6295   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6296
6297   // Pair of floats / doubles used to pass the result.
6298   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6299
6300   // Create stack object for sret.
6301   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6302   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6303   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6304   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6305
6306   ArgListTy Args;
6307   ArgListEntry Entry;
6308
6309   Entry.Node = SRet;
6310   Entry.Ty = RetTy->getPointerTo();
6311   Entry.isSExt = false;
6312   Entry.isZExt = false;
6313   Entry.isSRet = true;
6314   Args.push_back(Entry);
6315
6316   Entry.Node = Arg;
6317   Entry.Ty = ArgTy;
6318   Entry.isSExt = false;
6319   Entry.isZExt = false;
6320   Args.push_back(Entry);
6321
6322   const char *LibcallName  = (ArgVT == MVT::f64)
6323   ? "__sincos_stret" : "__sincosf_stret";
6324   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6325
6326   TargetLowering::CallLoweringInfo CLI(DAG);
6327   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6328     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6329                std::move(Args), 0)
6330     .setDiscardResult();
6331
6332   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6333
6334   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6335                                 MachinePointerInfo(), false, false, false, 0);
6336
6337   // Address of cos field.
6338   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6339                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6340   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6341                                 MachinePointerInfo(), false, false, false, 0);
6342
6343   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6344   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6345                      LoadSin.getValue(0), LoadCos.getValue(0));
6346 }
6347
6348 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6349   // Monotonic load/store is legal for all targets
6350   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6351     return Op;
6352
6353   // Acquire/Release load/store is not legal for targets without a
6354   // dmb or equivalent available.
6355   return SDValue();
6356 }
6357
6358 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6359                                     SmallVectorImpl<SDValue> &Results,
6360                                     SelectionDAG &DAG,
6361                                     const ARMSubtarget *Subtarget) {
6362   SDLoc DL(N);
6363   SDValue Cycles32, OutChain;
6364
6365   if (Subtarget->hasPerfMon()) {
6366     // Under Power Management extensions, the cycle-count is:
6367     //    mrc p15, #0, <Rt>, c9, c13, #0
6368     SDValue Ops[] = { N->getOperand(0), // Chain
6369                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6370                       DAG.getConstant(15, DL, MVT::i32),
6371                       DAG.getConstant(0, DL, MVT::i32),
6372                       DAG.getConstant(9, DL, MVT::i32),
6373                       DAG.getConstant(13, DL, MVT::i32),
6374                       DAG.getConstant(0, DL, MVT::i32)
6375     };
6376
6377     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6378                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6379     OutChain = Cycles32.getValue(1);
6380   } else {
6381     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6382     // there are older ARM CPUs that have implementation-specific ways of
6383     // obtaining this information (FIXME!).
6384     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6385     OutChain = DAG.getEntryNode();
6386   }
6387
6388
6389   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6390                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6391   Results.push_back(Cycles64);
6392   Results.push_back(OutChain);
6393 }
6394
6395 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6396   switch (Op.getOpcode()) {
6397   default: llvm_unreachable("Don't know how to custom lower this!");
6398   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6399   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6400   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6401   case ISD::GlobalAddress:
6402     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6403     default: llvm_unreachable("unknown object format");
6404     case Triple::COFF:
6405       return LowerGlobalAddressWindows(Op, DAG);
6406     case Triple::ELF:
6407       return LowerGlobalAddressELF(Op, DAG);
6408     case Triple::MachO:
6409       return LowerGlobalAddressDarwin(Op, DAG);
6410     }
6411   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6412   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6413   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6414   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6415   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6416   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6417   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6418   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6419   case ISD::SINT_TO_FP:
6420   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6421   case ISD::FP_TO_SINT:
6422   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6423   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6424   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6425   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6426   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6427   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6428   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6429   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6430                                                                Subtarget);
6431   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6432   case ISD::SHL:
6433   case ISD::SRL:
6434   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6435   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6436   case ISD::SRL_PARTS:
6437   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6438   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6439   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6440   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6441   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6442   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6443   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6444   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6445   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6446   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6447   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6448   case ISD::MUL:           return LowerMUL(Op, DAG);
6449   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6450   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6451   case ISD::ADDC:
6452   case ISD::ADDE:
6453   case ISD::SUBC:
6454   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6455   case ISD::SADDO:
6456   case ISD::UADDO:
6457   case ISD::SSUBO:
6458   case ISD::USUBO:
6459     return LowerXALUO(Op, DAG);
6460   case ISD::ATOMIC_LOAD:
6461   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6462   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6463   case ISD::SDIVREM:
6464   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6465   case ISD::DYNAMIC_STACKALLOC:
6466     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6467       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6468     llvm_unreachable("Don't know how to custom lower this!");
6469   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6470   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6471   }
6472 }
6473
6474 /// ReplaceNodeResults - Replace the results of node with an illegal result
6475 /// type with new values built out of custom code.
6476 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6477                                            SmallVectorImpl<SDValue>&Results,
6478                                            SelectionDAG &DAG) const {
6479   SDValue Res;
6480   switch (N->getOpcode()) {
6481   default:
6482     llvm_unreachable("Don't know how to custom expand this!");
6483   case ISD::READ_REGISTER:
6484     Res = ExpandREAD_REGISTER(N, DAG);
6485     break;
6486   case ISD::BITCAST:
6487     Res = ExpandBITCAST(N, DAG);
6488     break;
6489   case ISD::SRL:
6490   case ISD::SRA:
6491     Res = Expand64BitShift(N, DAG, Subtarget);
6492     break;
6493   case ISD::READCYCLECOUNTER:
6494     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6495     return;
6496   }
6497   if (Res.getNode())
6498     Results.push_back(Res);
6499 }
6500
6501 //===----------------------------------------------------------------------===//
6502 //                           ARM Scheduler Hooks
6503 //===----------------------------------------------------------------------===//
6504
6505 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6506 /// registers the function context.
6507 void ARMTargetLowering::
6508 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6509                        MachineBasicBlock *DispatchBB, int FI) const {
6510   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6511   DebugLoc dl = MI->getDebugLoc();
6512   MachineFunction *MF = MBB->getParent();
6513   MachineRegisterInfo *MRI = &MF->getRegInfo();
6514   MachineConstantPool *MCP = MF->getConstantPool();
6515   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6516   const Function *F = MF->getFunction();
6517
6518   bool isThumb = Subtarget->isThumb();
6519   bool isThumb2 = Subtarget->isThumb2();
6520
6521   unsigned PCLabelId = AFI->createPICLabelUId();
6522   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6523   ARMConstantPoolValue *CPV =
6524     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6525   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6526
6527   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6528                                            : &ARM::GPRRegClass;
6529
6530   // Grab constant pool and fixed stack memory operands.
6531   MachineMemOperand *CPMMO =
6532     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6533                              MachineMemOperand::MOLoad, 4, 4);
6534
6535   MachineMemOperand *FIMMOSt =
6536     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6537                              MachineMemOperand::MOStore, 4, 4);
6538
6539   // Load the address of the dispatch MBB into the jump buffer.
6540   if (isThumb2) {
6541     // Incoming value: jbuf
6542     //   ldr.n  r5, LCPI1_1
6543     //   orr    r5, r5, #1
6544     //   add    r5, pc
6545     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6546     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6547     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6548                    .addConstantPoolIndex(CPI)
6549                    .addMemOperand(CPMMO));
6550     // Set the low bit because of thumb mode.
6551     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6552     AddDefaultCC(
6553       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6554                      .addReg(NewVReg1, RegState::Kill)
6555                      .addImm(0x01)));
6556     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6557     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6558       .addReg(NewVReg2, RegState::Kill)
6559       .addImm(PCLabelId);
6560     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6561                    .addReg(NewVReg3, RegState::Kill)
6562                    .addFrameIndex(FI)
6563                    .addImm(36)  // &jbuf[1] :: pc
6564                    .addMemOperand(FIMMOSt));
6565   } else if (isThumb) {
6566     // Incoming value: jbuf
6567     //   ldr.n  r1, LCPI1_4
6568     //   add    r1, pc
6569     //   mov    r2, #1
6570     //   orrs   r1, r2
6571     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6572     //   str    r1, [r2]
6573     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6574     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6575                    .addConstantPoolIndex(CPI)
6576                    .addMemOperand(CPMMO));
6577     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6578     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6579       .addReg(NewVReg1, RegState::Kill)
6580       .addImm(PCLabelId);
6581     // Set the low bit because of thumb mode.
6582     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6583     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6584                    .addReg(ARM::CPSR, RegState::Define)
6585                    .addImm(1));
6586     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6587     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6588                    .addReg(ARM::CPSR, RegState::Define)
6589                    .addReg(NewVReg2, RegState::Kill)
6590                    .addReg(NewVReg3, RegState::Kill));
6591     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6592     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6593             .addFrameIndex(FI)
6594             .addImm(36); // &jbuf[1] :: pc
6595     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6596                    .addReg(NewVReg4, RegState::Kill)
6597                    .addReg(NewVReg5, RegState::Kill)
6598                    .addImm(0)
6599                    .addMemOperand(FIMMOSt));
6600   } else {
6601     // Incoming value: jbuf
6602     //   ldr  r1, LCPI1_1
6603     //   add  r1, pc, r1
6604     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6605     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6606     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6607                    .addConstantPoolIndex(CPI)
6608                    .addImm(0)
6609                    .addMemOperand(CPMMO));
6610     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6611     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6612                    .addReg(NewVReg1, RegState::Kill)
6613                    .addImm(PCLabelId));
6614     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6615                    .addReg(NewVReg2, RegState::Kill)
6616                    .addFrameIndex(FI)
6617                    .addImm(36)  // &jbuf[1] :: pc
6618                    .addMemOperand(FIMMOSt));
6619   }
6620 }
6621
6622 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6623                                               MachineBasicBlock *MBB) const {
6624   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6625   DebugLoc dl = MI->getDebugLoc();
6626   MachineFunction *MF = MBB->getParent();
6627   MachineRegisterInfo *MRI = &MF->getRegInfo();
6628   MachineFrameInfo *MFI = MF->getFrameInfo();
6629   int FI = MFI->getFunctionContextIndex();
6630
6631   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6632                                                         : &ARM::GPRnopcRegClass;
6633
6634   // Get a mapping of the call site numbers to all of the landing pads they're
6635   // associated with.
6636   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6637   unsigned MaxCSNum = 0;
6638   MachineModuleInfo &MMI = MF->getMMI();
6639   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6640        ++BB) {
6641     if (!BB->isLandingPad()) continue;
6642
6643     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6644     // pad.
6645     for (MachineBasicBlock::iterator
6646            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6647       if (!II->isEHLabel()) continue;
6648
6649       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6650       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6651
6652       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6653       for (SmallVectorImpl<unsigned>::iterator
6654              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6655            CSI != CSE; ++CSI) {
6656         CallSiteNumToLPad[*CSI].push_back(BB);
6657         MaxCSNum = std::max(MaxCSNum, *CSI);
6658       }
6659       break;
6660     }
6661   }
6662
6663   // Get an ordered list of the machine basic blocks for the jump table.
6664   std::vector<MachineBasicBlock*> LPadList;
6665   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6666   LPadList.reserve(CallSiteNumToLPad.size());
6667   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6668     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6669     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6670            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6671       LPadList.push_back(*II);
6672       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6673     }
6674   }
6675
6676   assert(!LPadList.empty() &&
6677          "No landing pad destinations for the dispatch jump table!");
6678
6679   // Create the jump table and associated information.
6680   MachineJumpTableInfo *JTI =
6681     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6682   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6683   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6684
6685   // Create the MBBs for the dispatch code.
6686
6687   // Shove the dispatch's address into the return slot in the function context.
6688   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6689   DispatchBB->setIsLandingPad();
6690
6691   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6692   unsigned trap_opcode;
6693   if (Subtarget->isThumb())
6694     trap_opcode = ARM::tTRAP;
6695   else
6696     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6697
6698   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6699   DispatchBB->addSuccessor(TrapBB);
6700
6701   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6702   DispatchBB->addSuccessor(DispContBB);
6703
6704   // Insert and MBBs.
6705   MF->insert(MF->end(), DispatchBB);
6706   MF->insert(MF->end(), DispContBB);
6707   MF->insert(MF->end(), TrapBB);
6708
6709   // Insert code into the entry block that creates and registers the function
6710   // context.
6711   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6712
6713   MachineMemOperand *FIMMOLd =
6714     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6715                              MachineMemOperand::MOLoad |
6716                              MachineMemOperand::MOVolatile, 4, 4);
6717
6718   MachineInstrBuilder MIB;
6719   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6720
6721   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6722   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6723
6724   // Add a register mask with no preserved registers.  This results in all
6725   // registers being marked as clobbered.
6726   MIB.addRegMask(RI.getNoPreservedMask());
6727
6728   unsigned NumLPads = LPadList.size();
6729   if (Subtarget->isThumb2()) {
6730     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6731     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6732                    .addFrameIndex(FI)
6733                    .addImm(4)
6734                    .addMemOperand(FIMMOLd));
6735
6736     if (NumLPads < 256) {
6737       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6738                      .addReg(NewVReg1)
6739                      .addImm(LPadList.size()));
6740     } else {
6741       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6742       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6743                      .addImm(NumLPads & 0xFFFF));
6744
6745       unsigned VReg2 = VReg1;
6746       if ((NumLPads & 0xFFFF0000) != 0) {
6747         VReg2 = MRI->createVirtualRegister(TRC);
6748         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6749                        .addReg(VReg1)
6750                        .addImm(NumLPads >> 16));
6751       }
6752
6753       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6754                      .addReg(NewVReg1)
6755                      .addReg(VReg2));
6756     }
6757
6758     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6759       .addMBB(TrapBB)
6760       .addImm(ARMCC::HI)
6761       .addReg(ARM::CPSR);
6762
6763     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6764     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6765                    .addJumpTableIndex(MJTI));
6766
6767     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6768     AddDefaultCC(
6769       AddDefaultPred(
6770         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6771         .addReg(NewVReg3, RegState::Kill)
6772         .addReg(NewVReg1)
6773         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6774
6775     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6776       .addReg(NewVReg4, RegState::Kill)
6777       .addReg(NewVReg1)
6778       .addJumpTableIndex(MJTI);
6779   } else if (Subtarget->isThumb()) {
6780     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6781     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6782                    .addFrameIndex(FI)
6783                    .addImm(1)
6784                    .addMemOperand(FIMMOLd));
6785
6786     if (NumLPads < 256) {
6787       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6788                      .addReg(NewVReg1)
6789                      .addImm(NumLPads));
6790     } else {
6791       MachineConstantPool *ConstantPool = MF->getConstantPool();
6792       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6793       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6794
6795       // MachineConstantPool wants an explicit alignment.
6796       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6797       if (Align == 0)
6798         Align = getDataLayout()->getTypeAllocSize(C->getType());
6799       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6800
6801       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6802       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6803                      .addReg(VReg1, RegState::Define)
6804                      .addConstantPoolIndex(Idx));
6805       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6806                      .addReg(NewVReg1)
6807                      .addReg(VReg1));
6808     }
6809
6810     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6811       .addMBB(TrapBB)
6812       .addImm(ARMCC::HI)
6813       .addReg(ARM::CPSR);
6814
6815     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6816     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6817                    .addReg(ARM::CPSR, RegState::Define)
6818                    .addReg(NewVReg1)
6819                    .addImm(2));
6820
6821     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6822     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6823                    .addJumpTableIndex(MJTI));
6824
6825     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6826     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6827                    .addReg(ARM::CPSR, RegState::Define)
6828                    .addReg(NewVReg2, RegState::Kill)
6829                    .addReg(NewVReg3));
6830
6831     MachineMemOperand *JTMMOLd =
6832       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6833                                MachineMemOperand::MOLoad, 4, 4);
6834
6835     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6836     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6837                    .addReg(NewVReg4, RegState::Kill)
6838                    .addImm(0)
6839                    .addMemOperand(JTMMOLd));
6840
6841     unsigned NewVReg6 = NewVReg5;
6842     if (RelocM == Reloc::PIC_) {
6843       NewVReg6 = MRI->createVirtualRegister(TRC);
6844       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6845                      .addReg(ARM::CPSR, RegState::Define)
6846                      .addReg(NewVReg5, RegState::Kill)
6847                      .addReg(NewVReg3));
6848     }
6849
6850     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6851       .addReg(NewVReg6, RegState::Kill)
6852       .addJumpTableIndex(MJTI);
6853   } else {
6854     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6855     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6856                    .addFrameIndex(FI)
6857                    .addImm(4)
6858                    .addMemOperand(FIMMOLd));
6859
6860     if (NumLPads < 256) {
6861       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6862                      .addReg(NewVReg1)
6863                      .addImm(NumLPads));
6864     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6865       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6866       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6867                      .addImm(NumLPads & 0xFFFF));
6868
6869       unsigned VReg2 = VReg1;
6870       if ((NumLPads & 0xFFFF0000) != 0) {
6871         VReg2 = MRI->createVirtualRegister(TRC);
6872         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6873                        .addReg(VReg1)
6874                        .addImm(NumLPads >> 16));
6875       }
6876
6877       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6878                      .addReg(NewVReg1)
6879                      .addReg(VReg2));
6880     } else {
6881       MachineConstantPool *ConstantPool = MF->getConstantPool();
6882       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6883       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6884
6885       // MachineConstantPool wants an explicit alignment.
6886       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6887       if (Align == 0)
6888         Align = getDataLayout()->getTypeAllocSize(C->getType());
6889       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6890
6891       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6892       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6893                      .addReg(VReg1, RegState::Define)
6894                      .addConstantPoolIndex(Idx)
6895                      .addImm(0));
6896       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6897                      .addReg(NewVReg1)
6898                      .addReg(VReg1, RegState::Kill));
6899     }
6900
6901     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6902       .addMBB(TrapBB)
6903       .addImm(ARMCC::HI)
6904       .addReg(ARM::CPSR);
6905
6906     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6907     AddDefaultCC(
6908       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6909                      .addReg(NewVReg1)
6910                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6911     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6912     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6913                    .addJumpTableIndex(MJTI));
6914
6915     MachineMemOperand *JTMMOLd =
6916       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6917                                MachineMemOperand::MOLoad, 4, 4);
6918     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6919     AddDefaultPred(
6920       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6921       .addReg(NewVReg3, RegState::Kill)
6922       .addReg(NewVReg4)
6923       .addImm(0)
6924       .addMemOperand(JTMMOLd));
6925
6926     if (RelocM == Reloc::PIC_) {
6927       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6928         .addReg(NewVReg5, RegState::Kill)
6929         .addReg(NewVReg4)
6930         .addJumpTableIndex(MJTI);
6931     } else {
6932       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6933         .addReg(NewVReg5, RegState::Kill)
6934         .addJumpTableIndex(MJTI);
6935     }
6936   }
6937
6938   // Add the jump table entries as successors to the MBB.
6939   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6940   for (std::vector<MachineBasicBlock*>::iterator
6941          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6942     MachineBasicBlock *CurMBB = *I;
6943     if (SeenMBBs.insert(CurMBB).second)
6944       DispContBB->addSuccessor(CurMBB);
6945   }
6946
6947   // N.B. the order the invoke BBs are processed in doesn't matter here.
6948   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6949   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6950   for (MachineBasicBlock *BB : InvokeBBs) {
6951
6952     // Remove the landing pad successor from the invoke block and replace it
6953     // with the new dispatch block.
6954     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6955                                                   BB->succ_end());
6956     while (!Successors.empty()) {
6957       MachineBasicBlock *SMBB = Successors.pop_back_val();
6958       if (SMBB->isLandingPad()) {
6959         BB->removeSuccessor(SMBB);
6960         MBBLPads.push_back(SMBB);
6961       }
6962     }
6963
6964     BB->addSuccessor(DispatchBB);
6965
6966     // Find the invoke call and mark all of the callee-saved registers as
6967     // 'implicit defined' so that they're spilled. This prevents code from
6968     // moving instructions to before the EH block, where they will never be
6969     // executed.
6970     for (MachineBasicBlock::reverse_iterator
6971            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6972       if (!II->isCall()) continue;
6973
6974       DenseMap<unsigned, bool> DefRegs;
6975       for (MachineInstr::mop_iterator
6976              OI = II->operands_begin(), OE = II->operands_end();
6977            OI != OE; ++OI) {
6978         if (!OI->isReg()) continue;
6979         DefRegs[OI->getReg()] = true;
6980       }
6981
6982       MachineInstrBuilder MIB(*MF, &*II);
6983
6984       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6985         unsigned Reg = SavedRegs[i];
6986         if (Subtarget->isThumb2() &&
6987             !ARM::tGPRRegClass.contains(Reg) &&
6988             !ARM::hGPRRegClass.contains(Reg))
6989           continue;
6990         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6991           continue;
6992         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6993           continue;
6994         if (!DefRegs[Reg])
6995           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6996       }
6997
6998       break;
6999     }
7000   }
7001
7002   // Mark all former landing pads as non-landing pads. The dispatch is the only
7003   // landing pad now.
7004   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7005          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7006     (*I)->setIsLandingPad(false);
7007
7008   // The instruction is gone now.
7009   MI->eraseFromParent();
7010 }
7011
7012 static
7013 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7014   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7015        E = MBB->succ_end(); I != E; ++I)
7016     if (*I != Succ)
7017       return *I;
7018   llvm_unreachable("Expecting a BB with two successors!");
7019 }
7020
7021 /// Return the load opcode for a given load size. If load size >= 8,
7022 /// neon opcode will be returned.
7023 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7024   if (LdSize >= 8)
7025     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7026                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7027   if (IsThumb1)
7028     return LdSize == 4 ? ARM::tLDRi
7029                        : LdSize == 2 ? ARM::tLDRHi
7030                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7031   if (IsThumb2)
7032     return LdSize == 4 ? ARM::t2LDR_POST
7033                        : LdSize == 2 ? ARM::t2LDRH_POST
7034                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7035   return LdSize == 4 ? ARM::LDR_POST_IMM
7036                      : LdSize == 2 ? ARM::LDRH_POST
7037                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7038 }
7039
7040 /// Return the store opcode for a given store size. If store size >= 8,
7041 /// neon opcode will be returned.
7042 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7043   if (StSize >= 8)
7044     return StSize == 16 ? ARM::VST1q32wb_fixed
7045                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7046   if (IsThumb1)
7047     return StSize == 4 ? ARM::tSTRi
7048                        : StSize == 2 ? ARM::tSTRHi
7049                                      : StSize == 1 ? ARM::tSTRBi : 0;
7050   if (IsThumb2)
7051     return StSize == 4 ? ARM::t2STR_POST
7052                        : StSize == 2 ? ARM::t2STRH_POST
7053                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7054   return StSize == 4 ? ARM::STR_POST_IMM
7055                      : StSize == 2 ? ARM::STRH_POST
7056                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7057 }
7058
7059 /// Emit a post-increment load operation with given size. The instructions
7060 /// will be added to BB at Pos.
7061 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7062                        const TargetInstrInfo *TII, DebugLoc dl,
7063                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7064                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7065   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7066   assert(LdOpc != 0 && "Should have a load opcode");
7067   if (LdSize >= 8) {
7068     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7069                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7070                        .addImm(0));
7071   } else if (IsThumb1) {
7072     // load + update AddrIn
7073     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7074                        .addReg(AddrIn).addImm(0));
7075     MachineInstrBuilder MIB =
7076         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7077     MIB = AddDefaultT1CC(MIB);
7078     MIB.addReg(AddrIn).addImm(LdSize);
7079     AddDefaultPred(MIB);
7080   } else if (IsThumb2) {
7081     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7082                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7083                        .addImm(LdSize));
7084   } else { // arm
7085     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7086                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7087                        .addReg(0).addImm(LdSize));
7088   }
7089 }
7090
7091 /// Emit a post-increment store operation with given size. The instructions
7092 /// will be added to BB at Pos.
7093 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7094                        const TargetInstrInfo *TII, DebugLoc dl,
7095                        unsigned StSize, unsigned Data, unsigned AddrIn,
7096                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7097   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7098   assert(StOpc != 0 && "Should have a store opcode");
7099   if (StSize >= 8) {
7100     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7101                        .addReg(AddrIn).addImm(0).addReg(Data));
7102   } else if (IsThumb1) {
7103     // store + update AddrIn
7104     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7105                        .addReg(AddrIn).addImm(0));
7106     MachineInstrBuilder MIB =
7107         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7108     MIB = AddDefaultT1CC(MIB);
7109     MIB.addReg(AddrIn).addImm(StSize);
7110     AddDefaultPred(MIB);
7111   } else if (IsThumb2) {
7112     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7113                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7114   } else { // arm
7115     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7116                        .addReg(Data).addReg(AddrIn).addReg(0)
7117                        .addImm(StSize));
7118   }
7119 }
7120
7121 MachineBasicBlock *
7122 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7123                                    MachineBasicBlock *BB) const {
7124   // This pseudo instruction has 3 operands: dst, src, size
7125   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7126   // Otherwise, we will generate unrolled scalar copies.
7127   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7128   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7129   MachineFunction::iterator It = BB;
7130   ++It;
7131
7132   unsigned dest = MI->getOperand(0).getReg();
7133   unsigned src = MI->getOperand(1).getReg();
7134   unsigned SizeVal = MI->getOperand(2).getImm();
7135   unsigned Align = MI->getOperand(3).getImm();
7136   DebugLoc dl = MI->getDebugLoc();
7137
7138   MachineFunction *MF = BB->getParent();
7139   MachineRegisterInfo &MRI = MF->getRegInfo();
7140   unsigned UnitSize = 0;
7141   const TargetRegisterClass *TRC = nullptr;
7142   const TargetRegisterClass *VecTRC = nullptr;
7143
7144   bool IsThumb1 = Subtarget->isThumb1Only();
7145   bool IsThumb2 = Subtarget->isThumb2();
7146
7147   if (Align & 1) {
7148     UnitSize = 1;
7149   } else if (Align & 2) {
7150     UnitSize = 2;
7151   } else {
7152     // Check whether we can use NEON instructions.
7153     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7154         Subtarget->hasNEON()) {
7155       if ((Align % 16 == 0) && SizeVal >= 16)
7156         UnitSize = 16;
7157       else if ((Align % 8 == 0) && SizeVal >= 8)
7158         UnitSize = 8;
7159     }
7160     // Can't use NEON instructions.
7161     if (UnitSize == 0)
7162       UnitSize = 4;
7163   }
7164
7165   // Select the correct opcode and register class for unit size load/store
7166   bool IsNeon = UnitSize >= 8;
7167   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7168   if (IsNeon)
7169     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7170                             : UnitSize == 8 ? &ARM::DPRRegClass
7171                                             : nullptr;
7172
7173   unsigned BytesLeft = SizeVal % UnitSize;
7174   unsigned LoopSize = SizeVal - BytesLeft;
7175
7176   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7177     // Use LDR and STR to copy.
7178     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7179     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7180     unsigned srcIn = src;
7181     unsigned destIn = dest;
7182     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7183       unsigned srcOut = MRI.createVirtualRegister(TRC);
7184       unsigned destOut = MRI.createVirtualRegister(TRC);
7185       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7186       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7187                  IsThumb1, IsThumb2);
7188       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7189                  IsThumb1, IsThumb2);
7190       srcIn = srcOut;
7191       destIn = destOut;
7192     }
7193
7194     // Handle the leftover bytes with LDRB and STRB.
7195     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7196     // [destOut] = STRB_POST(scratch, destIn, 1)
7197     for (unsigned i = 0; i < BytesLeft; i++) {
7198       unsigned srcOut = MRI.createVirtualRegister(TRC);
7199       unsigned destOut = MRI.createVirtualRegister(TRC);
7200       unsigned scratch = MRI.createVirtualRegister(TRC);
7201       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7202                  IsThumb1, IsThumb2);
7203       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7204                  IsThumb1, IsThumb2);
7205       srcIn = srcOut;
7206       destIn = destOut;
7207     }
7208     MI->eraseFromParent();   // The instruction is gone now.
7209     return BB;
7210   }
7211
7212   // Expand the pseudo op to a loop.
7213   // thisMBB:
7214   //   ...
7215   //   movw varEnd, # --> with thumb2
7216   //   movt varEnd, #
7217   //   ldrcp varEnd, idx --> without thumb2
7218   //   fallthrough --> loopMBB
7219   // loopMBB:
7220   //   PHI varPhi, varEnd, varLoop
7221   //   PHI srcPhi, src, srcLoop
7222   //   PHI destPhi, dst, destLoop
7223   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7224   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7225   //   subs varLoop, varPhi, #UnitSize
7226   //   bne loopMBB
7227   //   fallthrough --> exitMBB
7228   // exitMBB:
7229   //   epilogue to handle left-over bytes
7230   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7231   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7232   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7233   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7234   MF->insert(It, loopMBB);
7235   MF->insert(It, exitMBB);
7236
7237   // Transfer the remainder of BB and its successor edges to exitMBB.
7238   exitMBB->splice(exitMBB->begin(), BB,
7239                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7240   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7241
7242   // Load an immediate to varEnd.
7243   unsigned varEnd = MRI.createVirtualRegister(TRC);
7244   if (Subtarget->useMovt(*MF)) {
7245     unsigned Vtmp = varEnd;
7246     if ((LoopSize & 0xFFFF0000) != 0)
7247       Vtmp = MRI.createVirtualRegister(TRC);
7248     AddDefaultPred(BuildMI(BB, dl,
7249                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7250                            Vtmp).addImm(LoopSize & 0xFFFF));
7251
7252     if ((LoopSize & 0xFFFF0000) != 0)
7253       AddDefaultPred(BuildMI(BB, dl,
7254                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7255                              varEnd)
7256                          .addReg(Vtmp)
7257                          .addImm(LoopSize >> 16));
7258   } else {
7259     MachineConstantPool *ConstantPool = MF->getConstantPool();
7260     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7261     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7262
7263     // MachineConstantPool wants an explicit alignment.
7264     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7265     if (Align == 0)
7266       Align = getDataLayout()->getTypeAllocSize(C->getType());
7267     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7268
7269     if (IsThumb1)
7270       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7271           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7272     else
7273       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7274           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7275   }
7276   BB->addSuccessor(loopMBB);
7277
7278   // Generate the loop body:
7279   //   varPhi = PHI(varLoop, varEnd)
7280   //   srcPhi = PHI(srcLoop, src)
7281   //   destPhi = PHI(destLoop, dst)
7282   MachineBasicBlock *entryBB = BB;
7283   BB = loopMBB;
7284   unsigned varLoop = MRI.createVirtualRegister(TRC);
7285   unsigned varPhi = MRI.createVirtualRegister(TRC);
7286   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7287   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7288   unsigned destLoop = MRI.createVirtualRegister(TRC);
7289   unsigned destPhi = MRI.createVirtualRegister(TRC);
7290
7291   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7292     .addReg(varLoop).addMBB(loopMBB)
7293     .addReg(varEnd).addMBB(entryBB);
7294   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7295     .addReg(srcLoop).addMBB(loopMBB)
7296     .addReg(src).addMBB(entryBB);
7297   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7298     .addReg(destLoop).addMBB(loopMBB)
7299     .addReg(dest).addMBB(entryBB);
7300
7301   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7302   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7303   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7304   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7305              IsThumb1, IsThumb2);
7306   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7307              IsThumb1, IsThumb2);
7308
7309   // Decrement loop variable by UnitSize.
7310   if (IsThumb1) {
7311     MachineInstrBuilder MIB =
7312         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7313     MIB = AddDefaultT1CC(MIB);
7314     MIB.addReg(varPhi).addImm(UnitSize);
7315     AddDefaultPred(MIB);
7316   } else {
7317     MachineInstrBuilder MIB =
7318         BuildMI(*BB, BB->end(), dl,
7319                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7320     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7321     MIB->getOperand(5).setReg(ARM::CPSR);
7322     MIB->getOperand(5).setIsDef(true);
7323   }
7324   BuildMI(*BB, BB->end(), dl,
7325           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7326       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7327
7328   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7329   BB->addSuccessor(loopMBB);
7330   BB->addSuccessor(exitMBB);
7331
7332   // Add epilogue to handle BytesLeft.
7333   BB = exitMBB;
7334   MachineInstr *StartOfExit = exitMBB->begin();
7335
7336   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7337   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7338   unsigned srcIn = srcLoop;
7339   unsigned destIn = destLoop;
7340   for (unsigned i = 0; i < BytesLeft; i++) {
7341     unsigned srcOut = MRI.createVirtualRegister(TRC);
7342     unsigned destOut = MRI.createVirtualRegister(TRC);
7343     unsigned scratch = MRI.createVirtualRegister(TRC);
7344     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7345                IsThumb1, IsThumb2);
7346     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7347                IsThumb1, IsThumb2);
7348     srcIn = srcOut;
7349     destIn = destOut;
7350   }
7351
7352   MI->eraseFromParent();   // The instruction is gone now.
7353   return BB;
7354 }
7355
7356 MachineBasicBlock *
7357 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7358                                        MachineBasicBlock *MBB) const {
7359   const TargetMachine &TM = getTargetMachine();
7360   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7361   DebugLoc DL = MI->getDebugLoc();
7362
7363   assert(Subtarget->isTargetWindows() &&
7364          "__chkstk is only supported on Windows");
7365   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7366
7367   // __chkstk takes the number of words to allocate on the stack in R4, and
7368   // returns the stack adjustment in number of bytes in R4.  This will not
7369   // clober any other registers (other than the obvious lr).
7370   //
7371   // Although, technically, IP should be considered a register which may be
7372   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7373   // thumb-2 environment, so there is no interworking required.  As a result, we
7374   // do not expect a veneer to be emitted by the linker, clobbering IP.
7375   //
7376   // Each module receives its own copy of __chkstk, so no import thunk is
7377   // required, again, ensuring that IP is not clobbered.
7378   //
7379   // Finally, although some linkers may theoretically provide a trampoline for
7380   // out of range calls (which is quite common due to a 32M range limitation of
7381   // branches for Thumb), we can generate the long-call version via
7382   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7383   // IP.
7384
7385   switch (TM.getCodeModel()) {
7386   case CodeModel::Small:
7387   case CodeModel::Medium:
7388   case CodeModel::Default:
7389   case CodeModel::Kernel:
7390     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7391       .addImm((unsigned)ARMCC::AL).addReg(0)
7392       .addExternalSymbol("__chkstk")
7393       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7394       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7395       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7396     break;
7397   case CodeModel::Large:
7398   case CodeModel::JITDefault: {
7399     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7400     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7401
7402     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7403       .addExternalSymbol("__chkstk");
7404     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7405       .addImm((unsigned)ARMCC::AL).addReg(0)
7406       .addReg(Reg, RegState::Kill)
7407       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7408       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7409       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7410     break;
7411   }
7412   }
7413
7414   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7415                                       ARM::SP)
7416                               .addReg(ARM::SP).addReg(ARM::R4)));
7417
7418   MI->eraseFromParent();
7419   return MBB;
7420 }
7421
7422 MachineBasicBlock *
7423 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7424                                                MachineBasicBlock *BB) const {
7425   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7426   DebugLoc dl = MI->getDebugLoc();
7427   bool isThumb2 = Subtarget->isThumb2();
7428   switch (MI->getOpcode()) {
7429   default: {
7430     MI->dump();
7431     llvm_unreachable("Unexpected instr type to insert");
7432   }
7433   // The Thumb2 pre-indexed stores have the same MI operands, they just
7434   // define them differently in the .td files from the isel patterns, so
7435   // they need pseudos.
7436   case ARM::t2STR_preidx:
7437     MI->setDesc(TII->get(ARM::t2STR_PRE));
7438     return BB;
7439   case ARM::t2STRB_preidx:
7440     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7441     return BB;
7442   case ARM::t2STRH_preidx:
7443     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7444     return BB;
7445
7446   case ARM::STRi_preidx:
7447   case ARM::STRBi_preidx: {
7448     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7449       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7450     // Decode the offset.
7451     unsigned Offset = MI->getOperand(4).getImm();
7452     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7453     Offset = ARM_AM::getAM2Offset(Offset);
7454     if (isSub)
7455       Offset = -Offset;
7456
7457     MachineMemOperand *MMO = *MI->memoperands_begin();
7458     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7459       .addOperand(MI->getOperand(0))  // Rn_wb
7460       .addOperand(MI->getOperand(1))  // Rt
7461       .addOperand(MI->getOperand(2))  // Rn
7462       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7463       .addOperand(MI->getOperand(5))  // pred
7464       .addOperand(MI->getOperand(6))
7465       .addMemOperand(MMO);
7466     MI->eraseFromParent();
7467     return BB;
7468   }
7469   case ARM::STRr_preidx:
7470   case ARM::STRBr_preidx:
7471   case ARM::STRH_preidx: {
7472     unsigned NewOpc;
7473     switch (MI->getOpcode()) {
7474     default: llvm_unreachable("unexpected opcode!");
7475     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7476     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7477     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7478     }
7479     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7480     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7481       MIB.addOperand(MI->getOperand(i));
7482     MI->eraseFromParent();
7483     return BB;
7484   }
7485
7486   case ARM::tMOVCCr_pseudo: {
7487     // To "insert" a SELECT_CC instruction, we actually have to insert the
7488     // diamond control-flow pattern.  The incoming instruction knows the
7489     // destination vreg to set, the condition code register to branch on, the
7490     // true/false values to select between, and a branch opcode to use.
7491     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7492     MachineFunction::iterator It = BB;
7493     ++It;
7494
7495     //  thisMBB:
7496     //  ...
7497     //   TrueVal = ...
7498     //   cmpTY ccX, r1, r2
7499     //   bCC copy1MBB
7500     //   fallthrough --> copy0MBB
7501     MachineBasicBlock *thisMBB  = BB;
7502     MachineFunction *F = BB->getParent();
7503     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7504     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7505     F->insert(It, copy0MBB);
7506     F->insert(It, sinkMBB);
7507
7508     // Transfer the remainder of BB and its successor edges to sinkMBB.
7509     sinkMBB->splice(sinkMBB->begin(), BB,
7510                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7511     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7512
7513     BB->addSuccessor(copy0MBB);
7514     BB->addSuccessor(sinkMBB);
7515
7516     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7517       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7518
7519     //  copy0MBB:
7520     //   %FalseValue = ...
7521     //   # fallthrough to sinkMBB
7522     BB = copy0MBB;
7523
7524     // Update machine-CFG edges
7525     BB->addSuccessor(sinkMBB);
7526
7527     //  sinkMBB:
7528     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7529     //  ...
7530     BB = sinkMBB;
7531     BuildMI(*BB, BB->begin(), dl,
7532             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7533       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7534       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7535
7536     MI->eraseFromParent();   // The pseudo instruction is gone now.
7537     return BB;
7538   }
7539
7540   case ARM::BCCi64:
7541   case ARM::BCCZi64: {
7542     // If there is an unconditional branch to the other successor, remove it.
7543     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7544
7545     // Compare both parts that make up the double comparison separately for
7546     // equality.
7547     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7548
7549     unsigned LHS1 = MI->getOperand(1).getReg();
7550     unsigned LHS2 = MI->getOperand(2).getReg();
7551     if (RHSisZero) {
7552       AddDefaultPred(BuildMI(BB, dl,
7553                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7554                      .addReg(LHS1).addImm(0));
7555       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7556         .addReg(LHS2).addImm(0)
7557         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7558     } else {
7559       unsigned RHS1 = MI->getOperand(3).getReg();
7560       unsigned RHS2 = MI->getOperand(4).getReg();
7561       AddDefaultPred(BuildMI(BB, dl,
7562                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7563                      .addReg(LHS1).addReg(RHS1));
7564       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7565         .addReg(LHS2).addReg(RHS2)
7566         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7567     }
7568
7569     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7570     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7571     if (MI->getOperand(0).getImm() == ARMCC::NE)
7572       std::swap(destMBB, exitMBB);
7573
7574     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7575       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7576     if (isThumb2)
7577       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7578     else
7579       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7580
7581     MI->eraseFromParent();   // The pseudo instruction is gone now.
7582     return BB;
7583   }
7584
7585   case ARM::Int_eh_sjlj_setjmp:
7586   case ARM::Int_eh_sjlj_setjmp_nofp:
7587   case ARM::tInt_eh_sjlj_setjmp:
7588   case ARM::t2Int_eh_sjlj_setjmp:
7589   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7590     EmitSjLjDispatchBlock(MI, BB);
7591     return BB;
7592
7593   case ARM::ABS:
7594   case ARM::t2ABS: {
7595     // To insert an ABS instruction, we have to insert the
7596     // diamond control-flow pattern.  The incoming instruction knows the
7597     // source vreg to test against 0, the destination vreg to set,
7598     // the condition code register to branch on, the
7599     // true/false values to select between, and a branch opcode to use.
7600     // It transforms
7601     //     V1 = ABS V0
7602     // into
7603     //     V2 = MOVS V0
7604     //     BCC                      (branch to SinkBB if V0 >= 0)
7605     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7606     //     SinkBB: V1 = PHI(V2, V3)
7607     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7608     MachineFunction::iterator BBI = BB;
7609     ++BBI;
7610     MachineFunction *Fn = BB->getParent();
7611     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7612     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7613     Fn->insert(BBI, RSBBB);
7614     Fn->insert(BBI, SinkBB);
7615
7616     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7617     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7618     bool ABSSrcKIll = MI->getOperand(1).isKill();
7619     bool isThumb2 = Subtarget->isThumb2();
7620     MachineRegisterInfo &MRI = Fn->getRegInfo();
7621     // In Thumb mode S must not be specified if source register is the SP or
7622     // PC and if destination register is the SP, so restrict register class
7623     unsigned NewRsbDstReg =
7624       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7625
7626     // Transfer the remainder of BB and its successor edges to sinkMBB.
7627     SinkBB->splice(SinkBB->begin(), BB,
7628                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7629     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7630
7631     BB->addSuccessor(RSBBB);
7632     BB->addSuccessor(SinkBB);
7633
7634     // fall through to SinkMBB
7635     RSBBB->addSuccessor(SinkBB);
7636
7637     // insert a cmp at the end of BB
7638     AddDefaultPred(BuildMI(BB, dl,
7639                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7640                    .addReg(ABSSrcReg).addImm(0));
7641
7642     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7643     BuildMI(BB, dl,
7644       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7645       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7646
7647     // insert rsbri in RSBBB
7648     // Note: BCC and rsbri will be converted into predicated rsbmi
7649     // by if-conversion pass
7650     BuildMI(*RSBBB, RSBBB->begin(), dl,
7651       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7652       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7653       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7654
7655     // insert PHI in SinkBB,
7656     // reuse ABSDstReg to not change uses of ABS instruction
7657     BuildMI(*SinkBB, SinkBB->begin(), dl,
7658       TII->get(ARM::PHI), ABSDstReg)
7659       .addReg(NewRsbDstReg).addMBB(RSBBB)
7660       .addReg(ABSSrcReg).addMBB(BB);
7661
7662     // remove ABS instruction
7663     MI->eraseFromParent();
7664
7665     // return last added BB
7666     return SinkBB;
7667   }
7668   case ARM::COPY_STRUCT_BYVAL_I32:
7669     ++NumLoopByVals;
7670     return EmitStructByval(MI, BB);
7671   case ARM::WIN__CHKSTK:
7672     return EmitLowered__chkstk(MI, BB);
7673   }
7674 }
7675
7676 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7677                                                       SDNode *Node) const {
7678   const MCInstrDesc *MCID = &MI->getDesc();
7679   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7680   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7681   // operand is still set to noreg. If needed, set the optional operand's
7682   // register to CPSR, and remove the redundant implicit def.
7683   //
7684   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7685
7686   // Rename pseudo opcodes.
7687   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7688   if (NewOpc) {
7689     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7690     MCID = &TII->get(NewOpc);
7691
7692     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7693            "converted opcode should be the same except for cc_out");
7694
7695     MI->setDesc(*MCID);
7696
7697     // Add the optional cc_out operand
7698     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7699   }
7700   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7701
7702   // Any ARM instruction that sets the 's' bit should specify an optional
7703   // "cc_out" operand in the last operand position.
7704   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7705     assert(!NewOpc && "Optional cc_out operand required");
7706     return;
7707   }
7708   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7709   // since we already have an optional CPSR def.
7710   bool definesCPSR = false;
7711   bool deadCPSR = false;
7712   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7713        i != e; ++i) {
7714     const MachineOperand &MO = MI->getOperand(i);
7715     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7716       definesCPSR = true;
7717       if (MO.isDead())
7718         deadCPSR = true;
7719       MI->RemoveOperand(i);
7720       break;
7721     }
7722   }
7723   if (!definesCPSR) {
7724     assert(!NewOpc && "Optional cc_out operand required");
7725     return;
7726   }
7727   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7728   if (deadCPSR) {
7729     assert(!MI->getOperand(ccOutIdx).getReg() &&
7730            "expect uninitialized optional cc_out operand");
7731     return;
7732   }
7733
7734   // If this instruction was defined with an optional CPSR def and its dag node
7735   // had a live implicit CPSR def, then activate the optional CPSR def.
7736   MachineOperand &MO = MI->getOperand(ccOutIdx);
7737   MO.setReg(ARM::CPSR);
7738   MO.setIsDef(true);
7739 }
7740
7741 //===----------------------------------------------------------------------===//
7742 //                           ARM Optimization Hooks
7743 //===----------------------------------------------------------------------===//
7744
7745 // Helper function that checks if N is a null or all ones constant.
7746 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7747   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7748   if (!C)
7749     return false;
7750   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7751 }
7752
7753 // Return true if N is conditionally 0 or all ones.
7754 // Detects these expressions where cc is an i1 value:
7755 //
7756 //   (select cc 0, y)   [AllOnes=0]
7757 //   (select cc y, 0)   [AllOnes=0]
7758 //   (zext cc)          [AllOnes=0]
7759 //   (sext cc)          [AllOnes=0/1]
7760 //   (select cc -1, y)  [AllOnes=1]
7761 //   (select cc y, -1)  [AllOnes=1]
7762 //
7763 // Invert is set when N is the null/all ones constant when CC is false.
7764 // OtherOp is set to the alternative value of N.
7765 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7766                                        SDValue &CC, bool &Invert,
7767                                        SDValue &OtherOp,
7768                                        SelectionDAG &DAG) {
7769   switch (N->getOpcode()) {
7770   default: return false;
7771   case ISD::SELECT: {
7772     CC = N->getOperand(0);
7773     SDValue N1 = N->getOperand(1);
7774     SDValue N2 = N->getOperand(2);
7775     if (isZeroOrAllOnes(N1, AllOnes)) {
7776       Invert = false;
7777       OtherOp = N2;
7778       return true;
7779     }
7780     if (isZeroOrAllOnes(N2, AllOnes)) {
7781       Invert = true;
7782       OtherOp = N1;
7783       return true;
7784     }
7785     return false;
7786   }
7787   case ISD::ZERO_EXTEND:
7788     // (zext cc) can never be the all ones value.
7789     if (AllOnes)
7790       return false;
7791     // Fall through.
7792   case ISD::SIGN_EXTEND: {
7793     SDLoc dl(N);
7794     EVT VT = N->getValueType(0);
7795     CC = N->getOperand(0);
7796     if (CC.getValueType() != MVT::i1)
7797       return false;
7798     Invert = !AllOnes;
7799     if (AllOnes)
7800       // When looking for an AllOnes constant, N is an sext, and the 'other'
7801       // value is 0.
7802       OtherOp = DAG.getConstant(0, dl, VT);
7803     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7804       // When looking for a 0 constant, N can be zext or sext.
7805       OtherOp = DAG.getConstant(1, dl, VT);
7806     else
7807       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
7808                                 VT);
7809     return true;
7810   }
7811   }
7812 }
7813
7814 // Combine a constant select operand into its use:
7815 //
7816 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7817 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7818 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7819 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7820 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7821 //
7822 // The transform is rejected if the select doesn't have a constant operand that
7823 // is null, or all ones when AllOnes is set.
7824 //
7825 // Also recognize sext/zext from i1:
7826 //
7827 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7828 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7829 //
7830 // These transformations eventually create predicated instructions.
7831 //
7832 // @param N       The node to transform.
7833 // @param Slct    The N operand that is a select.
7834 // @param OtherOp The other N operand (x above).
7835 // @param DCI     Context.
7836 // @param AllOnes Require the select constant to be all ones instead of null.
7837 // @returns The new node, or SDValue() on failure.
7838 static
7839 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7840                             TargetLowering::DAGCombinerInfo &DCI,
7841                             bool AllOnes = false) {
7842   SelectionDAG &DAG = DCI.DAG;
7843   EVT VT = N->getValueType(0);
7844   SDValue NonConstantVal;
7845   SDValue CCOp;
7846   bool SwapSelectOps;
7847   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7848                                   NonConstantVal, DAG))
7849     return SDValue();
7850
7851   // Slct is now know to be the desired identity constant when CC is true.
7852   SDValue TrueVal = OtherOp;
7853   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7854                                  OtherOp, NonConstantVal);
7855   // Unless SwapSelectOps says CC should be false.
7856   if (SwapSelectOps)
7857     std::swap(TrueVal, FalseVal);
7858
7859   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7860                      CCOp, TrueVal, FalseVal);
7861 }
7862
7863 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7864 static
7865 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7866                                        TargetLowering::DAGCombinerInfo &DCI) {
7867   SDValue N0 = N->getOperand(0);
7868   SDValue N1 = N->getOperand(1);
7869   if (N0.getNode()->hasOneUse()) {
7870     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7871     if (Result.getNode())
7872       return Result;
7873   }
7874   if (N1.getNode()->hasOneUse()) {
7875     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7876     if (Result.getNode())
7877       return Result;
7878   }
7879   return SDValue();
7880 }
7881
7882 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7883 // (only after legalization).
7884 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7885                                  TargetLowering::DAGCombinerInfo &DCI,
7886                                  const ARMSubtarget *Subtarget) {
7887
7888   // Only perform optimization if after legalize, and if NEON is available. We
7889   // also expected both operands to be BUILD_VECTORs.
7890   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7891       || N0.getOpcode() != ISD::BUILD_VECTOR
7892       || N1.getOpcode() != ISD::BUILD_VECTOR)
7893     return SDValue();
7894
7895   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7896   EVT VT = N->getValueType(0);
7897   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7898     return SDValue();
7899
7900   // Check that the vector operands are of the right form.
7901   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7902   // operands, where N is the size of the formed vector.
7903   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7904   // index such that we have a pair wise add pattern.
7905
7906   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7907   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7908     return SDValue();
7909   SDValue Vec = N0->getOperand(0)->getOperand(0);
7910   SDNode *V = Vec.getNode();
7911   unsigned nextIndex = 0;
7912
7913   // For each operands to the ADD which are BUILD_VECTORs,
7914   // check to see if each of their operands are an EXTRACT_VECTOR with
7915   // the same vector and appropriate index.
7916   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7917     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7918         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7919
7920       SDValue ExtVec0 = N0->getOperand(i);
7921       SDValue ExtVec1 = N1->getOperand(i);
7922
7923       // First operand is the vector, verify its the same.
7924       if (V != ExtVec0->getOperand(0).getNode() ||
7925           V != ExtVec1->getOperand(0).getNode())
7926         return SDValue();
7927
7928       // Second is the constant, verify its correct.
7929       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7930       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7931
7932       // For the constant, we want to see all the even or all the odd.
7933       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7934           || C1->getZExtValue() != nextIndex+1)
7935         return SDValue();
7936
7937       // Increment index.
7938       nextIndex+=2;
7939     } else
7940       return SDValue();
7941   }
7942
7943   // Create VPADDL node.
7944   SelectionDAG &DAG = DCI.DAG;
7945   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7946
7947   SDLoc dl(N);
7948
7949   // Build operand list.
7950   SmallVector<SDValue, 8> Ops;
7951   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
7952                                 TLI.getPointerTy()));
7953
7954   // Input is the vector.
7955   Ops.push_back(Vec);
7956
7957   // Get widened type and narrowed type.
7958   MVT widenType;
7959   unsigned numElem = VT.getVectorNumElements();
7960
7961   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7962   switch (inputLaneType.getSimpleVT().SimpleTy) {
7963     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7964     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7965     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7966     default:
7967       llvm_unreachable("Invalid vector element type for padd optimization.");
7968   }
7969
7970   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
7971   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7972   return DAG.getNode(ExtOp, dl, VT, tmp);
7973 }
7974
7975 static SDValue findMUL_LOHI(SDValue V) {
7976   if (V->getOpcode() == ISD::UMUL_LOHI ||
7977       V->getOpcode() == ISD::SMUL_LOHI)
7978     return V;
7979   return SDValue();
7980 }
7981
7982 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7983                                      TargetLowering::DAGCombinerInfo &DCI,
7984                                      const ARMSubtarget *Subtarget) {
7985
7986   if (Subtarget->isThumb1Only()) return SDValue();
7987
7988   // Only perform the checks after legalize when the pattern is available.
7989   if (DCI.isBeforeLegalize()) return SDValue();
7990
7991   // Look for multiply add opportunities.
7992   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7993   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7994   // a glue link from the first add to the second add.
7995   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7996   // a S/UMLAL instruction.
7997   //          loAdd   UMUL_LOHI
7998   //            \    / :lo    \ :hi
7999   //             \  /          \          [no multiline comment]
8000   //              ADDC         |  hiAdd
8001   //                 \ :glue  /  /
8002   //                  \      /  /
8003   //                    ADDE
8004   //
8005   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8006   SDValue AddcOp0 = AddcNode->getOperand(0);
8007   SDValue AddcOp1 = AddcNode->getOperand(1);
8008
8009   // Check if the two operands are from the same mul_lohi node.
8010   if (AddcOp0.getNode() == AddcOp1.getNode())
8011     return SDValue();
8012
8013   assert(AddcNode->getNumValues() == 2 &&
8014          AddcNode->getValueType(0) == MVT::i32 &&
8015          "Expect ADDC with two result values. First: i32");
8016
8017   // Check that we have a glued ADDC node.
8018   if (AddcNode->getValueType(1) != MVT::Glue)
8019     return SDValue();
8020
8021   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8022   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8023       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8024       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8025       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8026     return SDValue();
8027
8028   // Look for the glued ADDE.
8029   SDNode* AddeNode = AddcNode->getGluedUser();
8030   if (!AddeNode)
8031     return SDValue();
8032
8033   // Make sure it is really an ADDE.
8034   if (AddeNode->getOpcode() != ISD::ADDE)
8035     return SDValue();
8036
8037   assert(AddeNode->getNumOperands() == 3 &&
8038          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8039          "ADDE node has the wrong inputs");
8040
8041   // Check for the triangle shape.
8042   SDValue AddeOp0 = AddeNode->getOperand(0);
8043   SDValue AddeOp1 = AddeNode->getOperand(1);
8044
8045   // Make sure that the ADDE operands are not coming from the same node.
8046   if (AddeOp0.getNode() == AddeOp1.getNode())
8047     return SDValue();
8048
8049   // Find the MUL_LOHI node walking up ADDE's operands.
8050   bool IsLeftOperandMUL = false;
8051   SDValue MULOp = findMUL_LOHI(AddeOp0);
8052   if (MULOp == SDValue())
8053    MULOp = findMUL_LOHI(AddeOp1);
8054   else
8055     IsLeftOperandMUL = true;
8056   if (MULOp == SDValue())
8057     return SDValue();
8058
8059   // Figure out the right opcode.
8060   unsigned Opc = MULOp->getOpcode();
8061   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8062
8063   // Figure out the high and low input values to the MLAL node.
8064   SDValue* HiAdd = nullptr;
8065   SDValue* LoMul = nullptr;
8066   SDValue* LowAdd = nullptr;
8067
8068   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8069   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8070     return SDValue();
8071
8072   if (IsLeftOperandMUL)
8073     HiAdd = &AddeOp1;
8074   else
8075     HiAdd = &AddeOp0;
8076
8077
8078   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8079   // whose low result is fed to the ADDC we are checking.
8080
8081   if (AddcOp0 == MULOp.getValue(0)) {
8082     LoMul = &AddcOp0;
8083     LowAdd = &AddcOp1;
8084   }
8085   if (AddcOp1 == MULOp.getValue(0)) {
8086     LoMul = &AddcOp1;
8087     LowAdd = &AddcOp0;
8088   }
8089
8090   if (!LoMul)
8091     return SDValue();
8092
8093   // Create the merged node.
8094   SelectionDAG &DAG = DCI.DAG;
8095
8096   // Build operand list.
8097   SmallVector<SDValue, 8> Ops;
8098   Ops.push_back(LoMul->getOperand(0));
8099   Ops.push_back(LoMul->getOperand(1));
8100   Ops.push_back(*LowAdd);
8101   Ops.push_back(*HiAdd);
8102
8103   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8104                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8105
8106   // Replace the ADDs' nodes uses by the MLA node's values.
8107   SDValue HiMLALResult(MLALNode.getNode(), 1);
8108   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8109
8110   SDValue LoMLALResult(MLALNode.getNode(), 0);
8111   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8112
8113   // Return original node to notify the driver to stop replacing.
8114   SDValue resNode(AddcNode, 0);
8115   return resNode;
8116 }
8117
8118 /// PerformADDCCombine - Target-specific dag combine transform from
8119 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8120 static SDValue PerformADDCCombine(SDNode *N,
8121                                  TargetLowering::DAGCombinerInfo &DCI,
8122                                  const ARMSubtarget *Subtarget) {
8123
8124   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8125
8126 }
8127
8128 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8129 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8130 /// called with the default operands, and if that fails, with commuted
8131 /// operands.
8132 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8133                                           TargetLowering::DAGCombinerInfo &DCI,
8134                                           const ARMSubtarget *Subtarget){
8135
8136   // Attempt to create vpaddl for this add.
8137   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8138   if (Result.getNode())
8139     return Result;
8140
8141   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8142   if (N0.getNode()->hasOneUse()) {
8143     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8144     if (Result.getNode()) return Result;
8145   }
8146   return SDValue();
8147 }
8148
8149 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8150 ///
8151 static SDValue PerformADDCombine(SDNode *N,
8152                                  TargetLowering::DAGCombinerInfo &DCI,
8153                                  const ARMSubtarget *Subtarget) {
8154   SDValue N0 = N->getOperand(0);
8155   SDValue N1 = N->getOperand(1);
8156
8157   // First try with the default operand order.
8158   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8159   if (Result.getNode())
8160     return Result;
8161
8162   // If that didn't work, try again with the operands commuted.
8163   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8164 }
8165
8166 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8167 ///
8168 static SDValue PerformSUBCombine(SDNode *N,
8169                                  TargetLowering::DAGCombinerInfo &DCI) {
8170   SDValue N0 = N->getOperand(0);
8171   SDValue N1 = N->getOperand(1);
8172
8173   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8174   if (N1.getNode()->hasOneUse()) {
8175     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8176     if (Result.getNode()) return Result;
8177   }
8178
8179   return SDValue();
8180 }
8181
8182 /// PerformVMULCombine
8183 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8184 /// special multiplier accumulator forwarding.
8185 ///   vmul d3, d0, d2
8186 ///   vmla d3, d1, d2
8187 /// is faster than
8188 ///   vadd d3, d0, d1
8189 ///   vmul d3, d3, d2
8190 //  However, for (A + B) * (A + B),
8191 //    vadd d2, d0, d1
8192 //    vmul d3, d0, d2
8193 //    vmla d3, d1, d2
8194 //  is slower than
8195 //    vadd d2, d0, d1
8196 //    vmul d3, d2, d2
8197 static SDValue PerformVMULCombine(SDNode *N,
8198                                   TargetLowering::DAGCombinerInfo &DCI,
8199                                   const ARMSubtarget *Subtarget) {
8200   if (!Subtarget->hasVMLxForwarding())
8201     return SDValue();
8202
8203   SelectionDAG &DAG = DCI.DAG;
8204   SDValue N0 = N->getOperand(0);
8205   SDValue N1 = N->getOperand(1);
8206   unsigned Opcode = N0.getOpcode();
8207   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8208       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8209     Opcode = N1.getOpcode();
8210     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8211         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8212       return SDValue();
8213     std::swap(N0, N1);
8214   }
8215
8216   if (N0 == N1)
8217     return SDValue();
8218
8219   EVT VT = N->getValueType(0);
8220   SDLoc DL(N);
8221   SDValue N00 = N0->getOperand(0);
8222   SDValue N01 = N0->getOperand(1);
8223   return DAG.getNode(Opcode, DL, VT,
8224                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8225                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8226 }
8227
8228 static SDValue PerformMULCombine(SDNode *N,
8229                                  TargetLowering::DAGCombinerInfo &DCI,
8230                                  const ARMSubtarget *Subtarget) {
8231   SelectionDAG &DAG = DCI.DAG;
8232
8233   if (Subtarget->isThumb1Only())
8234     return SDValue();
8235
8236   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8237     return SDValue();
8238
8239   EVT VT = N->getValueType(0);
8240   if (VT.is64BitVector() || VT.is128BitVector())
8241     return PerformVMULCombine(N, DCI, Subtarget);
8242   if (VT != MVT::i32)
8243     return SDValue();
8244
8245   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8246   if (!C)
8247     return SDValue();
8248
8249   int64_t MulAmt = C->getSExtValue();
8250   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8251
8252   ShiftAmt = ShiftAmt & (32 - 1);
8253   SDValue V = N->getOperand(0);
8254   SDLoc DL(N);
8255
8256   SDValue Res;
8257   MulAmt >>= ShiftAmt;
8258
8259   if (MulAmt >= 0) {
8260     if (isPowerOf2_32(MulAmt - 1)) {
8261       // (mul x, 2^N + 1) => (add (shl x, N), x)
8262       Res = DAG.getNode(ISD::ADD, DL, VT,
8263                         V,
8264                         DAG.getNode(ISD::SHL, DL, VT,
8265                                     V,
8266                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8267                                                     MVT::i32)));
8268     } else if (isPowerOf2_32(MulAmt + 1)) {
8269       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8270       Res = DAG.getNode(ISD::SUB, DL, VT,
8271                         DAG.getNode(ISD::SHL, DL, VT,
8272                                     V,
8273                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8274                                                     MVT::i32)),
8275                         V);
8276     } else
8277       return SDValue();
8278   } else {
8279     uint64_t MulAmtAbs = -MulAmt;
8280     if (isPowerOf2_32(MulAmtAbs + 1)) {
8281       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8282       Res = DAG.getNode(ISD::SUB, DL, VT,
8283                         V,
8284                         DAG.getNode(ISD::SHL, DL, VT,
8285                                     V,
8286                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8287                                                     MVT::i32)));
8288     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8289       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8290       Res = DAG.getNode(ISD::ADD, DL, VT,
8291                         V,
8292                         DAG.getNode(ISD::SHL, DL, VT,
8293                                     V,
8294                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8295                                                     MVT::i32)));
8296       Res = DAG.getNode(ISD::SUB, DL, VT,
8297                         DAG.getConstant(0, DL, MVT::i32), Res);
8298
8299     } else
8300       return SDValue();
8301   }
8302
8303   if (ShiftAmt != 0)
8304     Res = DAG.getNode(ISD::SHL, DL, VT,
8305                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8306
8307   // Do not add new nodes to DAG combiner worklist.
8308   DCI.CombineTo(N, Res, false);
8309   return SDValue();
8310 }
8311
8312 static SDValue PerformANDCombine(SDNode *N,
8313                                  TargetLowering::DAGCombinerInfo &DCI,
8314                                  const ARMSubtarget *Subtarget) {
8315
8316   // Attempt to use immediate-form VBIC
8317   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8318   SDLoc dl(N);
8319   EVT VT = N->getValueType(0);
8320   SelectionDAG &DAG = DCI.DAG;
8321
8322   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8323     return SDValue();
8324
8325   APInt SplatBits, SplatUndef;
8326   unsigned SplatBitSize;
8327   bool HasAnyUndefs;
8328   if (BVN &&
8329       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8330     if (SplatBitSize <= 64) {
8331       EVT VbicVT;
8332       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8333                                       SplatUndef.getZExtValue(), SplatBitSize,
8334                                       DAG, dl, VbicVT, VT.is128BitVector(),
8335                                       OtherModImm);
8336       if (Val.getNode()) {
8337         SDValue Input =
8338           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8339         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8340         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8341       }
8342     }
8343   }
8344
8345   if (!Subtarget->isThumb1Only()) {
8346     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8347     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8348     if (Result.getNode())
8349       return Result;
8350   }
8351
8352   return SDValue();
8353 }
8354
8355 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8356 static SDValue PerformORCombine(SDNode *N,
8357                                 TargetLowering::DAGCombinerInfo &DCI,
8358                                 const ARMSubtarget *Subtarget) {
8359   // Attempt to use immediate-form VORR
8360   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8361   SDLoc dl(N);
8362   EVT VT = N->getValueType(0);
8363   SelectionDAG &DAG = DCI.DAG;
8364
8365   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8366     return SDValue();
8367
8368   APInt SplatBits, SplatUndef;
8369   unsigned SplatBitSize;
8370   bool HasAnyUndefs;
8371   if (BVN && Subtarget->hasNEON() &&
8372       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8373     if (SplatBitSize <= 64) {
8374       EVT VorrVT;
8375       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8376                                       SplatUndef.getZExtValue(), SplatBitSize,
8377                                       DAG, dl, VorrVT, VT.is128BitVector(),
8378                                       OtherModImm);
8379       if (Val.getNode()) {
8380         SDValue Input =
8381           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8382         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8383         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8384       }
8385     }
8386   }
8387
8388   if (!Subtarget->isThumb1Only()) {
8389     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8390     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8391     if (Result.getNode())
8392       return Result;
8393   }
8394
8395   // The code below optimizes (or (and X, Y), Z).
8396   // The AND operand needs to have a single user to make these optimizations
8397   // profitable.
8398   SDValue N0 = N->getOperand(0);
8399   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8400     return SDValue();
8401   SDValue N1 = N->getOperand(1);
8402
8403   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8404   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8405       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8406     APInt SplatUndef;
8407     unsigned SplatBitSize;
8408     bool HasAnyUndefs;
8409
8410     APInt SplatBits0, SplatBits1;
8411     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8412     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8413     // Ensure that the second operand of both ands are constants
8414     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8415                                       HasAnyUndefs) && !HasAnyUndefs) {
8416         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8417                                           HasAnyUndefs) && !HasAnyUndefs) {
8418             // Ensure that the bit width of the constants are the same and that
8419             // the splat arguments are logical inverses as per the pattern we
8420             // are trying to simplify.
8421             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8422                 SplatBits0 == ~SplatBits1) {
8423                 // Canonicalize the vector type to make instruction selection
8424                 // simpler.
8425                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8426                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8427                                              N0->getOperand(1),
8428                                              N0->getOperand(0),
8429                                              N1->getOperand(0));
8430                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8431             }
8432         }
8433     }
8434   }
8435
8436   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8437   // reasonable.
8438
8439   // BFI is only available on V6T2+
8440   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8441     return SDValue();
8442
8443   SDLoc DL(N);
8444   // 1) or (and A, mask), val => ARMbfi A, val, mask
8445   //      iff (val & mask) == val
8446   //
8447   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8448   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8449   //          && mask == ~mask2
8450   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8451   //          && ~mask == mask2
8452   //  (i.e., copy a bitfield value into another bitfield of the same width)
8453
8454   if (VT != MVT::i32)
8455     return SDValue();
8456
8457   SDValue N00 = N0.getOperand(0);
8458
8459   // The value and the mask need to be constants so we can verify this is
8460   // actually a bitfield set. If the mask is 0xffff, we can do better
8461   // via a movt instruction, so don't use BFI in that case.
8462   SDValue MaskOp = N0.getOperand(1);
8463   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8464   if (!MaskC)
8465     return SDValue();
8466   unsigned Mask = MaskC->getZExtValue();
8467   if (Mask == 0xffff)
8468     return SDValue();
8469   SDValue Res;
8470   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8471   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8472   if (N1C) {
8473     unsigned Val = N1C->getZExtValue();
8474     if ((Val & ~Mask) != Val)
8475       return SDValue();
8476
8477     if (ARM::isBitFieldInvertedMask(Mask)) {
8478       Val >>= countTrailingZeros(~Mask);
8479
8480       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8481                         DAG.getConstant(Val, DL, MVT::i32),
8482                         DAG.getConstant(Mask, DL, MVT::i32));
8483
8484       // Do not add new nodes to DAG combiner worklist.
8485       DCI.CombineTo(N, Res, false);
8486       return SDValue();
8487     }
8488   } else if (N1.getOpcode() == ISD::AND) {
8489     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8490     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8491     if (!N11C)
8492       return SDValue();
8493     unsigned Mask2 = N11C->getZExtValue();
8494
8495     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8496     // as is to match.
8497     if (ARM::isBitFieldInvertedMask(Mask) &&
8498         (Mask == ~Mask2)) {
8499       // The pack halfword instruction works better for masks that fit it,
8500       // so use that when it's available.
8501       if (Subtarget->hasT2ExtractPack() &&
8502           (Mask == 0xffff || Mask == 0xffff0000))
8503         return SDValue();
8504       // 2a
8505       unsigned amt = countTrailingZeros(Mask2);
8506       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8507                         DAG.getConstant(amt, DL, MVT::i32));
8508       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8509                         DAG.getConstant(Mask, DL, MVT::i32));
8510       // Do not add new nodes to DAG combiner worklist.
8511       DCI.CombineTo(N, Res, false);
8512       return SDValue();
8513     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8514                (~Mask == Mask2)) {
8515       // The pack halfword instruction works better for masks that fit it,
8516       // so use that when it's available.
8517       if (Subtarget->hasT2ExtractPack() &&
8518           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8519         return SDValue();
8520       // 2b
8521       unsigned lsb = countTrailingZeros(Mask);
8522       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8523                         DAG.getConstant(lsb, DL, MVT::i32));
8524       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8525                         DAG.getConstant(Mask2, DL, MVT::i32));
8526       // Do not add new nodes to DAG combiner worklist.
8527       DCI.CombineTo(N, Res, false);
8528       return SDValue();
8529     }
8530   }
8531
8532   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8533       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8534       ARM::isBitFieldInvertedMask(~Mask)) {
8535     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8536     // where lsb(mask) == #shamt and masked bits of B are known zero.
8537     SDValue ShAmt = N00.getOperand(1);
8538     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8539     unsigned LSB = countTrailingZeros(Mask);
8540     if (ShAmtC != LSB)
8541       return SDValue();
8542
8543     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8544                       DAG.getConstant(~Mask, DL, MVT::i32));
8545
8546     // Do not add new nodes to DAG combiner worklist.
8547     DCI.CombineTo(N, Res, false);
8548   }
8549
8550   return SDValue();
8551 }
8552
8553 static SDValue PerformXORCombine(SDNode *N,
8554                                  TargetLowering::DAGCombinerInfo &DCI,
8555                                  const ARMSubtarget *Subtarget) {
8556   EVT VT = N->getValueType(0);
8557   SelectionDAG &DAG = DCI.DAG;
8558
8559   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8560     return SDValue();
8561
8562   if (!Subtarget->isThumb1Only()) {
8563     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8564     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8565     if (Result.getNode())
8566       return Result;
8567   }
8568
8569   return SDValue();
8570 }
8571
8572 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8573 /// the bits being cleared by the AND are not demanded by the BFI.
8574 static SDValue PerformBFICombine(SDNode *N,
8575                                  TargetLowering::DAGCombinerInfo &DCI) {
8576   SDValue N1 = N->getOperand(1);
8577   if (N1.getOpcode() == ISD::AND) {
8578     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8579     if (!N11C)
8580       return SDValue();
8581     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8582     unsigned LSB = countTrailingZeros(~InvMask);
8583     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8584     assert(Width <
8585                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8586            "undefined behavior");
8587     unsigned Mask = (1u << Width) - 1;
8588     unsigned Mask2 = N11C->getZExtValue();
8589     if ((Mask & (~Mask2)) == 0)
8590       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8591                              N->getOperand(0), N1.getOperand(0),
8592                              N->getOperand(2));
8593   }
8594   return SDValue();
8595 }
8596
8597 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8598 /// ARMISD::VMOVRRD.
8599 static SDValue PerformVMOVRRDCombine(SDNode *N,
8600                                      TargetLowering::DAGCombinerInfo &DCI,
8601                                      const ARMSubtarget *Subtarget) {
8602   // vmovrrd(vmovdrr x, y) -> x,y
8603   SDValue InDouble = N->getOperand(0);
8604   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8605     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8606
8607   // vmovrrd(load f64) -> (load i32), (load i32)
8608   SDNode *InNode = InDouble.getNode();
8609   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8610       InNode->getValueType(0) == MVT::f64 &&
8611       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8612       !cast<LoadSDNode>(InNode)->isVolatile()) {
8613     // TODO: Should this be done for non-FrameIndex operands?
8614     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8615
8616     SelectionDAG &DAG = DCI.DAG;
8617     SDLoc DL(LD);
8618     SDValue BasePtr = LD->getBasePtr();
8619     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8620                                  LD->getPointerInfo(), LD->isVolatile(),
8621                                  LD->isNonTemporal(), LD->isInvariant(),
8622                                  LD->getAlignment());
8623
8624     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8625                                     DAG.getConstant(4, DL, MVT::i32));
8626     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8627                                  LD->getPointerInfo(), LD->isVolatile(),
8628                                  LD->isNonTemporal(), LD->isInvariant(),
8629                                  std::min(4U, LD->getAlignment() / 2));
8630
8631     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8632     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8633       std::swap (NewLD1, NewLD2);
8634     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8635     return Result;
8636   }
8637
8638   return SDValue();
8639 }
8640
8641 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8642 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8643 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8644   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8645   SDValue Op0 = N->getOperand(0);
8646   SDValue Op1 = N->getOperand(1);
8647   if (Op0.getOpcode() == ISD::BITCAST)
8648     Op0 = Op0.getOperand(0);
8649   if (Op1.getOpcode() == ISD::BITCAST)
8650     Op1 = Op1.getOperand(0);
8651   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8652       Op0.getNode() == Op1.getNode() &&
8653       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8654     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8655                        N->getValueType(0), Op0.getOperand(0));
8656   return SDValue();
8657 }
8658
8659 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8660 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8661 /// i64 vector to have f64 elements, since the value can then be loaded
8662 /// directly into a VFP register.
8663 static bool hasNormalLoadOperand(SDNode *N) {
8664   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8665   for (unsigned i = 0; i < NumElts; ++i) {
8666     SDNode *Elt = N->getOperand(i).getNode();
8667     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8668       return true;
8669   }
8670   return false;
8671 }
8672
8673 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8674 /// ISD::BUILD_VECTOR.
8675 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8676                                           TargetLowering::DAGCombinerInfo &DCI,
8677                                           const ARMSubtarget *Subtarget) {
8678   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8679   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8680   // into a pair of GPRs, which is fine when the value is used as a scalar,
8681   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8682   SelectionDAG &DAG = DCI.DAG;
8683   if (N->getNumOperands() == 2) {
8684     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8685     if (RV.getNode())
8686       return RV;
8687   }
8688
8689   // Load i64 elements as f64 values so that type legalization does not split
8690   // them up into i32 values.
8691   EVT VT = N->getValueType(0);
8692   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8693     return SDValue();
8694   SDLoc dl(N);
8695   SmallVector<SDValue, 8> Ops;
8696   unsigned NumElts = VT.getVectorNumElements();
8697   for (unsigned i = 0; i < NumElts; ++i) {
8698     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8699     Ops.push_back(V);
8700     // Make the DAGCombiner fold the bitcast.
8701     DCI.AddToWorklist(V.getNode());
8702   }
8703   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8704   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8705   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8706 }
8707
8708 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8709 static SDValue
8710 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8711   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8712   // At that time, we may have inserted bitcasts from integer to float.
8713   // If these bitcasts have survived DAGCombine, change the lowering of this
8714   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8715   // force to use floating point types.
8716
8717   // Make sure we can change the type of the vector.
8718   // This is possible iff:
8719   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8720   //    1.1. Vector is used only once.
8721   //    1.2. Use is a bit convert to an integer type.
8722   // 2. The size of its operands are 32-bits (64-bits are not legal).
8723   EVT VT = N->getValueType(0);
8724   EVT EltVT = VT.getVectorElementType();
8725
8726   // Check 1.1. and 2.
8727   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8728     return SDValue();
8729
8730   // By construction, the input type must be float.
8731   assert(EltVT == MVT::f32 && "Unexpected type!");
8732
8733   // Check 1.2.
8734   SDNode *Use = *N->use_begin();
8735   if (Use->getOpcode() != ISD::BITCAST ||
8736       Use->getValueType(0).isFloatingPoint())
8737     return SDValue();
8738
8739   // Check profitability.
8740   // Model is, if more than half of the relevant operands are bitcast from
8741   // i32, turn the build_vector into a sequence of insert_vector_elt.
8742   // Relevant operands are everything that is not statically
8743   // (i.e., at compile time) bitcasted.
8744   unsigned NumOfBitCastedElts = 0;
8745   unsigned NumElts = VT.getVectorNumElements();
8746   unsigned NumOfRelevantElts = NumElts;
8747   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8748     SDValue Elt = N->getOperand(Idx);
8749     if (Elt->getOpcode() == ISD::BITCAST) {
8750       // Assume only bit cast to i32 will go away.
8751       if (Elt->getOperand(0).getValueType() == MVT::i32)
8752         ++NumOfBitCastedElts;
8753     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8754       // Constants are statically casted, thus do not count them as
8755       // relevant operands.
8756       --NumOfRelevantElts;
8757   }
8758
8759   // Check if more than half of the elements require a non-free bitcast.
8760   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8761     return SDValue();
8762
8763   SelectionDAG &DAG = DCI.DAG;
8764   // Create the new vector type.
8765   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8766   // Check if the type is legal.
8767   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8768   if (!TLI.isTypeLegal(VecVT))
8769     return SDValue();
8770
8771   // Combine:
8772   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8773   // => BITCAST INSERT_VECTOR_ELT
8774   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8775   //                      (BITCAST EN), N.
8776   SDValue Vec = DAG.getUNDEF(VecVT);
8777   SDLoc dl(N);
8778   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8779     SDValue V = N->getOperand(Idx);
8780     if (V.getOpcode() == ISD::UNDEF)
8781       continue;
8782     if (V.getOpcode() == ISD::BITCAST &&
8783         V->getOperand(0).getValueType() == MVT::i32)
8784       // Fold obvious case.
8785       V = V.getOperand(0);
8786     else {
8787       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8788       // Make the DAGCombiner fold the bitcasts.
8789       DCI.AddToWorklist(V.getNode());
8790     }
8791     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
8792     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8793   }
8794   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8795   // Make the DAGCombiner fold the bitcasts.
8796   DCI.AddToWorklist(Vec.getNode());
8797   return Vec;
8798 }
8799
8800 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8801 /// ISD::INSERT_VECTOR_ELT.
8802 static SDValue PerformInsertEltCombine(SDNode *N,
8803                                        TargetLowering::DAGCombinerInfo &DCI) {
8804   // Bitcast an i64 load inserted into a vector to f64.
8805   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8806   EVT VT = N->getValueType(0);
8807   SDNode *Elt = N->getOperand(1).getNode();
8808   if (VT.getVectorElementType() != MVT::i64 ||
8809       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8810     return SDValue();
8811
8812   SelectionDAG &DAG = DCI.DAG;
8813   SDLoc dl(N);
8814   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8815                                  VT.getVectorNumElements());
8816   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8817   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8818   // Make the DAGCombiner fold the bitcasts.
8819   DCI.AddToWorklist(Vec.getNode());
8820   DCI.AddToWorklist(V.getNode());
8821   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8822                                Vec, V, N->getOperand(2));
8823   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8824 }
8825
8826 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8827 /// ISD::VECTOR_SHUFFLE.
8828 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8829   // The LLVM shufflevector instruction does not require the shuffle mask
8830   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8831   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8832   // operands do not match the mask length, they are extended by concatenating
8833   // them with undef vectors.  That is probably the right thing for other
8834   // targets, but for NEON it is better to concatenate two double-register
8835   // size vector operands into a single quad-register size vector.  Do that
8836   // transformation here:
8837   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8838   //   shuffle(concat(v1, v2), undef)
8839   SDValue Op0 = N->getOperand(0);
8840   SDValue Op1 = N->getOperand(1);
8841   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8842       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8843       Op0.getNumOperands() != 2 ||
8844       Op1.getNumOperands() != 2)
8845     return SDValue();
8846   SDValue Concat0Op1 = Op0.getOperand(1);
8847   SDValue Concat1Op1 = Op1.getOperand(1);
8848   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8849       Concat1Op1.getOpcode() != ISD::UNDEF)
8850     return SDValue();
8851   // Skip the transformation if any of the types are illegal.
8852   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8853   EVT VT = N->getValueType(0);
8854   if (!TLI.isTypeLegal(VT) ||
8855       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8856       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8857     return SDValue();
8858
8859   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8860                                   Op0.getOperand(0), Op1.getOperand(0));
8861   // Translate the shuffle mask.
8862   SmallVector<int, 16> NewMask;
8863   unsigned NumElts = VT.getVectorNumElements();
8864   unsigned HalfElts = NumElts/2;
8865   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8866   for (unsigned n = 0; n < NumElts; ++n) {
8867     int MaskElt = SVN->getMaskElt(n);
8868     int NewElt = -1;
8869     if (MaskElt < (int)HalfElts)
8870       NewElt = MaskElt;
8871     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8872       NewElt = HalfElts + MaskElt - NumElts;
8873     NewMask.push_back(NewElt);
8874   }
8875   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8876                               DAG.getUNDEF(VT), NewMask.data());
8877 }
8878
8879 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8880 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8881 /// base address updates.
8882 /// For generic load/stores, the memory type is assumed to be a vector.
8883 /// The caller is assumed to have checked legality.
8884 static SDValue CombineBaseUpdate(SDNode *N,
8885                                  TargetLowering::DAGCombinerInfo &DCI) {
8886   SelectionDAG &DAG = DCI.DAG;
8887   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8888                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8889   const bool isStore = N->getOpcode() == ISD::STORE;
8890   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8891   SDValue Addr = N->getOperand(AddrOpIdx);
8892   MemSDNode *MemN = cast<MemSDNode>(N);
8893   SDLoc dl(N);
8894
8895   // Search for a use of the address operand that is an increment.
8896   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8897          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8898     SDNode *User = *UI;
8899     if (User->getOpcode() != ISD::ADD ||
8900         UI.getUse().getResNo() != Addr.getResNo())
8901       continue;
8902
8903     // Check that the add is independent of the load/store.  Otherwise, folding
8904     // it would create a cycle.
8905     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8906       continue;
8907
8908     // Find the new opcode for the updating load/store.
8909     bool isLoadOp = true;
8910     bool isLaneOp = false;
8911     unsigned NewOpc = 0;
8912     unsigned NumVecs = 0;
8913     if (isIntrinsic) {
8914       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8915       switch (IntNo) {
8916       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8917       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8918         NumVecs = 1; break;
8919       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8920         NumVecs = 2; break;
8921       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8922         NumVecs = 3; break;
8923       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8924         NumVecs = 4; break;
8925       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8926         NumVecs = 2; isLaneOp = true; break;
8927       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8928         NumVecs = 3; isLaneOp = true; break;
8929       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8930         NumVecs = 4; isLaneOp = true; break;
8931       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8932         NumVecs = 1; isLoadOp = false; break;
8933       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8934         NumVecs = 2; isLoadOp = false; break;
8935       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8936         NumVecs = 3; isLoadOp = false; break;
8937       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8938         NumVecs = 4; isLoadOp = false; break;
8939       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8940         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8941       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8942         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8943       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8944         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8945       }
8946     } else {
8947       isLaneOp = true;
8948       switch (N->getOpcode()) {
8949       default: llvm_unreachable("unexpected opcode for Neon base update");
8950       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8951       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8952       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8953       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
8954         NumVecs = 1; isLaneOp = false; break;
8955       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
8956         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8957       }
8958     }
8959
8960     // Find the size of memory referenced by the load/store.
8961     EVT VecTy;
8962     if (isLoadOp) {
8963       VecTy = N->getValueType(0);
8964     } else if (isIntrinsic) {
8965       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8966     } else {
8967       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8968       VecTy = N->getOperand(1).getValueType();
8969     }
8970
8971     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8972     if (isLaneOp)
8973       NumBytes /= VecTy.getVectorNumElements();
8974
8975     // If the increment is a constant, it must match the memory ref size.
8976     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8977     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8978       uint64_t IncVal = CInc->getZExtValue();
8979       if (IncVal != NumBytes)
8980         continue;
8981     } else if (NumBytes >= 3 * 16) {
8982       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8983       // separate instructions that make it harder to use a non-constant update.
8984       continue;
8985     }
8986
8987     // OK, we found an ADD we can fold into the base update.
8988     // Now, create a _UPD node, taking care of not breaking alignment.
8989
8990     EVT AlignedVecTy = VecTy;
8991     unsigned Alignment = MemN->getAlignment();
8992
8993     // If this is a less-than-standard-aligned load/store, change the type to
8994     // match the standard alignment.
8995     // The alignment is overlooked when selecting _UPD variants; and it's
8996     // easier to introduce bitcasts here than fix that.
8997     // There are 3 ways to get to this base-update combine:
8998     // - intrinsics: they are assumed to be properly aligned (to the standard
8999     //   alignment of the memory type), so we don't need to do anything.
9000     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9001     //   intrinsics, so, likewise, there's nothing to do.
9002     // - generic load/store instructions: the alignment is specified as an
9003     //   explicit operand, rather than implicitly as the standard alignment
9004     //   of the memory type (like the intrisics).  We need to change the
9005     //   memory type to match the explicit alignment.  That way, we don't
9006     //   generate non-standard-aligned ARMISD::VLDx nodes.
9007     if (isa<LSBaseSDNode>(N)) {
9008       if (Alignment == 0)
9009         Alignment = 1;
9010       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9011         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9012         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9013         assert(!isLaneOp && "Unexpected generic load/store lane.");
9014         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9015         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9016       }
9017       // Don't set an explicit alignment on regular load/stores that we want
9018       // to transform to VLD/VST 1_UPD nodes.
9019       // This matches the behavior of regular load/stores, which only get an
9020       // explicit alignment if the MMO alignment is larger than the standard
9021       // alignment of the memory type.
9022       // Intrinsics, however, always get an explicit alignment, set to the
9023       // alignment of the MMO.
9024       Alignment = 1;
9025     }
9026
9027     // Create the new updating load/store node.
9028     // First, create an SDVTList for the new updating node's results.
9029     EVT Tys[6];
9030     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9031     unsigned n;
9032     for (n = 0; n < NumResultVecs; ++n)
9033       Tys[n] = AlignedVecTy;
9034     Tys[n++] = MVT::i32;
9035     Tys[n] = MVT::Other;
9036     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9037
9038     // Then, gather the new node's operands.
9039     SmallVector<SDValue, 8> Ops;
9040     Ops.push_back(N->getOperand(0)); // incoming chain
9041     Ops.push_back(N->getOperand(AddrOpIdx));
9042     Ops.push_back(Inc);
9043
9044     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9045       // Try to match the intrinsic's signature
9046       Ops.push_back(StN->getValue());
9047     } else {
9048       // Loads (and of course intrinsics) match the intrinsics' signature,
9049       // so just add all but the alignment operand.
9050       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9051         Ops.push_back(N->getOperand(i));
9052     }
9053
9054     // For all node types, the alignment operand is always the last one.
9055     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9056
9057     // If this is a non-standard-aligned STORE, the penultimate operand is the
9058     // stored value.  Bitcast it to the aligned type.
9059     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9060       SDValue &StVal = Ops[Ops.size()-2];
9061       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9062     }
9063
9064     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9065                                            Ops, AlignedVecTy,
9066                                            MemN->getMemOperand());
9067
9068     // Update the uses.
9069     SmallVector<SDValue, 5> NewResults;
9070     for (unsigned i = 0; i < NumResultVecs; ++i)
9071       NewResults.push_back(SDValue(UpdN.getNode(), i));
9072
9073     // If this is an non-standard-aligned LOAD, the first result is the loaded
9074     // value.  Bitcast it to the expected result type.
9075     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9076       SDValue &LdVal = NewResults[0];
9077       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9078     }
9079
9080     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9081     DCI.CombineTo(N, NewResults);
9082     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9083
9084     break;
9085   }
9086   return SDValue();
9087 }
9088
9089 static SDValue PerformVLDCombine(SDNode *N,
9090                                  TargetLowering::DAGCombinerInfo &DCI) {
9091   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9092     return SDValue();
9093
9094   return CombineBaseUpdate(N, DCI);
9095 }
9096
9097 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9098 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9099 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9100 /// return true.
9101 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9102   SelectionDAG &DAG = DCI.DAG;
9103   EVT VT = N->getValueType(0);
9104   // vldN-dup instructions only support 64-bit vectors for N > 1.
9105   if (!VT.is64BitVector())
9106     return false;
9107
9108   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9109   SDNode *VLD = N->getOperand(0).getNode();
9110   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9111     return false;
9112   unsigned NumVecs = 0;
9113   unsigned NewOpc = 0;
9114   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9115   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9116     NumVecs = 2;
9117     NewOpc = ARMISD::VLD2DUP;
9118   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9119     NumVecs = 3;
9120     NewOpc = ARMISD::VLD3DUP;
9121   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9122     NumVecs = 4;
9123     NewOpc = ARMISD::VLD4DUP;
9124   } else {
9125     return false;
9126   }
9127
9128   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9129   // numbers match the load.
9130   unsigned VLDLaneNo =
9131     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9132   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9133        UI != UE; ++UI) {
9134     // Ignore uses of the chain result.
9135     if (UI.getUse().getResNo() == NumVecs)
9136       continue;
9137     SDNode *User = *UI;
9138     if (User->getOpcode() != ARMISD::VDUPLANE ||
9139         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9140       return false;
9141   }
9142
9143   // Create the vldN-dup node.
9144   EVT Tys[5];
9145   unsigned n;
9146   for (n = 0; n < NumVecs; ++n)
9147     Tys[n] = VT;
9148   Tys[n] = MVT::Other;
9149   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9150   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9151   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9152   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9153                                            Ops, VLDMemInt->getMemoryVT(),
9154                                            VLDMemInt->getMemOperand());
9155
9156   // Update the uses.
9157   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9158        UI != UE; ++UI) {
9159     unsigned ResNo = UI.getUse().getResNo();
9160     // Ignore uses of the chain result.
9161     if (ResNo == NumVecs)
9162       continue;
9163     SDNode *User = *UI;
9164     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9165   }
9166
9167   // Now the vldN-lane intrinsic is dead except for its chain result.
9168   // Update uses of the chain.
9169   std::vector<SDValue> VLDDupResults;
9170   for (unsigned n = 0; n < NumVecs; ++n)
9171     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9172   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9173   DCI.CombineTo(VLD, VLDDupResults);
9174
9175   return true;
9176 }
9177
9178 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9179 /// ARMISD::VDUPLANE.
9180 static SDValue PerformVDUPLANECombine(SDNode *N,
9181                                       TargetLowering::DAGCombinerInfo &DCI) {
9182   SDValue Op = N->getOperand(0);
9183
9184   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9185   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9186   if (CombineVLDDUP(N, DCI))
9187     return SDValue(N, 0);
9188
9189   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9190   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9191   while (Op.getOpcode() == ISD::BITCAST)
9192     Op = Op.getOperand(0);
9193   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9194     return SDValue();
9195
9196   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9197   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9198   // The canonical VMOV for a zero vector uses a 32-bit element size.
9199   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9200   unsigned EltBits;
9201   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9202     EltSize = 8;
9203   EVT VT = N->getValueType(0);
9204   if (EltSize > VT.getVectorElementType().getSizeInBits())
9205     return SDValue();
9206
9207   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9208 }
9209
9210 static SDValue PerformLOADCombine(SDNode *N,
9211                                   TargetLowering::DAGCombinerInfo &DCI) {
9212   EVT VT = N->getValueType(0);
9213
9214   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9215   if (ISD::isNormalLoad(N) && VT.isVector() &&
9216       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9217     return CombineBaseUpdate(N, DCI);
9218
9219   return SDValue();
9220 }
9221
9222 /// PerformSTORECombine - Target-specific dag combine xforms for
9223 /// ISD::STORE.
9224 static SDValue PerformSTORECombine(SDNode *N,
9225                                    TargetLowering::DAGCombinerInfo &DCI) {
9226   StoreSDNode *St = cast<StoreSDNode>(N);
9227   if (St->isVolatile())
9228     return SDValue();
9229
9230   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9231   // pack all of the elements in one place.  Next, store to memory in fewer
9232   // chunks.
9233   SDValue StVal = St->getValue();
9234   EVT VT = StVal.getValueType();
9235   if (St->isTruncatingStore() && VT.isVector()) {
9236     SelectionDAG &DAG = DCI.DAG;
9237     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9238     EVT StVT = St->getMemoryVT();
9239     unsigned NumElems = VT.getVectorNumElements();
9240     assert(StVT != VT && "Cannot truncate to the same type");
9241     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9242     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9243
9244     // From, To sizes and ElemCount must be pow of two
9245     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9246
9247     // We are going to use the original vector elt for storing.
9248     // Accumulated smaller vector elements must be a multiple of the store size.
9249     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9250
9251     unsigned SizeRatio  = FromEltSz / ToEltSz;
9252     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9253
9254     // Create a type on which we perform the shuffle.
9255     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9256                                      NumElems*SizeRatio);
9257     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9258
9259     SDLoc DL(St);
9260     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9261     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9262     for (unsigned i = 0; i < NumElems; ++i)
9263       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9264
9265     // Can't shuffle using an illegal type.
9266     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9267
9268     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9269                                 DAG.getUNDEF(WideVec.getValueType()),
9270                                 ShuffleVec.data());
9271     // At this point all of the data is stored at the bottom of the
9272     // register. We now need to save it to mem.
9273
9274     // Find the largest store unit
9275     MVT StoreType = MVT::i8;
9276     for (MVT Tp : MVT::integer_valuetypes()) {
9277       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9278         StoreType = Tp;
9279     }
9280     // Didn't find a legal store type.
9281     if (!TLI.isTypeLegal(StoreType))
9282       return SDValue();
9283
9284     // Bitcast the original vector into a vector of store-size units
9285     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9286             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9287     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9288     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9289     SmallVector<SDValue, 8> Chains;
9290     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, DL,
9291                                         TLI.getPointerTy());
9292     SDValue BasePtr = St->getBasePtr();
9293
9294     // Perform one or more big stores into memory.
9295     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9296     for (unsigned I = 0; I < E; I++) {
9297       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9298                                    StoreType, ShuffWide,
9299                                    DAG.getIntPtrConstant(I, DL));
9300       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9301                                 St->getPointerInfo(), St->isVolatile(),
9302                                 St->isNonTemporal(), St->getAlignment());
9303       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9304                             Increment);
9305       Chains.push_back(Ch);
9306     }
9307     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9308   }
9309
9310   if (!ISD::isNormalStore(St))
9311     return SDValue();
9312
9313   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9314   // ARM stores of arguments in the same cache line.
9315   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9316       StVal.getNode()->hasOneUse()) {
9317     SelectionDAG  &DAG = DCI.DAG;
9318     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9319     SDLoc DL(St);
9320     SDValue BasePtr = St->getBasePtr();
9321     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9322                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9323                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9324                                   St->isNonTemporal(), St->getAlignment());
9325
9326     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9327                                     DAG.getConstant(4, DL, MVT::i32));
9328     return DAG.getStore(NewST1.getValue(0), DL,
9329                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9330                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9331                         St->isNonTemporal(),
9332                         std::min(4U, St->getAlignment() / 2));
9333   }
9334
9335   if (StVal.getValueType() == MVT::i64 &&
9336       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9337
9338     // Bitcast an i64 store extracted from a vector to f64.
9339     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9340     SelectionDAG &DAG = DCI.DAG;
9341     SDLoc dl(StVal);
9342     SDValue IntVec = StVal.getOperand(0);
9343     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9344                                    IntVec.getValueType().getVectorNumElements());
9345     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9346     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9347                                  Vec, StVal.getOperand(1));
9348     dl = SDLoc(N);
9349     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9350     // Make the DAGCombiner fold the bitcasts.
9351     DCI.AddToWorklist(Vec.getNode());
9352     DCI.AddToWorklist(ExtElt.getNode());
9353     DCI.AddToWorklist(V.getNode());
9354     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9355                         St->getPointerInfo(), St->isVolatile(),
9356                         St->isNonTemporal(), St->getAlignment(),
9357                         St->getAAInfo());
9358   }
9359
9360   // If this is a legal vector store, try to combine it into a VST1_UPD.
9361   if (ISD::isNormalStore(N) && VT.isVector() &&
9362       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9363     return CombineBaseUpdate(N, DCI);
9364
9365   return SDValue();
9366 }
9367
9368 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9369 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9370 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9371 {
9372   integerPart cN;
9373   integerPart c0 = 0;
9374   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9375        I != E; I++) {
9376     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9377     if (!C)
9378       return false;
9379
9380     bool isExact;
9381     APFloat APF = C->getValueAPF();
9382     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9383         != APFloat::opOK || !isExact)
9384       return false;
9385
9386     c0 = (I == 0) ? cN : c0;
9387     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9388       return false;
9389   }
9390   C = c0;
9391   return true;
9392 }
9393
9394 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9395 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9396 /// when the VMUL has a constant operand that is a power of 2.
9397 ///
9398 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9399 ///  vmul.f32        d16, d17, d16
9400 ///  vcvt.s32.f32    d16, d16
9401 /// becomes:
9402 ///  vcvt.s32.f32    d16, d16, #3
9403 static SDValue PerformVCVTCombine(SDNode *N,
9404                                   TargetLowering::DAGCombinerInfo &DCI,
9405                                   const ARMSubtarget *Subtarget) {
9406   SelectionDAG &DAG = DCI.DAG;
9407   SDValue Op = N->getOperand(0);
9408
9409   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9410       Op.getOpcode() != ISD::FMUL)
9411     return SDValue();
9412
9413   uint64_t C;
9414   SDValue N0 = Op->getOperand(0);
9415   SDValue ConstVec = Op->getOperand(1);
9416   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9417
9418   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9419       !isConstVecPow2(ConstVec, isSigned, C))
9420     return SDValue();
9421
9422   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9423   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9424   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9425   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9426       NumLanes > 4) {
9427     // These instructions only exist converting from f32 to i32. We can handle
9428     // smaller integers by generating an extra truncate, but larger ones would
9429     // be lossy. We also can't handle more then 4 lanes, since these intructions
9430     // only support v2i32/v4i32 types.
9431     return SDValue();
9432   }
9433
9434   SDLoc dl(N);
9435   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9436     Intrinsic::arm_neon_vcvtfp2fxu;
9437   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9438                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9439                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9440                                  N0,
9441                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9442
9443   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9444     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9445
9446   return FixConv;
9447 }
9448
9449 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9450 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9451 /// when the VDIV has a constant operand that is a power of 2.
9452 ///
9453 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9454 ///  vcvt.f32.s32    d16, d16
9455 ///  vdiv.f32        d16, d17, d16
9456 /// becomes:
9457 ///  vcvt.f32.s32    d16, d16, #3
9458 static SDValue PerformVDIVCombine(SDNode *N,
9459                                   TargetLowering::DAGCombinerInfo &DCI,
9460                                   const ARMSubtarget *Subtarget) {
9461   SelectionDAG &DAG = DCI.DAG;
9462   SDValue Op = N->getOperand(0);
9463   unsigned OpOpcode = Op.getNode()->getOpcode();
9464
9465   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9466       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9467     return SDValue();
9468
9469   uint64_t C;
9470   SDValue ConstVec = N->getOperand(1);
9471   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9472
9473   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9474       !isConstVecPow2(ConstVec, isSigned, C))
9475     return SDValue();
9476
9477   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9478   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9479   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9480     // These instructions only exist converting from i32 to f32. We can handle
9481     // smaller integers by generating an extra extend, but larger ones would
9482     // be lossy.
9483     return SDValue();
9484   }
9485
9486   SDLoc dl(N);
9487   SDValue ConvInput = Op.getOperand(0);
9488   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9489   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9490     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9491                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9492                             ConvInput);
9493
9494   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9495     Intrinsic::arm_neon_vcvtfxu2fp;
9496   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9497                      Op.getValueType(),
9498                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9499                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9500 }
9501
9502 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9503 /// operand of a vector shift operation, where all the elements of the
9504 /// build_vector must have the same constant integer value.
9505 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9506   // Ignore bit_converts.
9507   while (Op.getOpcode() == ISD::BITCAST)
9508     Op = Op.getOperand(0);
9509   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9510   APInt SplatBits, SplatUndef;
9511   unsigned SplatBitSize;
9512   bool HasAnyUndefs;
9513   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9514                                       HasAnyUndefs, ElementBits) ||
9515       SplatBitSize > ElementBits)
9516     return false;
9517   Cnt = SplatBits.getSExtValue();
9518   return true;
9519 }
9520
9521 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9522 /// operand of a vector shift left operation.  That value must be in the range:
9523 ///   0 <= Value < ElementBits for a left shift; or
9524 ///   0 <= Value <= ElementBits for a long left shift.
9525 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9526   assert(VT.isVector() && "vector shift count is not a vector type");
9527   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9528   if (! getVShiftImm(Op, ElementBits, Cnt))
9529     return false;
9530   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9531 }
9532
9533 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9534 /// operand of a vector shift right operation.  For a shift opcode, the value
9535 /// is positive, but for an intrinsic the value count must be negative. The
9536 /// absolute value must be in the range:
9537 ///   1 <= |Value| <= ElementBits for a right shift; or
9538 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9539 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9540                          int64_t &Cnt) {
9541   assert(VT.isVector() && "vector shift count is not a vector type");
9542   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9543   if (! getVShiftImm(Op, ElementBits, Cnt))
9544     return false;
9545   if (isIntrinsic)
9546     Cnt = -Cnt;
9547   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9548 }
9549
9550 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9551 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9552   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9553   switch (IntNo) {
9554   default:
9555     // Don't do anything for most intrinsics.
9556     break;
9557
9558   // Vector shifts: check for immediate versions and lower them.
9559   // Note: This is done during DAG combining instead of DAG legalizing because
9560   // the build_vectors for 64-bit vector element shift counts are generally
9561   // not legal, and it is hard to see their values after they get legalized to
9562   // loads from a constant pool.
9563   case Intrinsic::arm_neon_vshifts:
9564   case Intrinsic::arm_neon_vshiftu:
9565   case Intrinsic::arm_neon_vrshifts:
9566   case Intrinsic::arm_neon_vrshiftu:
9567   case Intrinsic::arm_neon_vrshiftn:
9568   case Intrinsic::arm_neon_vqshifts:
9569   case Intrinsic::arm_neon_vqshiftu:
9570   case Intrinsic::arm_neon_vqshiftsu:
9571   case Intrinsic::arm_neon_vqshiftns:
9572   case Intrinsic::arm_neon_vqshiftnu:
9573   case Intrinsic::arm_neon_vqshiftnsu:
9574   case Intrinsic::arm_neon_vqrshiftns:
9575   case Intrinsic::arm_neon_vqrshiftnu:
9576   case Intrinsic::arm_neon_vqrshiftnsu: {
9577     EVT VT = N->getOperand(1).getValueType();
9578     int64_t Cnt;
9579     unsigned VShiftOpc = 0;
9580
9581     switch (IntNo) {
9582     case Intrinsic::arm_neon_vshifts:
9583     case Intrinsic::arm_neon_vshiftu:
9584       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9585         VShiftOpc = ARMISD::VSHL;
9586         break;
9587       }
9588       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9589         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9590                      ARMISD::VSHRs : ARMISD::VSHRu);
9591         break;
9592       }
9593       return SDValue();
9594
9595     case Intrinsic::arm_neon_vrshifts:
9596     case Intrinsic::arm_neon_vrshiftu:
9597       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9598         break;
9599       return SDValue();
9600
9601     case Intrinsic::arm_neon_vqshifts:
9602     case Intrinsic::arm_neon_vqshiftu:
9603       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9604         break;
9605       return SDValue();
9606
9607     case Intrinsic::arm_neon_vqshiftsu:
9608       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9609         break;
9610       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9611
9612     case Intrinsic::arm_neon_vrshiftn:
9613     case Intrinsic::arm_neon_vqshiftns:
9614     case Intrinsic::arm_neon_vqshiftnu:
9615     case Intrinsic::arm_neon_vqshiftnsu:
9616     case Intrinsic::arm_neon_vqrshiftns:
9617     case Intrinsic::arm_neon_vqrshiftnu:
9618     case Intrinsic::arm_neon_vqrshiftnsu:
9619       // Narrowing shifts require an immediate right shift.
9620       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9621         break;
9622       llvm_unreachable("invalid shift count for narrowing vector shift "
9623                        "intrinsic");
9624
9625     default:
9626       llvm_unreachable("unhandled vector shift");
9627     }
9628
9629     switch (IntNo) {
9630     case Intrinsic::arm_neon_vshifts:
9631     case Intrinsic::arm_neon_vshiftu:
9632       // Opcode already set above.
9633       break;
9634     case Intrinsic::arm_neon_vrshifts:
9635       VShiftOpc = ARMISD::VRSHRs; break;
9636     case Intrinsic::arm_neon_vrshiftu:
9637       VShiftOpc = ARMISD::VRSHRu; break;
9638     case Intrinsic::arm_neon_vrshiftn:
9639       VShiftOpc = ARMISD::VRSHRN; break;
9640     case Intrinsic::arm_neon_vqshifts:
9641       VShiftOpc = ARMISD::VQSHLs; break;
9642     case Intrinsic::arm_neon_vqshiftu:
9643       VShiftOpc = ARMISD::VQSHLu; break;
9644     case Intrinsic::arm_neon_vqshiftsu:
9645       VShiftOpc = ARMISD::VQSHLsu; break;
9646     case Intrinsic::arm_neon_vqshiftns:
9647       VShiftOpc = ARMISD::VQSHRNs; break;
9648     case Intrinsic::arm_neon_vqshiftnu:
9649       VShiftOpc = ARMISD::VQSHRNu; break;
9650     case Intrinsic::arm_neon_vqshiftnsu:
9651       VShiftOpc = ARMISD::VQSHRNsu; break;
9652     case Intrinsic::arm_neon_vqrshiftns:
9653       VShiftOpc = ARMISD::VQRSHRNs; break;
9654     case Intrinsic::arm_neon_vqrshiftnu:
9655       VShiftOpc = ARMISD::VQRSHRNu; break;
9656     case Intrinsic::arm_neon_vqrshiftnsu:
9657       VShiftOpc = ARMISD::VQRSHRNsu; break;
9658     }
9659
9660     SDLoc dl(N);
9661     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9662                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9663   }
9664
9665   case Intrinsic::arm_neon_vshiftins: {
9666     EVT VT = N->getOperand(1).getValueType();
9667     int64_t Cnt;
9668     unsigned VShiftOpc = 0;
9669
9670     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9671       VShiftOpc = ARMISD::VSLI;
9672     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9673       VShiftOpc = ARMISD::VSRI;
9674     else {
9675       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9676     }
9677
9678     SDLoc dl(N);
9679     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9680                        N->getOperand(1), N->getOperand(2),
9681                        DAG.getConstant(Cnt, dl, MVT::i32));
9682   }
9683
9684   case Intrinsic::arm_neon_vqrshifts:
9685   case Intrinsic::arm_neon_vqrshiftu:
9686     // No immediate versions of these to check for.
9687     break;
9688   }
9689
9690   return SDValue();
9691 }
9692
9693 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9694 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9695 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9696 /// vector element shift counts are generally not legal, and it is hard to see
9697 /// their values after they get legalized to loads from a constant pool.
9698 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9699                                    const ARMSubtarget *ST) {
9700   EVT VT = N->getValueType(0);
9701   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9702     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9703     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9704     SDValue N1 = N->getOperand(1);
9705     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9706       SDValue N0 = N->getOperand(0);
9707       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9708           DAG.MaskedValueIsZero(N0.getOperand(0),
9709                                 APInt::getHighBitsSet(32, 16)))
9710         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9711     }
9712   }
9713
9714   // Nothing to be done for scalar shifts.
9715   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9716   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9717     return SDValue();
9718
9719   assert(ST->hasNEON() && "unexpected vector shift");
9720   int64_t Cnt;
9721
9722   switch (N->getOpcode()) {
9723   default: llvm_unreachable("unexpected shift opcode");
9724
9725   case ISD::SHL:
9726     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
9727       SDLoc dl(N);
9728       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
9729                          DAG.getConstant(Cnt, dl, MVT::i32));
9730     }
9731     break;
9732
9733   case ISD::SRA:
9734   case ISD::SRL:
9735     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9736       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9737                             ARMISD::VSHRs : ARMISD::VSHRu);
9738       SDLoc dl(N);
9739       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
9740                          DAG.getConstant(Cnt, dl, MVT::i32));
9741     }
9742   }
9743   return SDValue();
9744 }
9745
9746 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9747 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9748 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9749                                     const ARMSubtarget *ST) {
9750   SDValue N0 = N->getOperand(0);
9751
9752   // Check for sign- and zero-extensions of vector extract operations of 8-
9753   // and 16-bit vector elements.  NEON supports these directly.  They are
9754   // handled during DAG combining because type legalization will promote them
9755   // to 32-bit types and it is messy to recognize the operations after that.
9756   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9757     SDValue Vec = N0.getOperand(0);
9758     SDValue Lane = N0.getOperand(1);
9759     EVT VT = N->getValueType(0);
9760     EVT EltVT = N0.getValueType();
9761     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9762
9763     if (VT == MVT::i32 &&
9764         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9765         TLI.isTypeLegal(Vec.getValueType()) &&
9766         isa<ConstantSDNode>(Lane)) {
9767
9768       unsigned Opc = 0;
9769       switch (N->getOpcode()) {
9770       default: llvm_unreachable("unexpected opcode");
9771       case ISD::SIGN_EXTEND:
9772         Opc = ARMISD::VGETLANEs;
9773         break;
9774       case ISD::ZERO_EXTEND:
9775       case ISD::ANY_EXTEND:
9776         Opc = ARMISD::VGETLANEu;
9777         break;
9778       }
9779       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9780     }
9781   }
9782
9783   return SDValue();
9784 }
9785
9786 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9787 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9788 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9789                                        const ARMSubtarget *ST) {
9790   // If the target supports NEON, try to use vmax/vmin instructions for f32
9791   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9792   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9793   // a NaN; only do the transformation when it matches that behavior.
9794
9795   // For now only do this when using NEON for FP operations; if using VFP, it
9796   // is not obvious that the benefit outweighs the cost of switching to the
9797   // NEON pipeline.
9798   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9799       N->getValueType(0) != MVT::f32)
9800     return SDValue();
9801
9802   SDValue CondLHS = N->getOperand(0);
9803   SDValue CondRHS = N->getOperand(1);
9804   SDValue LHS = N->getOperand(2);
9805   SDValue RHS = N->getOperand(3);
9806   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9807
9808   unsigned Opcode = 0;
9809   bool IsReversed;
9810   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9811     IsReversed = false; // x CC y ? x : y
9812   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9813     IsReversed = true ; // x CC y ? y : x
9814   } else {
9815     return SDValue();
9816   }
9817
9818   bool IsUnordered;
9819   switch (CC) {
9820   default: break;
9821   case ISD::SETOLT:
9822   case ISD::SETOLE:
9823   case ISD::SETLT:
9824   case ISD::SETLE:
9825   case ISD::SETULT:
9826   case ISD::SETULE:
9827     // If LHS is NaN, an ordered comparison will be false and the result will
9828     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9829     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9830     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9831     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9832       break;
9833     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9834     // will return -0, so vmin can only be used for unsafe math or if one of
9835     // the operands is known to be nonzero.
9836     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9837         !DAG.getTarget().Options.UnsafeFPMath &&
9838         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9839       break;
9840     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9841     break;
9842
9843   case ISD::SETOGT:
9844   case ISD::SETOGE:
9845   case ISD::SETGT:
9846   case ISD::SETGE:
9847   case ISD::SETUGT:
9848   case ISD::SETUGE:
9849     // If LHS is NaN, an ordered comparison will be false and the result will
9850     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9851     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9852     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9853     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9854       break;
9855     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9856     // will return +0, so vmax can only be used for unsafe math or if one of
9857     // the operands is known to be nonzero.
9858     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9859         !DAG.getTarget().Options.UnsafeFPMath &&
9860         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9861       break;
9862     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9863     break;
9864   }
9865
9866   if (!Opcode)
9867     return SDValue();
9868   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9869 }
9870
9871 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9872 SDValue
9873 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9874   SDValue Cmp = N->getOperand(4);
9875   if (Cmp.getOpcode() != ARMISD::CMPZ)
9876     // Only looking at EQ and NE cases.
9877     return SDValue();
9878
9879   EVT VT = N->getValueType(0);
9880   SDLoc dl(N);
9881   SDValue LHS = Cmp.getOperand(0);
9882   SDValue RHS = Cmp.getOperand(1);
9883   SDValue FalseVal = N->getOperand(0);
9884   SDValue TrueVal = N->getOperand(1);
9885   SDValue ARMcc = N->getOperand(2);
9886   ARMCC::CondCodes CC =
9887     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9888
9889   // Simplify
9890   //   mov     r1, r0
9891   //   cmp     r1, x
9892   //   mov     r0, y
9893   //   moveq   r0, x
9894   // to
9895   //   cmp     r0, x
9896   //   movne   r0, y
9897   //
9898   //   mov     r1, r0
9899   //   cmp     r1, x
9900   //   mov     r0, x
9901   //   movne   r0, y
9902   // to
9903   //   cmp     r0, x
9904   //   movne   r0, y
9905   /// FIXME: Turn this into a target neutral optimization?
9906   SDValue Res;
9907   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9908     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9909                       N->getOperand(3), Cmp);
9910   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9911     SDValue ARMcc;
9912     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9913     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9914                       N->getOperand(3), NewCmp);
9915   }
9916
9917   if (Res.getNode()) {
9918     APInt KnownZero, KnownOne;
9919     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9920     // Capture demanded bits information that would be otherwise lost.
9921     if (KnownZero == 0xfffffffe)
9922       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9923                         DAG.getValueType(MVT::i1));
9924     else if (KnownZero == 0xffffff00)
9925       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9926                         DAG.getValueType(MVT::i8));
9927     else if (KnownZero == 0xffff0000)
9928       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9929                         DAG.getValueType(MVT::i16));
9930   }
9931
9932   return Res;
9933 }
9934
9935 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9936                                              DAGCombinerInfo &DCI) const {
9937   switch (N->getOpcode()) {
9938   default: break;
9939   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9940   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9941   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9942   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9943   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9944   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9945   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9946   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9947   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9948   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9949   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9950   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9951   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9952   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9953   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9954   case ISD::FP_TO_SINT:
9955   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9956   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9957   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9958   case ISD::SHL:
9959   case ISD::SRA:
9960   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9961   case ISD::SIGN_EXTEND:
9962   case ISD::ZERO_EXTEND:
9963   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9964   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9965   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9966   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
9967   case ARMISD::VLD2DUP:
9968   case ARMISD::VLD3DUP:
9969   case ARMISD::VLD4DUP:
9970     return PerformVLDCombine(N, DCI);
9971   case ARMISD::BUILD_VECTOR:
9972     return PerformARMBUILD_VECTORCombine(N, DCI);
9973   case ISD::INTRINSIC_VOID:
9974   case ISD::INTRINSIC_W_CHAIN:
9975     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9976     case Intrinsic::arm_neon_vld1:
9977     case Intrinsic::arm_neon_vld2:
9978     case Intrinsic::arm_neon_vld3:
9979     case Intrinsic::arm_neon_vld4:
9980     case Intrinsic::arm_neon_vld2lane:
9981     case Intrinsic::arm_neon_vld3lane:
9982     case Intrinsic::arm_neon_vld4lane:
9983     case Intrinsic::arm_neon_vst1:
9984     case Intrinsic::arm_neon_vst2:
9985     case Intrinsic::arm_neon_vst3:
9986     case Intrinsic::arm_neon_vst4:
9987     case Intrinsic::arm_neon_vst2lane:
9988     case Intrinsic::arm_neon_vst3lane:
9989     case Intrinsic::arm_neon_vst4lane:
9990       return PerformVLDCombine(N, DCI);
9991     default: break;
9992     }
9993     break;
9994   }
9995   return SDValue();
9996 }
9997
9998 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9999                                                           EVT VT) const {
10000   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10001 }
10002
10003 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10004                                                        unsigned,
10005                                                        unsigned,
10006                                                        bool *Fast) const {
10007   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10008   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10009
10010   switch (VT.getSimpleVT().SimpleTy) {
10011   default:
10012     return false;
10013   case MVT::i8:
10014   case MVT::i16:
10015   case MVT::i32: {
10016     // Unaligned access can use (for example) LRDB, LRDH, LDR
10017     if (AllowsUnaligned) {
10018       if (Fast)
10019         *Fast = Subtarget->hasV7Ops();
10020       return true;
10021     }
10022     return false;
10023   }
10024   case MVT::f64:
10025   case MVT::v2f64: {
10026     // For any little-endian targets with neon, we can support unaligned ld/st
10027     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10028     // A big-endian target may also explicitly support unaligned accesses
10029     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10030       if (Fast)
10031         *Fast = true;
10032       return true;
10033     }
10034     return false;
10035   }
10036   }
10037 }
10038
10039 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10040                        unsigned AlignCheck) {
10041   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10042           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10043 }
10044
10045 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10046                                            unsigned DstAlign, unsigned SrcAlign,
10047                                            bool IsMemset, bool ZeroMemset,
10048                                            bool MemcpyStrSrc,
10049                                            MachineFunction &MF) const {
10050   const Function *F = MF.getFunction();
10051
10052   // See if we can use NEON instructions for this...
10053   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10054       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10055     bool Fast;
10056     if (Size >= 16 &&
10057         (memOpAlign(SrcAlign, DstAlign, 16) ||
10058          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10059       return MVT::v2f64;
10060     } else if (Size >= 8 &&
10061                (memOpAlign(SrcAlign, DstAlign, 8) ||
10062                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10063                  Fast))) {
10064       return MVT::f64;
10065     }
10066   }
10067
10068   // Lowering to i32/i16 if the size permits.
10069   if (Size >= 4)
10070     return MVT::i32;
10071   else if (Size >= 2)
10072     return MVT::i16;
10073
10074   // Let the target-independent logic figure it out.
10075   return MVT::Other;
10076 }
10077
10078 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10079   if (Val.getOpcode() != ISD::LOAD)
10080     return false;
10081
10082   EVT VT1 = Val.getValueType();
10083   if (!VT1.isSimple() || !VT1.isInteger() ||
10084       !VT2.isSimple() || !VT2.isInteger())
10085     return false;
10086
10087   switch (VT1.getSimpleVT().SimpleTy) {
10088   default: break;
10089   case MVT::i1:
10090   case MVT::i8:
10091   case MVT::i16:
10092     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10093     return true;
10094   }
10095
10096   return false;
10097 }
10098
10099 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10100   EVT VT = ExtVal.getValueType();
10101
10102   if (!isTypeLegal(VT))
10103     return false;
10104
10105   // Don't create a loadext if we can fold the extension into a wide/long
10106   // instruction.
10107   // If there's more than one user instruction, the loadext is desirable no
10108   // matter what.  There can be two uses by the same instruction.
10109   if (ExtVal->use_empty() ||
10110       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10111     return true;
10112
10113   SDNode *U = *ExtVal->use_begin();
10114   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10115        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10116     return false;
10117
10118   return true;
10119 }
10120
10121 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10122   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10123     return false;
10124
10125   if (!isTypeLegal(EVT::getEVT(Ty1)))
10126     return false;
10127
10128   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10129
10130   // Assuming the caller doesn't have a zeroext or signext return parameter,
10131   // truncation all the way down to i1 is valid.
10132   return true;
10133 }
10134
10135
10136 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10137   if (V < 0)
10138     return false;
10139
10140   unsigned Scale = 1;
10141   switch (VT.getSimpleVT().SimpleTy) {
10142   default: return false;
10143   case MVT::i1:
10144   case MVT::i8:
10145     // Scale == 1;
10146     break;
10147   case MVT::i16:
10148     // Scale == 2;
10149     Scale = 2;
10150     break;
10151   case MVT::i32:
10152     // Scale == 4;
10153     Scale = 4;
10154     break;
10155   }
10156
10157   if ((V & (Scale - 1)) != 0)
10158     return false;
10159   V /= Scale;
10160   return V == (V & ((1LL << 5) - 1));
10161 }
10162
10163 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10164                                       const ARMSubtarget *Subtarget) {
10165   bool isNeg = false;
10166   if (V < 0) {
10167     isNeg = true;
10168     V = - V;
10169   }
10170
10171   switch (VT.getSimpleVT().SimpleTy) {
10172   default: return false;
10173   case MVT::i1:
10174   case MVT::i8:
10175   case MVT::i16:
10176   case MVT::i32:
10177     // + imm12 or - imm8
10178     if (isNeg)
10179       return V == (V & ((1LL << 8) - 1));
10180     return V == (V & ((1LL << 12) - 1));
10181   case MVT::f32:
10182   case MVT::f64:
10183     // Same as ARM mode. FIXME: NEON?
10184     if (!Subtarget->hasVFP2())
10185       return false;
10186     if ((V & 3) != 0)
10187       return false;
10188     V >>= 2;
10189     return V == (V & ((1LL << 8) - 1));
10190   }
10191 }
10192
10193 /// isLegalAddressImmediate - Return true if the integer value can be used
10194 /// as the offset of the target addressing mode for load / store of the
10195 /// given type.
10196 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10197                                     const ARMSubtarget *Subtarget) {
10198   if (V == 0)
10199     return true;
10200
10201   if (!VT.isSimple())
10202     return false;
10203
10204   if (Subtarget->isThumb1Only())
10205     return isLegalT1AddressImmediate(V, VT);
10206   else if (Subtarget->isThumb2())
10207     return isLegalT2AddressImmediate(V, VT, Subtarget);
10208
10209   // ARM mode.
10210   if (V < 0)
10211     V = - V;
10212   switch (VT.getSimpleVT().SimpleTy) {
10213   default: return false;
10214   case MVT::i1:
10215   case MVT::i8:
10216   case MVT::i32:
10217     // +- imm12
10218     return V == (V & ((1LL << 12) - 1));
10219   case MVT::i16:
10220     // +- imm8
10221     return V == (V & ((1LL << 8) - 1));
10222   case MVT::f32:
10223   case MVT::f64:
10224     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10225       return false;
10226     if ((V & 3) != 0)
10227       return false;
10228     V >>= 2;
10229     return V == (V & ((1LL << 8) - 1));
10230   }
10231 }
10232
10233 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10234                                                       EVT VT) const {
10235   int Scale = AM.Scale;
10236   if (Scale < 0)
10237     return false;
10238
10239   switch (VT.getSimpleVT().SimpleTy) {
10240   default: return false;
10241   case MVT::i1:
10242   case MVT::i8:
10243   case MVT::i16:
10244   case MVT::i32:
10245     if (Scale == 1)
10246       return true;
10247     // r + r << imm
10248     Scale = Scale & ~1;
10249     return Scale == 2 || Scale == 4 || Scale == 8;
10250   case MVT::i64:
10251     // r + r
10252     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10253       return true;
10254     return false;
10255   case MVT::isVoid:
10256     // Note, we allow "void" uses (basically, uses that aren't loads or
10257     // stores), because arm allows folding a scale into many arithmetic
10258     // operations.  This should be made more precise and revisited later.
10259
10260     // Allow r << imm, but the imm has to be a multiple of two.
10261     if (Scale & 1) return false;
10262     return isPowerOf2_32(Scale);
10263   }
10264 }
10265
10266 /// isLegalAddressingMode - Return true if the addressing mode represented
10267 /// by AM is legal for this target, for a load/store of the specified type.
10268 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10269                                               Type *Ty) const {
10270   EVT VT = getValueType(Ty, true);
10271   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10272     return false;
10273
10274   // Can never fold addr of global into load/store.
10275   if (AM.BaseGV)
10276     return false;
10277
10278   switch (AM.Scale) {
10279   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10280     break;
10281   case 1:
10282     if (Subtarget->isThumb1Only())
10283       return false;
10284     // FALL THROUGH.
10285   default:
10286     // ARM doesn't support any R+R*scale+imm addr modes.
10287     if (AM.BaseOffs)
10288       return false;
10289
10290     if (!VT.isSimple())
10291       return false;
10292
10293     if (Subtarget->isThumb2())
10294       return isLegalT2ScaledAddressingMode(AM, VT);
10295
10296     int Scale = AM.Scale;
10297     switch (VT.getSimpleVT().SimpleTy) {
10298     default: return false;
10299     case MVT::i1:
10300     case MVT::i8:
10301     case MVT::i32:
10302       if (Scale < 0) Scale = -Scale;
10303       if (Scale == 1)
10304         return true;
10305       // r + r << imm
10306       return isPowerOf2_32(Scale & ~1);
10307     case MVT::i16:
10308     case MVT::i64:
10309       // r + r
10310       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10311         return true;
10312       return false;
10313
10314     case MVT::isVoid:
10315       // Note, we allow "void" uses (basically, uses that aren't loads or
10316       // stores), because arm allows folding a scale into many arithmetic
10317       // operations.  This should be made more precise and revisited later.
10318
10319       // Allow r << imm, but the imm has to be a multiple of two.
10320       if (Scale & 1) return false;
10321       return isPowerOf2_32(Scale);
10322     }
10323   }
10324   return true;
10325 }
10326
10327 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10328 /// icmp immediate, that is the target has icmp instructions which can compare
10329 /// a register against the immediate without having to materialize the
10330 /// immediate into a register.
10331 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10332   // Thumb2 and ARM modes can use cmn for negative immediates.
10333   if (!Subtarget->isThumb())
10334     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10335   if (Subtarget->isThumb2())
10336     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10337   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10338   return Imm >= 0 && Imm <= 255;
10339 }
10340
10341 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10342 /// *or sub* immediate, that is the target has add or sub instructions which can
10343 /// add a register with the immediate without having to materialize the
10344 /// immediate into a register.
10345 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10346   // Same encoding for add/sub, just flip the sign.
10347   int64_t AbsImm = std::abs(Imm);
10348   if (!Subtarget->isThumb())
10349     return ARM_AM::getSOImmVal(AbsImm) != -1;
10350   if (Subtarget->isThumb2())
10351     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10352   // Thumb1 only has 8-bit unsigned immediate.
10353   return AbsImm >= 0 && AbsImm <= 255;
10354 }
10355
10356 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10357                                       bool isSEXTLoad, SDValue &Base,
10358                                       SDValue &Offset, bool &isInc,
10359                                       SelectionDAG &DAG) {
10360   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10361     return false;
10362
10363   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10364     // AddressingMode 3
10365     Base = Ptr->getOperand(0);
10366     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10367       int RHSC = (int)RHS->getZExtValue();
10368       if (RHSC < 0 && RHSC > -256) {
10369         assert(Ptr->getOpcode() == ISD::ADD);
10370         isInc = false;
10371         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10372         return true;
10373       }
10374     }
10375     isInc = (Ptr->getOpcode() == ISD::ADD);
10376     Offset = Ptr->getOperand(1);
10377     return true;
10378   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10379     // AddressingMode 2
10380     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10381       int RHSC = (int)RHS->getZExtValue();
10382       if (RHSC < 0 && RHSC > -0x1000) {
10383         assert(Ptr->getOpcode() == ISD::ADD);
10384         isInc = false;
10385         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10386         Base = Ptr->getOperand(0);
10387         return true;
10388       }
10389     }
10390
10391     if (Ptr->getOpcode() == ISD::ADD) {
10392       isInc = true;
10393       ARM_AM::ShiftOpc ShOpcVal=
10394         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10395       if (ShOpcVal != ARM_AM::no_shift) {
10396         Base = Ptr->getOperand(1);
10397         Offset = Ptr->getOperand(0);
10398       } else {
10399         Base = Ptr->getOperand(0);
10400         Offset = Ptr->getOperand(1);
10401       }
10402       return true;
10403     }
10404
10405     isInc = (Ptr->getOpcode() == ISD::ADD);
10406     Base = Ptr->getOperand(0);
10407     Offset = Ptr->getOperand(1);
10408     return true;
10409   }
10410
10411   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10412   return false;
10413 }
10414
10415 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10416                                      bool isSEXTLoad, SDValue &Base,
10417                                      SDValue &Offset, bool &isInc,
10418                                      SelectionDAG &DAG) {
10419   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10420     return false;
10421
10422   Base = Ptr->getOperand(0);
10423   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10424     int RHSC = (int)RHS->getZExtValue();
10425     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10426       assert(Ptr->getOpcode() == ISD::ADD);
10427       isInc = false;
10428       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10429       return true;
10430     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10431       isInc = Ptr->getOpcode() == ISD::ADD;
10432       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10433       return true;
10434     }
10435   }
10436
10437   return false;
10438 }
10439
10440 /// getPreIndexedAddressParts - returns true by value, base pointer and
10441 /// offset pointer and addressing mode by reference if the node's address
10442 /// can be legally represented as pre-indexed load / store address.
10443 bool
10444 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10445                                              SDValue &Offset,
10446                                              ISD::MemIndexedMode &AM,
10447                                              SelectionDAG &DAG) const {
10448   if (Subtarget->isThumb1Only())
10449     return false;
10450
10451   EVT VT;
10452   SDValue Ptr;
10453   bool isSEXTLoad = false;
10454   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10455     Ptr = LD->getBasePtr();
10456     VT  = LD->getMemoryVT();
10457     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10458   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10459     Ptr = ST->getBasePtr();
10460     VT  = ST->getMemoryVT();
10461   } else
10462     return false;
10463
10464   bool isInc;
10465   bool isLegal = false;
10466   if (Subtarget->isThumb2())
10467     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10468                                        Offset, isInc, DAG);
10469   else
10470     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10471                                         Offset, isInc, DAG);
10472   if (!isLegal)
10473     return false;
10474
10475   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10476   return true;
10477 }
10478
10479 /// getPostIndexedAddressParts - returns true by value, base pointer and
10480 /// offset pointer and addressing mode by reference if this node can be
10481 /// combined with a load / store to form a post-indexed load / store.
10482 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10483                                                    SDValue &Base,
10484                                                    SDValue &Offset,
10485                                                    ISD::MemIndexedMode &AM,
10486                                                    SelectionDAG &DAG) const {
10487   if (Subtarget->isThumb1Only())
10488     return false;
10489
10490   EVT VT;
10491   SDValue Ptr;
10492   bool isSEXTLoad = false;
10493   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10494     VT  = LD->getMemoryVT();
10495     Ptr = LD->getBasePtr();
10496     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10497   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10498     VT  = ST->getMemoryVT();
10499     Ptr = ST->getBasePtr();
10500   } else
10501     return false;
10502
10503   bool isInc;
10504   bool isLegal = false;
10505   if (Subtarget->isThumb2())
10506     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10507                                        isInc, DAG);
10508   else
10509     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10510                                         isInc, DAG);
10511   if (!isLegal)
10512     return false;
10513
10514   if (Ptr != Base) {
10515     // Swap base ptr and offset to catch more post-index load / store when
10516     // it's legal. In Thumb2 mode, offset must be an immediate.
10517     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10518         !Subtarget->isThumb2())
10519       std::swap(Base, Offset);
10520
10521     // Post-indexed load / store update the base pointer.
10522     if (Ptr != Base)
10523       return false;
10524   }
10525
10526   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10527   return true;
10528 }
10529
10530 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10531                                                       APInt &KnownZero,
10532                                                       APInt &KnownOne,
10533                                                       const SelectionDAG &DAG,
10534                                                       unsigned Depth) const {
10535   unsigned BitWidth = KnownOne.getBitWidth();
10536   KnownZero = KnownOne = APInt(BitWidth, 0);
10537   switch (Op.getOpcode()) {
10538   default: break;
10539   case ARMISD::ADDC:
10540   case ARMISD::ADDE:
10541   case ARMISD::SUBC:
10542   case ARMISD::SUBE:
10543     // These nodes' second result is a boolean
10544     if (Op.getResNo() == 0)
10545       break;
10546     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10547     break;
10548   case ARMISD::CMOV: {
10549     // Bits are known zero/one if known on the LHS and RHS.
10550     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10551     if (KnownZero == 0 && KnownOne == 0) return;
10552
10553     APInt KnownZeroRHS, KnownOneRHS;
10554     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10555     KnownZero &= KnownZeroRHS;
10556     KnownOne  &= KnownOneRHS;
10557     return;
10558   }
10559   case ISD::INTRINSIC_W_CHAIN: {
10560     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10561     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10562     switch (IntID) {
10563     default: return;
10564     case Intrinsic::arm_ldaex:
10565     case Intrinsic::arm_ldrex: {
10566       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10567       unsigned MemBits = VT.getScalarType().getSizeInBits();
10568       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10569       return;
10570     }
10571     }
10572   }
10573   }
10574 }
10575
10576 //===----------------------------------------------------------------------===//
10577 //                           ARM Inline Assembly Support
10578 //===----------------------------------------------------------------------===//
10579
10580 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10581   // Looking for "rev" which is V6+.
10582   if (!Subtarget->hasV6Ops())
10583     return false;
10584
10585   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10586   std::string AsmStr = IA->getAsmString();
10587   SmallVector<StringRef, 4> AsmPieces;
10588   SplitString(AsmStr, AsmPieces, ";\n");
10589
10590   switch (AsmPieces.size()) {
10591   default: return false;
10592   case 1:
10593     AsmStr = AsmPieces[0];
10594     AsmPieces.clear();
10595     SplitString(AsmStr, AsmPieces, " \t,");
10596
10597     // rev $0, $1
10598     if (AsmPieces.size() == 3 &&
10599         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10600         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10601       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10602       if (Ty && Ty->getBitWidth() == 32)
10603         return IntrinsicLowering::LowerToByteSwap(CI);
10604     }
10605     break;
10606   }
10607
10608   return false;
10609 }
10610
10611 /// getConstraintType - Given a constraint letter, return the type of
10612 /// constraint it is for this target.
10613 ARMTargetLowering::ConstraintType
10614 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10615   if (Constraint.size() == 1) {
10616     switch (Constraint[0]) {
10617     default:  break;
10618     case 'l': return C_RegisterClass;
10619     case 'w': return C_RegisterClass;
10620     case 'h': return C_RegisterClass;
10621     case 'x': return C_RegisterClass;
10622     case 't': return C_RegisterClass;
10623     case 'j': return C_Other; // Constant for movw.
10624       // An address with a single base register. Due to the way we
10625       // currently handle addresses it is the same as an 'r' memory constraint.
10626     case 'Q': return C_Memory;
10627     }
10628   } else if (Constraint.size() == 2) {
10629     switch (Constraint[0]) {
10630     default: break;
10631     // All 'U+' constraints are addresses.
10632     case 'U': return C_Memory;
10633     }
10634   }
10635   return TargetLowering::getConstraintType(Constraint);
10636 }
10637
10638 /// Examine constraint type and operand type and determine a weight value.
10639 /// This object must already have been set up with the operand type
10640 /// and the current alternative constraint selected.
10641 TargetLowering::ConstraintWeight
10642 ARMTargetLowering::getSingleConstraintMatchWeight(
10643     AsmOperandInfo &info, const char *constraint) const {
10644   ConstraintWeight weight = CW_Invalid;
10645   Value *CallOperandVal = info.CallOperandVal;
10646     // If we don't have a value, we can't do a match,
10647     // but allow it at the lowest weight.
10648   if (!CallOperandVal)
10649     return CW_Default;
10650   Type *type = CallOperandVal->getType();
10651   // Look at the constraint type.
10652   switch (*constraint) {
10653   default:
10654     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10655     break;
10656   case 'l':
10657     if (type->isIntegerTy()) {
10658       if (Subtarget->isThumb())
10659         weight = CW_SpecificReg;
10660       else
10661         weight = CW_Register;
10662     }
10663     break;
10664   case 'w':
10665     if (type->isFloatingPointTy())
10666       weight = CW_Register;
10667     break;
10668   }
10669   return weight;
10670 }
10671
10672 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10673 RCPair
10674 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10675                                                 const std::string &Constraint,
10676                                                 MVT VT) const {
10677   if (Constraint.size() == 1) {
10678     // GCC ARM Constraint Letters
10679     switch (Constraint[0]) {
10680     case 'l': // Low regs or general regs.
10681       if (Subtarget->isThumb())
10682         return RCPair(0U, &ARM::tGPRRegClass);
10683       return RCPair(0U, &ARM::GPRRegClass);
10684     case 'h': // High regs or no regs.
10685       if (Subtarget->isThumb())
10686         return RCPair(0U, &ARM::hGPRRegClass);
10687       break;
10688     case 'r':
10689       if (Subtarget->isThumb1Only())
10690         return RCPair(0U, &ARM::tGPRRegClass);
10691       return RCPair(0U, &ARM::GPRRegClass);
10692     case 'w':
10693       if (VT == MVT::Other)
10694         break;
10695       if (VT == MVT::f32)
10696         return RCPair(0U, &ARM::SPRRegClass);
10697       if (VT.getSizeInBits() == 64)
10698         return RCPair(0U, &ARM::DPRRegClass);
10699       if (VT.getSizeInBits() == 128)
10700         return RCPair(0U, &ARM::QPRRegClass);
10701       break;
10702     case 'x':
10703       if (VT == MVT::Other)
10704         break;
10705       if (VT == MVT::f32)
10706         return RCPair(0U, &ARM::SPR_8RegClass);
10707       if (VT.getSizeInBits() == 64)
10708         return RCPair(0U, &ARM::DPR_8RegClass);
10709       if (VT.getSizeInBits() == 128)
10710         return RCPair(0U, &ARM::QPR_8RegClass);
10711       break;
10712     case 't':
10713       if (VT == MVT::f32)
10714         return RCPair(0U, &ARM::SPRRegClass);
10715       break;
10716     }
10717   }
10718   if (StringRef("{cc}").equals_lower(Constraint))
10719     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10720
10721   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10722 }
10723
10724 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10725 /// vector.  If it is invalid, don't add anything to Ops.
10726 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10727                                                      std::string &Constraint,
10728                                                      std::vector<SDValue>&Ops,
10729                                                      SelectionDAG &DAG) const {
10730   SDValue Result;
10731
10732   // Currently only support length 1 constraints.
10733   if (Constraint.length() != 1) return;
10734
10735   char ConstraintLetter = Constraint[0];
10736   switch (ConstraintLetter) {
10737   default: break;
10738   case 'j':
10739   case 'I': case 'J': case 'K': case 'L':
10740   case 'M': case 'N': case 'O':
10741     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10742     if (!C)
10743       return;
10744
10745     int64_t CVal64 = C->getSExtValue();
10746     int CVal = (int) CVal64;
10747     // None of these constraints allow values larger than 32 bits.  Check
10748     // that the value fits in an int.
10749     if (CVal != CVal64)
10750       return;
10751
10752     switch (ConstraintLetter) {
10753       case 'j':
10754         // Constant suitable for movw, must be between 0 and
10755         // 65535.
10756         if (Subtarget->hasV6T2Ops())
10757           if (CVal >= 0 && CVal <= 65535)
10758             break;
10759         return;
10760       case 'I':
10761         if (Subtarget->isThumb1Only()) {
10762           // This must be a constant between 0 and 255, for ADD
10763           // immediates.
10764           if (CVal >= 0 && CVal <= 255)
10765             break;
10766         } else if (Subtarget->isThumb2()) {
10767           // A constant that can be used as an immediate value in a
10768           // data-processing instruction.
10769           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10770             break;
10771         } else {
10772           // A constant that can be used as an immediate value in a
10773           // data-processing instruction.
10774           if (ARM_AM::getSOImmVal(CVal) != -1)
10775             break;
10776         }
10777         return;
10778
10779       case 'J':
10780         if (Subtarget->isThumb()) {  // FIXME thumb2
10781           // This must be a constant between -255 and -1, for negated ADD
10782           // immediates. This can be used in GCC with an "n" modifier that
10783           // prints the negated value, for use with SUB instructions. It is
10784           // not useful otherwise but is implemented for compatibility.
10785           if (CVal >= -255 && CVal <= -1)
10786             break;
10787         } else {
10788           // This must be a constant between -4095 and 4095. It is not clear
10789           // what this constraint is intended for. Implemented for
10790           // compatibility with GCC.
10791           if (CVal >= -4095 && CVal <= 4095)
10792             break;
10793         }
10794         return;
10795
10796       case 'K':
10797         if (Subtarget->isThumb1Only()) {
10798           // A 32-bit value where only one byte has a nonzero value. Exclude
10799           // zero to match GCC. This constraint is used by GCC internally for
10800           // constants that can be loaded with a move/shift combination.
10801           // It is not useful otherwise but is implemented for compatibility.
10802           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10803             break;
10804         } else if (Subtarget->isThumb2()) {
10805           // A constant whose bitwise inverse can be used as an immediate
10806           // value in a data-processing instruction. This can be used in GCC
10807           // with a "B" modifier that prints the inverted value, for use with
10808           // BIC and MVN instructions. It is not useful otherwise but is
10809           // implemented for compatibility.
10810           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10811             break;
10812         } else {
10813           // A constant whose bitwise inverse can be used as an immediate
10814           // value in a data-processing instruction. This can be used in GCC
10815           // with a "B" modifier that prints the inverted value, for use with
10816           // BIC and MVN instructions. It is not useful otherwise but is
10817           // implemented for compatibility.
10818           if (ARM_AM::getSOImmVal(~CVal) != -1)
10819             break;
10820         }
10821         return;
10822
10823       case 'L':
10824         if (Subtarget->isThumb1Only()) {
10825           // This must be a constant between -7 and 7,
10826           // for 3-operand ADD/SUB immediate instructions.
10827           if (CVal >= -7 && CVal < 7)
10828             break;
10829         } else if (Subtarget->isThumb2()) {
10830           // A constant whose negation can be used as an immediate value in a
10831           // data-processing instruction. This can be used in GCC with an "n"
10832           // modifier that prints the negated value, for use with SUB
10833           // instructions. It is not useful otherwise but is implemented for
10834           // compatibility.
10835           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10836             break;
10837         } else {
10838           // A constant whose negation can be used as an immediate value in a
10839           // data-processing instruction. This can be used in GCC with an "n"
10840           // modifier that prints the negated value, for use with SUB
10841           // instructions. It is not useful otherwise but is implemented for
10842           // compatibility.
10843           if (ARM_AM::getSOImmVal(-CVal) != -1)
10844             break;
10845         }
10846         return;
10847
10848       case 'M':
10849         if (Subtarget->isThumb()) { // FIXME thumb2
10850           // This must be a multiple of 4 between 0 and 1020, for
10851           // ADD sp + immediate.
10852           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10853             break;
10854         } else {
10855           // A power of two or a constant between 0 and 32.  This is used in
10856           // GCC for the shift amount on shifted register operands, but it is
10857           // useful in general for any shift amounts.
10858           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10859             break;
10860         }
10861         return;
10862
10863       case 'N':
10864         if (Subtarget->isThumb()) {  // FIXME thumb2
10865           // This must be a constant between 0 and 31, for shift amounts.
10866           if (CVal >= 0 && CVal <= 31)
10867             break;
10868         }
10869         return;
10870
10871       case 'O':
10872         if (Subtarget->isThumb()) {  // FIXME thumb2
10873           // This must be a multiple of 4 between -508 and 508, for
10874           // ADD/SUB sp = sp + immediate.
10875           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10876             break;
10877         }
10878         return;
10879     }
10880     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
10881     break;
10882   }
10883
10884   if (Result.getNode()) {
10885     Ops.push_back(Result);
10886     return;
10887   }
10888   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10889 }
10890
10891 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10892   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10893   unsigned Opcode = Op->getOpcode();
10894   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10895          "Invalid opcode for Div/Rem lowering");
10896   bool isSigned = (Opcode == ISD::SDIVREM);
10897   EVT VT = Op->getValueType(0);
10898   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10899
10900   RTLIB::Libcall LC;
10901   switch (VT.getSimpleVT().SimpleTy) {
10902   default: llvm_unreachable("Unexpected request for libcall!");
10903   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10904   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10905   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10906   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10907   }
10908
10909   SDValue InChain = DAG.getEntryNode();
10910
10911   TargetLowering::ArgListTy Args;
10912   TargetLowering::ArgListEntry Entry;
10913   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10914     EVT ArgVT = Op->getOperand(i).getValueType();
10915     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10916     Entry.Node = Op->getOperand(i);
10917     Entry.Ty = ArgTy;
10918     Entry.isSExt = isSigned;
10919     Entry.isZExt = !isSigned;
10920     Args.push_back(Entry);
10921   }
10922
10923   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10924                                          getPointerTy());
10925
10926   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10927
10928   SDLoc dl(Op);
10929   TargetLowering::CallLoweringInfo CLI(DAG);
10930   CLI.setDebugLoc(dl).setChain(InChain)
10931     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10932     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10933
10934   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10935   return CallInfo.first;
10936 }
10937
10938 SDValue
10939 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10940   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10941   SDLoc DL(Op);
10942
10943   // Get the inputs.
10944   SDValue Chain = Op.getOperand(0);
10945   SDValue Size  = Op.getOperand(1);
10946
10947   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10948                               DAG.getConstant(2, DL, MVT::i32));
10949
10950   SDValue Flag;
10951   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10952   Flag = Chain.getValue(1);
10953
10954   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10955   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10956
10957   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10958   Chain = NewSP.getValue(1);
10959
10960   SDValue Ops[2] = { NewSP, Chain };
10961   return DAG.getMergeValues(Ops, DL);
10962 }
10963
10964 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10965   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10966          "Unexpected type for custom-lowering FP_EXTEND");
10967
10968   RTLIB::Libcall LC;
10969   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10970
10971   SDValue SrcVal = Op.getOperand(0);
10972   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10973                      /*isSigned*/ false, SDLoc(Op)).first;
10974 }
10975
10976 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10977   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10978          Subtarget->isFPOnlySP() &&
10979          "Unexpected type for custom-lowering FP_ROUND");
10980
10981   RTLIB::Libcall LC;
10982   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10983
10984   SDValue SrcVal = Op.getOperand(0);
10985   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10986                      /*isSigned*/ false, SDLoc(Op)).first;
10987 }
10988
10989 bool
10990 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10991   // The ARM target isn't yet aware of offsets.
10992   return false;
10993 }
10994
10995 bool ARM::isBitFieldInvertedMask(unsigned v) {
10996   if (v == 0xffffffff)
10997     return false;
10998
10999   // there can be 1's on either or both "outsides", all the "inside"
11000   // bits must be 0's
11001   return isShiftedMask_32(~v);
11002 }
11003
11004 /// isFPImmLegal - Returns true if the target can instruction select the
11005 /// specified FP immediate natively. If false, the legalizer will
11006 /// materialize the FP immediate as a load from a constant pool.
11007 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11008   if (!Subtarget->hasVFP3())
11009     return false;
11010   if (VT == MVT::f32)
11011     return ARM_AM::getFP32Imm(Imm) != -1;
11012   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11013     return ARM_AM::getFP64Imm(Imm) != -1;
11014   return false;
11015 }
11016
11017 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11018 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11019 /// specified in the intrinsic calls.
11020 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11021                                            const CallInst &I,
11022                                            unsigned Intrinsic) const {
11023   switch (Intrinsic) {
11024   case Intrinsic::arm_neon_vld1:
11025   case Intrinsic::arm_neon_vld2:
11026   case Intrinsic::arm_neon_vld3:
11027   case Intrinsic::arm_neon_vld4:
11028   case Intrinsic::arm_neon_vld2lane:
11029   case Intrinsic::arm_neon_vld3lane:
11030   case Intrinsic::arm_neon_vld4lane: {
11031     Info.opc = ISD::INTRINSIC_W_CHAIN;
11032     // Conservatively set memVT to the entire set of vectors loaded.
11033     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11034     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11035     Info.ptrVal = I.getArgOperand(0);
11036     Info.offset = 0;
11037     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11038     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11039     Info.vol = false; // volatile loads with NEON intrinsics not supported
11040     Info.readMem = true;
11041     Info.writeMem = false;
11042     return true;
11043   }
11044   case Intrinsic::arm_neon_vst1:
11045   case Intrinsic::arm_neon_vst2:
11046   case Intrinsic::arm_neon_vst3:
11047   case Intrinsic::arm_neon_vst4:
11048   case Intrinsic::arm_neon_vst2lane:
11049   case Intrinsic::arm_neon_vst3lane:
11050   case Intrinsic::arm_neon_vst4lane: {
11051     Info.opc = ISD::INTRINSIC_VOID;
11052     // Conservatively set memVT to the entire set of vectors stored.
11053     unsigned NumElts = 0;
11054     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11055       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11056       if (!ArgTy->isVectorTy())
11057         break;
11058       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11059     }
11060     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11061     Info.ptrVal = I.getArgOperand(0);
11062     Info.offset = 0;
11063     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11064     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11065     Info.vol = false; // volatile stores with NEON intrinsics not supported
11066     Info.readMem = false;
11067     Info.writeMem = true;
11068     return true;
11069   }
11070   case Intrinsic::arm_ldaex:
11071   case Intrinsic::arm_ldrex: {
11072     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11073     Info.opc = ISD::INTRINSIC_W_CHAIN;
11074     Info.memVT = MVT::getVT(PtrTy->getElementType());
11075     Info.ptrVal = I.getArgOperand(0);
11076     Info.offset = 0;
11077     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11078     Info.vol = true;
11079     Info.readMem = true;
11080     Info.writeMem = false;
11081     return true;
11082   }
11083   case Intrinsic::arm_stlex:
11084   case Intrinsic::arm_strex: {
11085     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11086     Info.opc = ISD::INTRINSIC_W_CHAIN;
11087     Info.memVT = MVT::getVT(PtrTy->getElementType());
11088     Info.ptrVal = I.getArgOperand(1);
11089     Info.offset = 0;
11090     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11091     Info.vol = true;
11092     Info.readMem = false;
11093     Info.writeMem = true;
11094     return true;
11095   }
11096   case Intrinsic::arm_stlexd:
11097   case Intrinsic::arm_strexd: {
11098     Info.opc = ISD::INTRINSIC_W_CHAIN;
11099     Info.memVT = MVT::i64;
11100     Info.ptrVal = I.getArgOperand(2);
11101     Info.offset = 0;
11102     Info.align = 8;
11103     Info.vol = true;
11104     Info.readMem = false;
11105     Info.writeMem = true;
11106     return true;
11107   }
11108   case Intrinsic::arm_ldaexd:
11109   case Intrinsic::arm_ldrexd: {
11110     Info.opc = ISD::INTRINSIC_W_CHAIN;
11111     Info.memVT = MVT::i64;
11112     Info.ptrVal = I.getArgOperand(0);
11113     Info.offset = 0;
11114     Info.align = 8;
11115     Info.vol = true;
11116     Info.readMem = true;
11117     Info.writeMem = false;
11118     return true;
11119   }
11120   default:
11121     break;
11122   }
11123
11124   return false;
11125 }
11126
11127 /// \brief Returns true if it is beneficial to convert a load of a constant
11128 /// to just the constant itself.
11129 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11130                                                           Type *Ty) const {
11131   assert(Ty->isIntegerTy());
11132
11133   unsigned Bits = Ty->getPrimitiveSizeInBits();
11134   if (Bits == 0 || Bits > 32)
11135     return false;
11136   return true;
11137 }
11138
11139 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11140
11141 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11142                                         ARM_MB::MemBOpt Domain) const {
11143   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11144
11145   // First, if the target has no DMB, see what fallback we can use.
11146   if (!Subtarget->hasDataBarrier()) {
11147     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11148     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11149     // here.
11150     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11151       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11152       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11153                         Builder.getInt32(0), Builder.getInt32(7),
11154                         Builder.getInt32(10), Builder.getInt32(5)};
11155       return Builder.CreateCall(MCR, args);
11156     } else {
11157       // Instead of using barriers, atomic accesses on these subtargets use
11158       // libcalls.
11159       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11160     }
11161   } else {
11162     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11163     // Only a full system barrier exists in the M-class architectures.
11164     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11165     Constant *CDomain = Builder.getInt32(Domain);
11166     return Builder.CreateCall(DMB, CDomain);
11167   }
11168 }
11169
11170 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11171 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11172                                          AtomicOrdering Ord, bool IsStore,
11173                                          bool IsLoad) const {
11174   if (!getInsertFencesForAtomic())
11175     return nullptr;
11176
11177   switch (Ord) {
11178   case NotAtomic:
11179   case Unordered:
11180     llvm_unreachable("Invalid fence: unordered/non-atomic");
11181   case Monotonic:
11182   case Acquire:
11183     return nullptr; // Nothing to do
11184   case SequentiallyConsistent:
11185     if (!IsStore)
11186       return nullptr; // Nothing to do
11187     /*FALLTHROUGH*/
11188   case Release:
11189   case AcquireRelease:
11190     if (Subtarget->isSwift())
11191       return makeDMB(Builder, ARM_MB::ISHST);
11192     // FIXME: add a comment with a link to documentation justifying this.
11193     else
11194       return makeDMB(Builder, ARM_MB::ISH);
11195   }
11196   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11197 }
11198
11199 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11200                                           AtomicOrdering Ord, bool IsStore,
11201                                           bool IsLoad) const {
11202   if (!getInsertFencesForAtomic())
11203     return nullptr;
11204
11205   switch (Ord) {
11206   case NotAtomic:
11207   case Unordered:
11208     llvm_unreachable("Invalid fence: unordered/not-atomic");
11209   case Monotonic:
11210   case Release:
11211     return nullptr; // Nothing to do
11212   case Acquire:
11213   case AcquireRelease:
11214   case SequentiallyConsistent:
11215     return makeDMB(Builder, ARM_MB::ISH);
11216   }
11217   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11218 }
11219
11220 // Loads and stores less than 64-bits are already atomic; ones above that
11221 // are doomed anyway, so defer to the default libcall and blame the OS when
11222 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11223 // anything for those.
11224 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11225   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11226   return (Size == 64) && !Subtarget->isMClass();
11227 }
11228
11229 // Loads and stores less than 64-bits are already atomic; ones above that
11230 // are doomed anyway, so defer to the default libcall and blame the OS when
11231 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11232 // anything for those.
11233 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11234 // guarantee, see DDI0406C ARM architecture reference manual,
11235 // sections A8.8.72-74 LDRD)
11236 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11237   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11238   return (Size == 64) && !Subtarget->isMClass();
11239 }
11240
11241 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11242 // and up to 64 bits on the non-M profiles
11243 TargetLoweringBase::AtomicRMWExpansionKind
11244 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11245   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11246   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11247              ? AtomicRMWExpansionKind::LLSC
11248              : AtomicRMWExpansionKind::None;
11249 }
11250
11251 // This has so far only been implemented for MachO.
11252 bool ARMTargetLowering::useLoadStackGuardNode() const {
11253   return Subtarget->isTargetMachO();
11254 }
11255
11256 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11257                                                   unsigned &Cost) const {
11258   // If we do not have NEON, vector types are not natively supported.
11259   if (!Subtarget->hasNEON())
11260     return false;
11261
11262   // Floating point values and vector values map to the same register file.
11263   // Therefore, althought we could do a store extract of a vector type, this is
11264   // better to leave at float as we have more freedom in the addressing mode for
11265   // those.
11266   if (VectorTy->isFPOrFPVectorTy())
11267     return false;
11268
11269   // If the index is unknown at compile time, this is very expensive to lower
11270   // and it is not possible to combine the store with the extract.
11271   if (!isa<ConstantInt>(Idx))
11272     return false;
11273
11274   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11275   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11276   // We can do a store + vector extract on any vector that fits perfectly in a D
11277   // or Q register.
11278   if (BitWidth == 64 || BitWidth == 128) {
11279     Cost = 0;
11280     return true;
11281   }
11282   return false;
11283 }
11284
11285 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11286                                          AtomicOrdering Ord) const {
11287   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11288   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11289   bool IsAcquire = isAtLeastAcquire(Ord);
11290
11291   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11292   // intrinsic must return {i32, i32} and we have to recombine them into a
11293   // single i64 here.
11294   if (ValTy->getPrimitiveSizeInBits() == 64) {
11295     Intrinsic::ID Int =
11296         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11297     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11298
11299     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11300     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11301
11302     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11303     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11304     if (!Subtarget->isLittle())
11305       std::swap (Lo, Hi);
11306     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11307     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11308     return Builder.CreateOr(
11309         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11310   }
11311
11312   Type *Tys[] = { Addr->getType() };
11313   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11314   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11315
11316   return Builder.CreateTruncOrBitCast(
11317       Builder.CreateCall(Ldrex, Addr),
11318       cast<PointerType>(Addr->getType())->getElementType());
11319 }
11320
11321 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11322                                                Value *Addr,
11323                                                AtomicOrdering Ord) const {
11324   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11325   bool IsRelease = isAtLeastRelease(Ord);
11326
11327   // Since the intrinsics must have legal type, the i64 intrinsics take two
11328   // parameters: "i32, i32". We must marshal Val into the appropriate form
11329   // before the call.
11330   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11331     Intrinsic::ID Int =
11332         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11333     Function *Strex = Intrinsic::getDeclaration(M, Int);
11334     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11335
11336     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11337     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11338     if (!Subtarget->isLittle())
11339       std::swap (Lo, Hi);
11340     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11341     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11342   }
11343
11344   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11345   Type *Tys[] = { Addr->getType() };
11346   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11347
11348   return Builder.CreateCall2(
11349       Strex, Builder.CreateZExtOrBitCast(
11350                  Val, Strex->getFunctionType()->getParamType(0)),
11351       Addr);
11352 }
11353
11354 enum HABaseType {
11355   HA_UNKNOWN = 0,
11356   HA_FLOAT,
11357   HA_DOUBLE,
11358   HA_VECT64,
11359   HA_VECT128
11360 };
11361
11362 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11363                                    uint64_t &Members) {
11364   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11365     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11366       uint64_t SubMembers = 0;
11367       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11368         return false;
11369       Members += SubMembers;
11370     }
11371   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11372     uint64_t SubMembers = 0;
11373     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11374       return false;
11375     Members += SubMembers * AT->getNumElements();
11376   } else if (Ty->isFloatTy()) {
11377     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11378       return false;
11379     Members = 1;
11380     Base = HA_FLOAT;
11381   } else if (Ty->isDoubleTy()) {
11382     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11383       return false;
11384     Members = 1;
11385     Base = HA_DOUBLE;
11386   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11387     Members = 1;
11388     switch (Base) {
11389     case HA_FLOAT:
11390     case HA_DOUBLE:
11391       return false;
11392     case HA_VECT64:
11393       return VT->getBitWidth() == 64;
11394     case HA_VECT128:
11395       return VT->getBitWidth() == 128;
11396     case HA_UNKNOWN:
11397       switch (VT->getBitWidth()) {
11398       case 64:
11399         Base = HA_VECT64;
11400         return true;
11401       case 128:
11402         Base = HA_VECT128;
11403         return true;
11404       default:
11405         return false;
11406       }
11407     }
11408   }
11409
11410   return (Members > 0 && Members <= 4);
11411 }
11412
11413 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11414 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11415 /// passing according to AAPCS rules.
11416 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11417     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11418   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11419       CallingConv::ARM_AAPCS_VFP)
11420     return false;
11421
11422   HABaseType Base = HA_UNKNOWN;
11423   uint64_t Members = 0;
11424   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11425   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11426
11427   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11428   return IsHA || IsIntArray;
11429 }