Cleanup, remove unused return value
[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() && !TM.Options.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 (!TM.Options.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   if (Subtarget->hasNEON()) {
430     addDRTypeForNEON(MVT::v2f32);
431     addDRTypeForNEON(MVT::v8i8);
432     addDRTypeForNEON(MVT::v4i16);
433     addDRTypeForNEON(MVT::v2i32);
434     addDRTypeForNEON(MVT::v1i64);
435
436     addQRTypeForNEON(MVT::v4f32);
437     addQRTypeForNEON(MVT::v2f64);
438     addQRTypeForNEON(MVT::v16i8);
439     addQRTypeForNEON(MVT::v8i16);
440     addQRTypeForNEON(MVT::v4i32);
441     addQRTypeForNEON(MVT::v2i64);
442
443     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
444     // neither Neon nor VFP support any arithmetic operations on it.
445     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
446     // supported for v4f32.
447     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
448     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
449     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
450     // FIXME: Code duplication: FDIV and FREM are expanded always, see
451     // ARMTargetLowering::addTypeForNEON method for details.
452     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
453     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
454     // FIXME: Create unittest.
455     // In another words, find a way when "copysign" appears in DAG with vector
456     // operands.
457     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
458     // FIXME: Code duplication: SETCC has custom operation action, see
459     // ARMTargetLowering::addTypeForNEON method for details.
460     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
461     // FIXME: Create unittest for FNEG and for FABS.
462     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
463     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
464     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
465     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
466     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
467     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
468     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
469     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
470     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
471     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
472     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
473     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
474     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
475     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
476     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
477     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
478     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
479     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
480     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
481
482     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
483     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
484     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
485     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
486     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
487     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
488     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
489     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
490     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
491     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
492     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
493     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
494     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
495     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
496     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
497
498     // Mark v2f32 intrinsics.
499     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
500     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
501     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
502     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
503     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
504     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
505     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
506     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
507     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
508     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
509     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
510     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
511     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
512     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
513     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
514
515     // Neon does not support some operations on v1i64 and v2i64 types.
516     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
517     // Custom handling for some quad-vector types to detect VMULL.
518     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
519     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
520     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
521     // Custom handling for some vector types to avoid expensive expansions
522     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
523     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
524     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
525     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
526     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
527     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
528     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
529     // a destination type that is wider than the source, and nor does
530     // it have a FP_TO_[SU]INT instruction with a narrower destination than
531     // source.
532     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
533     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
534     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
535     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
536
537     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
538     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
539
540     // NEON does not have single instruction CTPOP for vectors with element
541     // types wider than 8-bits.  However, custom lowering can leverage the
542     // v8i8/v16i8 vcnt instruction.
543     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
544     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
545     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
546     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
547
548     // NEON only has FMA instructions as of VFP4.
549     if (!Subtarget->hasVFP4()) {
550       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
551       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
552     }
553
554     setTargetDAGCombine(ISD::INTRINSIC_VOID);
555     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
556     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
557     setTargetDAGCombine(ISD::SHL);
558     setTargetDAGCombine(ISD::SRL);
559     setTargetDAGCombine(ISD::SRA);
560     setTargetDAGCombine(ISD::SIGN_EXTEND);
561     setTargetDAGCombine(ISD::ZERO_EXTEND);
562     setTargetDAGCombine(ISD::ANY_EXTEND);
563     setTargetDAGCombine(ISD::SELECT_CC);
564     setTargetDAGCombine(ISD::BUILD_VECTOR);
565     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
566     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
567     setTargetDAGCombine(ISD::STORE);
568     setTargetDAGCombine(ISD::FP_TO_SINT);
569     setTargetDAGCombine(ISD::FP_TO_UINT);
570     setTargetDAGCombine(ISD::FDIV);
571     setTargetDAGCombine(ISD::LOAD);
572
573     // It is legal to extload from v4i8 to v4i16 or v4i32.
574     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
575                    MVT::v2i32}) {
576       for (MVT VT : MVT::integer_vector_valuetypes()) {
577         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
578         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
579         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
580       }
581     }
582   }
583
584   // ARM and Thumb2 support UMLAL/SMLAL.
585   if (!Subtarget->isThumb1Only())
586     setTargetDAGCombine(ISD::ADDC);
587
588   if (Subtarget->isFPOnlySP()) {
589     // When targetting a floating-point unit with only single-precision
590     // operations, f64 is legal for the few double-precision instructions which
591     // are present However, no double-precision operations other than moves,
592     // loads and stores are provided by the hardware.
593     setOperationAction(ISD::FADD,       MVT::f64, Expand);
594     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
595     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
596     setOperationAction(ISD::FMA,        MVT::f64, Expand);
597     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
598     setOperationAction(ISD::FREM,       MVT::f64, Expand);
599     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
600     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
601     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
602     setOperationAction(ISD::FABS,       MVT::f64, Expand);
603     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
604     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
605     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
606     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
607     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
608     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
609     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
610     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
611     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
612     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
613     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
614     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
615     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
616     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
617     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
618     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
619     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
620     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
621     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
622     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
623     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
624     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
625     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
626   }
627
628   computeRegisterProperties(Subtarget->getRegisterInfo());
629
630   // ARM does not have floating-point extending loads.
631   for (MVT VT : MVT::fp_valuetypes()) {
632     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
633     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
634   }
635
636   // ... or truncating stores
637   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
638   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
639   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
640
641   // ARM does not have i1 sign extending load.
642   for (MVT VT : MVT::integer_valuetypes())
643     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
644
645   // ARM supports all 4 flavors of integer indexed load / store.
646   if (!Subtarget->isThumb1Only()) {
647     for (unsigned im = (unsigned)ISD::PRE_INC;
648          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
649       setIndexedLoadAction(im,  MVT::i1,  Legal);
650       setIndexedLoadAction(im,  MVT::i8,  Legal);
651       setIndexedLoadAction(im,  MVT::i16, Legal);
652       setIndexedLoadAction(im,  MVT::i32, Legal);
653       setIndexedStoreAction(im, MVT::i1,  Legal);
654       setIndexedStoreAction(im, MVT::i8,  Legal);
655       setIndexedStoreAction(im, MVT::i16, Legal);
656       setIndexedStoreAction(im, MVT::i32, Legal);
657     }
658   }
659
660   setOperationAction(ISD::SADDO, MVT::i32, Custom);
661   setOperationAction(ISD::UADDO, MVT::i32, Custom);
662   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
663   setOperationAction(ISD::USUBO, MVT::i32, Custom);
664
665   // i64 operation support.
666   setOperationAction(ISD::MUL,     MVT::i64, Expand);
667   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
668   if (Subtarget->isThumb1Only()) {
669     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
670     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
671   }
672   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
673       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
674     setOperationAction(ISD::MULHS, MVT::i32, Expand);
675
676   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
677   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
678   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
679   setOperationAction(ISD::SRL,       MVT::i64, Custom);
680   setOperationAction(ISD::SRA,       MVT::i64, Custom);
681
682   if (!Subtarget->isThumb1Only()) {
683     // FIXME: We should do this for Thumb1 as well.
684     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
685     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
686     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
687     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
688   }
689
690   // ARM does not have ROTL.
691   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
692   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
693   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
694   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
695     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
696
697   // These just redirect to CTTZ and CTLZ on ARM.
698   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
699   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
700
701   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
702
703   // Only ARMv6 has BSWAP.
704   if (!Subtarget->hasV6Ops())
705     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
706
707   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
708       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
709     // These are expanded into libcalls if the cpu doesn't have HW divider.
710     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
711     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
712   }
713
714   // FIXME: Also set divmod for SREM on EABI
715   setOperationAction(ISD::SREM,  MVT::i32, Expand);
716   setOperationAction(ISD::UREM,  MVT::i32, Expand);
717   // Register based DivRem for AEABI (RTABI 4.2)
718   if (Subtarget->isTargetAEABI()) {
719     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
720     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
721     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
722     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
723     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
724     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
725     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
726     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
727
728     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
729     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
730     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
731     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
732     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
733     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
734     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
735     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
736
737     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
738     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
739   } else {
740     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
741     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
742   }
743
744   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
745   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
746   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
747   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
748   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
749
750   setOperationAction(ISD::TRAP, MVT::Other, Legal);
751
752   // Use the default implementation.
753   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
754   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
755   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
756   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
757   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
758   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
759
760   if (!Subtarget->isTargetMachO()) {
761     // Non-MachO platforms may return values in these registers via the
762     // personality function.
763     setExceptionPointerRegister(ARM::R0);
764     setExceptionSelectorRegister(ARM::R1);
765   }
766
767   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
768     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
769   else
770     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
771
772   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
773   // the default expansion. If we are targeting a single threaded system,
774   // then set them all for expand so we can lower them later into their
775   // non-atomic form.
776   if (TM.Options.ThreadModel == ThreadModel::Single)
777     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
778   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
779     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
780     // to ldrex/strex loops already.
781     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
782
783     // On v8, we have particularly efficient implementations of atomic fences
784     // if they can be combined with nearby atomic loads and stores.
785     if (!Subtarget->hasV8Ops()) {
786       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
787       setInsertFencesForAtomic(true);
788     }
789   } else {
790     // If there's anything we can use as a barrier, go through custom lowering
791     // for ATOMIC_FENCE.
792     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
793                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
794
795     // Set them all for expansion, which will force libcalls.
796     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
801     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
802     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
803     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
804     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
805     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
806     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
807     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
808     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
809     // Unordered/Monotonic case.
810     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
811     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
812   }
813
814   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
815
816   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
817   if (!Subtarget->hasV6Ops()) {
818     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
819     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
820   }
821   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
822
823   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
824       !Subtarget->isThumb1Only()) {
825     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
826     // iff target supports vfp2.
827     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
828     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
829   }
830
831   // We want to custom lower some of our intrinsics.
832   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
833   if (Subtarget->isTargetDarwin()) {
834     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
835     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
836     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
837   }
838
839   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
840   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
841   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
842   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
843   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
844   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
845   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
846   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
847   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
848
849   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
850   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
851   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
852   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
853   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
854
855   // We don't support sin/cos/fmod/copysign/pow
856   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
857   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
858   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
859   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
860   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
861   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
862   setOperationAction(ISD::FREM,      MVT::f64, Expand);
863   setOperationAction(ISD::FREM,      MVT::f32, Expand);
864   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
865       !Subtarget->isThumb1Only()) {
866     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
867     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
868   }
869   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
870   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
871
872   if (!Subtarget->hasVFP4()) {
873     setOperationAction(ISD::FMA, MVT::f64, Expand);
874     setOperationAction(ISD::FMA, MVT::f32, Expand);
875   }
876
877   // Various VFP goodness
878   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
879     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
880     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
881       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
882       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
883     }
884
885     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
886     if (!Subtarget->hasFP16()) {
887       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
888       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
889     }
890   }
891
892   // Combine sin / cos into one node or libcall if possible.
893   if (Subtarget->hasSinCos()) {
894     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
895     setLibcallName(RTLIB::SINCOS_F64, "sincos");
896     if (Subtarget->getTargetTriple().isiOS()) {
897       // For iOS, we don't want to the normal expansion of a libcall to
898       // sincos. We want to issue a libcall to __sincos_stret.
899       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
900       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
901     }
902   }
903
904   // FP-ARMv8 implements a lot of rounding-like FP operations.
905   if (Subtarget->hasFPARMv8()) {
906     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
907     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
908     setOperationAction(ISD::FROUND, MVT::f32, Legal);
909     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
910     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
911     setOperationAction(ISD::FRINT, MVT::f32, Legal);
912     if (!Subtarget->isFPOnlySP()) {
913       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
914       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
915       setOperationAction(ISD::FROUND, MVT::f64, Legal);
916       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
917       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
918       setOperationAction(ISD::FRINT, MVT::f64, Legal);
919     }
920   }
921   // We have target-specific dag combine patterns for the following nodes:
922   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
923   setTargetDAGCombine(ISD::ADD);
924   setTargetDAGCombine(ISD::SUB);
925   setTargetDAGCombine(ISD::MUL);
926   setTargetDAGCombine(ISD::AND);
927   setTargetDAGCombine(ISD::OR);
928   setTargetDAGCombine(ISD::XOR);
929
930   if (Subtarget->hasV6Ops())
931     setTargetDAGCombine(ISD::SRL);
932
933   setStackPointerRegisterToSaveRestore(ARM::SP);
934
935   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
936       !Subtarget->hasVFP2())
937     setSchedulingPreference(Sched::RegPressure);
938   else
939     setSchedulingPreference(Sched::Hybrid);
940
941   //// temporary - rewrite interface to use type
942   MaxStoresPerMemset = 8;
943   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
944   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
945   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
946   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
947   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
948
949   // On ARM arguments smaller than 4 bytes are extended, so all arguments
950   // are at least 4 bytes aligned.
951   setMinStackArgumentAlignment(4);
952
953   // Prefer likely predicted branches to selects on out-of-order cores.
954   PredictableSelectIsExpensive = Subtarget->isLikeA9();
955
956   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
957 }
958
959 // FIXME: It might make sense to define the representative register class as the
960 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
961 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
962 // SPR's representative would be DPR_VFP2. This should work well if register
963 // pressure tracking were modified such that a register use would increment the
964 // pressure of the register class's representative and all of it's super
965 // classes' representatives transitively. We have not implemented this because
966 // of the difficulty prior to coalescing of modeling operand register classes
967 // due to the common occurrence of cross class copies and subregister insertions
968 // and extractions.
969 std::pair<const TargetRegisterClass *, uint8_t>
970 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
971                                            MVT VT) const {
972   const TargetRegisterClass *RRC = nullptr;
973   uint8_t Cost = 1;
974   switch (VT.SimpleTy) {
975   default:
976     return TargetLowering::findRepresentativeClass(TRI, VT);
977   // Use DPR as representative register class for all floating point
978   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
979   // the cost is 1 for both f32 and f64.
980   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
981   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
982     RRC = &ARM::DPRRegClass;
983     // When NEON is used for SP, only half of the register file is available
984     // because operations that define both SP and DP results will be constrained
985     // to the VFP2 class (D0-D15). We currently model this constraint prior to
986     // coalescing by double-counting the SP regs. See the FIXME above.
987     if (Subtarget->useNEONForSinglePrecisionFP())
988       Cost = 2;
989     break;
990   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
991   case MVT::v4f32: case MVT::v2f64:
992     RRC = &ARM::DPRRegClass;
993     Cost = 2;
994     break;
995   case MVT::v4i64:
996     RRC = &ARM::DPRRegClass;
997     Cost = 4;
998     break;
999   case MVT::v8i64:
1000     RRC = &ARM::DPRRegClass;
1001     Cost = 8;
1002     break;
1003   }
1004   return std::make_pair(RRC, Cost);
1005 }
1006
1007 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1008   switch (Opcode) {
1009   default: return nullptr;
1010   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1011   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1012   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1013   case ARMISD::CALL:          return "ARMISD::CALL";
1014   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1015   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1016   case ARMISD::tCALL:         return "ARMISD::tCALL";
1017   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1018   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1019   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1020   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1021   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1022   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1023   case ARMISD::CMP:           return "ARMISD::CMP";
1024   case ARMISD::CMN:           return "ARMISD::CMN";
1025   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1026   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1027   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1028   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1029   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1030
1031   case ARMISD::CMOV:          return "ARMISD::CMOV";
1032
1033   case ARMISD::RBIT:          return "ARMISD::RBIT";
1034
1035   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1036   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1037   case ARMISD::RRX:           return "ARMISD::RRX";
1038
1039   case ARMISD::ADDC:          return "ARMISD::ADDC";
1040   case ARMISD::ADDE:          return "ARMISD::ADDE";
1041   case ARMISD::SUBC:          return "ARMISD::SUBC";
1042   case ARMISD::SUBE:          return "ARMISD::SUBE";
1043
1044   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1045   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1046
1047   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1048   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1049
1050   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1051
1052   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1053
1054   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1055
1056   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1057
1058   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1059
1060   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1061
1062   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1063   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1064   case ARMISD::VCGE:          return "ARMISD::VCGE";
1065   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1066   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1067   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1068   case ARMISD::VCGT:          return "ARMISD::VCGT";
1069   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1070   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1071   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1072   case ARMISD::VTST:          return "ARMISD::VTST";
1073
1074   case ARMISD::VSHL:          return "ARMISD::VSHL";
1075   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1076   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1077   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1078   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1079   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1080   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1081   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1082   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1083   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1084   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1085   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1086   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1087   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1088   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1089   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1090   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1091   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1092   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1093   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1094   case ARMISD::VDUP:          return "ARMISD::VDUP";
1095   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1096   case ARMISD::VEXT:          return "ARMISD::VEXT";
1097   case ARMISD::VREV64:        return "ARMISD::VREV64";
1098   case ARMISD::VREV32:        return "ARMISD::VREV32";
1099   case ARMISD::VREV16:        return "ARMISD::VREV16";
1100   case ARMISD::VZIP:          return "ARMISD::VZIP";
1101   case ARMISD::VUZP:          return "ARMISD::VUZP";
1102   case ARMISD::VTRN:          return "ARMISD::VTRN";
1103   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1104   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1105   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1106   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1107   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1108   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1109   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1110   case ARMISD::FMAX:          return "ARMISD::FMAX";
1111   case ARMISD::FMIN:          return "ARMISD::FMIN";
1112   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1113   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1114   case ARMISD::BFI:           return "ARMISD::BFI";
1115   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1116   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1117   case ARMISD::VBSL:          return "ARMISD::VBSL";
1118   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1119   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1120   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1121   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1122   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1123   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1124   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1125   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1126   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1127   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1128   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1129   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1130   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1131   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1132   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1133   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1134   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1135   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1136   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1137   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1138   }
1139 }
1140
1141 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1142   if (!VT.isVector()) return getPointerTy();
1143   return VT.changeVectorElementTypeToInteger();
1144 }
1145
1146 /// getRegClassFor - Return the register class that should be used for the
1147 /// specified value type.
1148 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1149   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1150   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1151   // load / store 4 to 8 consecutive D registers.
1152   if (Subtarget->hasNEON()) {
1153     if (VT == MVT::v4i64)
1154       return &ARM::QQPRRegClass;
1155     if (VT == MVT::v8i64)
1156       return &ARM::QQQQPRRegClass;
1157   }
1158   return TargetLowering::getRegClassFor(VT);
1159 }
1160
1161 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1162 // source/dest is aligned and the copy size is large enough. We therefore want
1163 // to align such objects passed to memory intrinsics.
1164 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1165                                                unsigned &PrefAlign) const {
1166   if (!isa<MemIntrinsic>(CI))
1167     return false;
1168   MinSize = 8;
1169   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1170   // cycle faster than 4-byte aligned LDM.
1171   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1172   return true;
1173 }
1174
1175 // Create a fast isel object.
1176 FastISel *
1177 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1178                                   const TargetLibraryInfo *libInfo) const {
1179   return ARM::createFastISel(funcInfo, libInfo);
1180 }
1181
1182 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1183   unsigned NumVals = N->getNumValues();
1184   if (!NumVals)
1185     return Sched::RegPressure;
1186
1187   for (unsigned i = 0; i != NumVals; ++i) {
1188     EVT VT = N->getValueType(i);
1189     if (VT == MVT::Glue || VT == MVT::Other)
1190       continue;
1191     if (VT.isFloatingPoint() || VT.isVector())
1192       return Sched::ILP;
1193   }
1194
1195   if (!N->isMachineOpcode())
1196     return Sched::RegPressure;
1197
1198   // Load are scheduled for latency even if there instruction itinerary
1199   // is not available.
1200   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1201   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1202
1203   if (MCID.getNumDefs() == 0)
1204     return Sched::RegPressure;
1205   if (!Itins->isEmpty() &&
1206       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1207     return Sched::ILP;
1208
1209   return Sched::RegPressure;
1210 }
1211
1212 //===----------------------------------------------------------------------===//
1213 // Lowering Code
1214 //===----------------------------------------------------------------------===//
1215
1216 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1217 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1218   switch (CC) {
1219   default: llvm_unreachable("Unknown condition code!");
1220   case ISD::SETNE:  return ARMCC::NE;
1221   case ISD::SETEQ:  return ARMCC::EQ;
1222   case ISD::SETGT:  return ARMCC::GT;
1223   case ISD::SETGE:  return ARMCC::GE;
1224   case ISD::SETLT:  return ARMCC::LT;
1225   case ISD::SETLE:  return ARMCC::LE;
1226   case ISD::SETUGT: return ARMCC::HI;
1227   case ISD::SETUGE: return ARMCC::HS;
1228   case ISD::SETULT: return ARMCC::LO;
1229   case ISD::SETULE: return ARMCC::LS;
1230   }
1231 }
1232
1233 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1234 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1235                         ARMCC::CondCodes &CondCode2) {
1236   CondCode2 = ARMCC::AL;
1237   switch (CC) {
1238   default: llvm_unreachable("Unknown FP condition!");
1239   case ISD::SETEQ:
1240   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1241   case ISD::SETGT:
1242   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1243   case ISD::SETGE:
1244   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1245   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1246   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1247   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1248   case ISD::SETO:   CondCode = ARMCC::VC; break;
1249   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1250   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1251   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1252   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1253   case ISD::SETLT:
1254   case ISD::SETULT: CondCode = ARMCC::LT; break;
1255   case ISD::SETLE:
1256   case ISD::SETULE: CondCode = ARMCC::LE; break;
1257   case ISD::SETNE:
1258   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1259   }
1260 }
1261
1262 //===----------------------------------------------------------------------===//
1263 //                      Calling Convention Implementation
1264 //===----------------------------------------------------------------------===//
1265
1266 #include "ARMGenCallingConv.inc"
1267
1268 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1269 /// account presence of floating point hardware and calling convention
1270 /// limitations, such as support for variadic functions.
1271 CallingConv::ID
1272 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1273                                            bool isVarArg) const {
1274   switch (CC) {
1275   default:
1276     llvm_unreachable("Unsupported calling convention");
1277   case CallingConv::ARM_AAPCS:
1278   case CallingConv::ARM_APCS:
1279   case CallingConv::GHC:
1280     return CC;
1281   case CallingConv::ARM_AAPCS_VFP:
1282     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1283   case CallingConv::C:
1284     if (!Subtarget->isAAPCS_ABI())
1285       return CallingConv::ARM_APCS;
1286     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1287              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1288              !isVarArg)
1289       return CallingConv::ARM_AAPCS_VFP;
1290     else
1291       return CallingConv::ARM_AAPCS;
1292   case CallingConv::Fast:
1293     if (!Subtarget->isAAPCS_ABI()) {
1294       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1295         return CallingConv::Fast;
1296       return CallingConv::ARM_APCS;
1297     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1298       return CallingConv::ARM_AAPCS_VFP;
1299     else
1300       return CallingConv::ARM_AAPCS;
1301   }
1302 }
1303
1304 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1305 /// CallingConvention.
1306 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1307                                                  bool Return,
1308                                                  bool isVarArg) const {
1309   switch (getEffectiveCallingConv(CC, isVarArg)) {
1310   default:
1311     llvm_unreachable("Unsupported calling convention");
1312   case CallingConv::ARM_APCS:
1313     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1314   case CallingConv::ARM_AAPCS:
1315     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1316   case CallingConv::ARM_AAPCS_VFP:
1317     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1318   case CallingConv::Fast:
1319     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1320   case CallingConv::GHC:
1321     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1322   }
1323 }
1324
1325 /// LowerCallResult - Lower the result values of a call into the
1326 /// appropriate copies out of appropriate physical registers.
1327 SDValue
1328 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1329                                    CallingConv::ID CallConv, bool isVarArg,
1330                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1331                                    SDLoc dl, SelectionDAG &DAG,
1332                                    SmallVectorImpl<SDValue> &InVals,
1333                                    bool isThisReturn, SDValue ThisVal) const {
1334
1335   // Assign locations to each value returned by this call.
1336   SmallVector<CCValAssign, 16> RVLocs;
1337   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1338                     *DAG.getContext(), Call);
1339   CCInfo.AnalyzeCallResult(Ins,
1340                            CCAssignFnForNode(CallConv, /* Return*/ true,
1341                                              isVarArg));
1342
1343   // Copy all of the result registers out of their specified physreg.
1344   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1345     CCValAssign VA = RVLocs[i];
1346
1347     // Pass 'this' value directly from the argument to return value, to avoid
1348     // reg unit interference
1349     if (i == 0 && isThisReturn) {
1350       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1351              "unexpected return calling convention register assignment");
1352       InVals.push_back(ThisVal);
1353       continue;
1354     }
1355
1356     SDValue Val;
1357     if (VA.needsCustom()) {
1358       // Handle f64 or half of a v2f64.
1359       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1360                                       InFlag);
1361       Chain = Lo.getValue(1);
1362       InFlag = Lo.getValue(2);
1363       VA = RVLocs[++i]; // skip ahead to next loc
1364       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1365                                       InFlag);
1366       Chain = Hi.getValue(1);
1367       InFlag = Hi.getValue(2);
1368       if (!Subtarget->isLittle())
1369         std::swap (Lo, Hi);
1370       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1371
1372       if (VA.getLocVT() == MVT::v2f64) {
1373         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1374         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1375                           DAG.getConstant(0, MVT::i32));
1376
1377         VA = RVLocs[++i]; // skip ahead to next loc
1378         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1379         Chain = Lo.getValue(1);
1380         InFlag = Lo.getValue(2);
1381         VA = RVLocs[++i]; // skip ahead to next loc
1382         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1383         Chain = Hi.getValue(1);
1384         InFlag = Hi.getValue(2);
1385         if (!Subtarget->isLittle())
1386           std::swap (Lo, Hi);
1387         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1388         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1389                           DAG.getConstant(1, MVT::i32));
1390       }
1391     } else {
1392       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1393                                InFlag);
1394       Chain = Val.getValue(1);
1395       InFlag = Val.getValue(2);
1396     }
1397
1398     switch (VA.getLocInfo()) {
1399     default: llvm_unreachable("Unknown loc info!");
1400     case CCValAssign::Full: break;
1401     case CCValAssign::BCvt:
1402       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1403       break;
1404     }
1405
1406     InVals.push_back(Val);
1407   }
1408
1409   return Chain;
1410 }
1411
1412 /// LowerMemOpCallTo - Store the argument to the stack.
1413 SDValue
1414 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1415                                     SDValue StackPtr, SDValue Arg,
1416                                     SDLoc dl, SelectionDAG &DAG,
1417                                     const CCValAssign &VA,
1418                                     ISD::ArgFlagsTy Flags) const {
1419   unsigned LocMemOffset = VA.getLocMemOffset();
1420   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1421   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1422   return DAG.getStore(Chain, dl, Arg, PtrOff,
1423                       MachinePointerInfo::getStack(LocMemOffset),
1424                       false, false, 0);
1425 }
1426
1427 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1428                                          SDValue Chain, SDValue &Arg,
1429                                          RegsToPassVector &RegsToPass,
1430                                          CCValAssign &VA, CCValAssign &NextVA,
1431                                          SDValue &StackPtr,
1432                                          SmallVectorImpl<SDValue> &MemOpChains,
1433                                          ISD::ArgFlagsTy Flags) const {
1434
1435   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1436                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1437   unsigned id = Subtarget->isLittle() ? 0 : 1;
1438   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1439
1440   if (NextVA.isRegLoc())
1441     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1442   else {
1443     assert(NextVA.isMemLoc());
1444     if (!StackPtr.getNode())
1445       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1446
1447     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1448                                            dl, DAG, NextVA,
1449                                            Flags));
1450   }
1451 }
1452
1453 /// LowerCall - Lowering a call into a callseq_start <-
1454 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1455 /// nodes.
1456 SDValue
1457 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1458                              SmallVectorImpl<SDValue> &InVals) const {
1459   SelectionDAG &DAG                     = CLI.DAG;
1460   SDLoc &dl                          = CLI.DL;
1461   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1462   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1463   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1464   SDValue Chain                         = CLI.Chain;
1465   SDValue Callee                        = CLI.Callee;
1466   bool &isTailCall                      = CLI.IsTailCall;
1467   CallingConv::ID CallConv              = CLI.CallConv;
1468   bool doesNotRet                       = CLI.DoesNotReturn;
1469   bool isVarArg                         = CLI.IsVarArg;
1470
1471   MachineFunction &MF = DAG.getMachineFunction();
1472   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1473   bool isThisReturn   = false;
1474   bool isSibCall      = false;
1475
1476   // Disable tail calls if they're not supported.
1477   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1478     isTailCall = false;
1479
1480   if (isTailCall) {
1481     // Check if it's really possible to do a tail call.
1482     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1483                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1484                                                    Outs, OutVals, Ins, DAG);
1485     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1486       report_fatal_error("failed to perform tail call elimination on a call "
1487                          "site marked musttail");
1488     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1489     // detected sibcalls.
1490     if (isTailCall) {
1491       ++NumTailCalls;
1492       isSibCall = true;
1493     }
1494   }
1495
1496   // Analyze operands of the call, assigning locations to each operand.
1497   SmallVector<CCValAssign, 16> ArgLocs;
1498   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1499                     *DAG.getContext(), Call);
1500   CCInfo.AnalyzeCallOperands(Outs,
1501                              CCAssignFnForNode(CallConv, /* Return*/ false,
1502                                                isVarArg));
1503
1504   // Get a count of how many bytes are to be pushed on the stack.
1505   unsigned NumBytes = CCInfo.getNextStackOffset();
1506
1507   // For tail calls, memory operands are available in our caller's stack.
1508   if (isSibCall)
1509     NumBytes = 0;
1510
1511   // Adjust the stack pointer for the new arguments...
1512   // These operations are automatically eliminated by the prolog/epilog pass
1513   if (!isSibCall)
1514     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1515                                  dl);
1516
1517   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1518
1519   RegsToPassVector RegsToPass;
1520   SmallVector<SDValue, 8> MemOpChains;
1521
1522   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1523   // of tail call optimization, arguments are handled later.
1524   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1525        i != e;
1526        ++i, ++realArgIdx) {
1527     CCValAssign &VA = ArgLocs[i];
1528     SDValue Arg = OutVals[realArgIdx];
1529     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1530     bool isByVal = Flags.isByVal();
1531
1532     // Promote the value if needed.
1533     switch (VA.getLocInfo()) {
1534     default: llvm_unreachable("Unknown loc info!");
1535     case CCValAssign::Full: break;
1536     case CCValAssign::SExt:
1537       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1538       break;
1539     case CCValAssign::ZExt:
1540       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1541       break;
1542     case CCValAssign::AExt:
1543       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1544       break;
1545     case CCValAssign::BCvt:
1546       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1547       break;
1548     }
1549
1550     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1551     if (VA.needsCustom()) {
1552       if (VA.getLocVT() == MVT::v2f64) {
1553         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1554                                   DAG.getConstant(0, MVT::i32));
1555         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1556                                   DAG.getConstant(1, MVT::i32));
1557
1558         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1559                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1560
1561         VA = ArgLocs[++i]; // skip ahead to next loc
1562         if (VA.isRegLoc()) {
1563           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1564                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1565         } else {
1566           assert(VA.isMemLoc());
1567
1568           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1569                                                  dl, DAG, VA, Flags));
1570         }
1571       } else {
1572         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1573                          StackPtr, MemOpChains, Flags);
1574       }
1575     } else if (VA.isRegLoc()) {
1576       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1577         assert(VA.getLocVT() == MVT::i32 &&
1578                "unexpected calling convention register assignment");
1579         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1580                "unexpected use of 'returned'");
1581         isThisReturn = true;
1582       }
1583       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1584     } else if (isByVal) {
1585       assert(VA.isMemLoc());
1586       unsigned offset = 0;
1587
1588       // True if this byval aggregate will be split between registers
1589       // and memory.
1590       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1591       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1592
1593       if (CurByValIdx < ByValArgsCount) {
1594
1595         unsigned RegBegin, RegEnd;
1596         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1597
1598         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1599         unsigned int i, j;
1600         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1601           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1602           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1603           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1604                                      MachinePointerInfo(),
1605                                      false, false, false,
1606                                      DAG.InferPtrAlignment(AddArg));
1607           MemOpChains.push_back(Load.getValue(1));
1608           RegsToPass.push_back(std::make_pair(j, Load));
1609         }
1610
1611         // If parameter size outsides register area, "offset" value
1612         // helps us to calculate stack slot for remained part properly.
1613         offset = RegEnd - RegBegin;
1614
1615         CCInfo.nextInRegsParam();
1616       }
1617
1618       if (Flags.getByValSize() > 4*offset) {
1619         unsigned LocMemOffset = VA.getLocMemOffset();
1620         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1621         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1622                                   StkPtrOff);
1623         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1624         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1625         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1626                                            MVT::i32);
1627         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1628
1629         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1630         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1631         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1632                                           Ops));
1633       }
1634     } else if (!isSibCall) {
1635       assert(VA.isMemLoc());
1636
1637       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1638                                              dl, DAG, VA, Flags));
1639     }
1640   }
1641
1642   if (!MemOpChains.empty())
1643     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1644
1645   // Build a sequence of copy-to-reg nodes chained together with token chain
1646   // and flag operands which copy the outgoing args into the appropriate regs.
1647   SDValue InFlag;
1648   // Tail call byval lowering might overwrite argument registers so in case of
1649   // tail call optimization the copies to registers are lowered later.
1650   if (!isTailCall)
1651     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1652       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1653                                RegsToPass[i].second, InFlag);
1654       InFlag = Chain.getValue(1);
1655     }
1656
1657   // For tail calls lower the arguments to the 'real' stack slot.
1658   if (isTailCall) {
1659     // Force all the incoming stack arguments to be loaded from the stack
1660     // before any new outgoing arguments are stored to the stack, because the
1661     // outgoing stack slots may alias the incoming argument stack slots, and
1662     // the alias isn't otherwise explicit. This is slightly more conservative
1663     // than necessary, because it means that each store effectively depends
1664     // on every argument instead of just those arguments it would clobber.
1665
1666     // Do not flag preceding copytoreg stuff together with the following stuff.
1667     InFlag = SDValue();
1668     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1669       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1670                                RegsToPass[i].second, InFlag);
1671       InFlag = Chain.getValue(1);
1672     }
1673     InFlag = SDValue();
1674   }
1675
1676   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1677   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1678   // node so that legalize doesn't hack it.
1679   bool isDirect = false;
1680   bool isARMFunc = false;
1681   bool isLocalARMFunc = false;
1682   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1683
1684   if (EnableARMLongCalls) {
1685     assert((Subtarget->isTargetWindows() ||
1686             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1687            "long-calls with non-static relocation model!");
1688     // Handle a global address or an external symbol. If it's not one of
1689     // those, the target's already in a register, so we don't need to do
1690     // anything extra.
1691     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1692       const GlobalValue *GV = G->getGlobal();
1693       // Create a constant pool entry for the callee address
1694       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1695       ARMConstantPoolValue *CPV =
1696         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1697
1698       // Get the address of the callee into a register
1699       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1700       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1701       Callee = DAG.getLoad(getPointerTy(), dl,
1702                            DAG.getEntryNode(), CPAddr,
1703                            MachinePointerInfo::getConstantPool(),
1704                            false, false, false, 0);
1705     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1706       const char *Sym = S->getSymbol();
1707
1708       // Create a constant pool entry for the callee address
1709       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1710       ARMConstantPoolValue *CPV =
1711         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1712                                       ARMPCLabelIndex, 0);
1713       // Get the address of the callee into a register
1714       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1715       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1716       Callee = DAG.getLoad(getPointerTy(), dl,
1717                            DAG.getEntryNode(), CPAddr,
1718                            MachinePointerInfo::getConstantPool(),
1719                            false, false, false, 0);
1720     }
1721   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1722     const GlobalValue *GV = G->getGlobal();
1723     isDirect = true;
1724     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1725     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1726                    getTargetMachine().getRelocationModel() != Reloc::Static;
1727     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1728     // ARM call to a local ARM function is predicable.
1729     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1730     // tBX takes a register source operand.
1731     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1732       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1733       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1734                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1735                                                       0, ARMII::MO_NONLAZY));
1736       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1737                            MachinePointerInfo::getGOT(), false, false, true, 0);
1738     } else if (Subtarget->isTargetCOFF()) {
1739       assert(Subtarget->isTargetWindows() &&
1740              "Windows is the only supported COFF target");
1741       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1742                                  ? ARMII::MO_DLLIMPORT
1743                                  : ARMII::MO_NO_FLAG;
1744       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1745                                           TargetFlags);
1746       if (GV->hasDLLImportStorageClass())
1747         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1748                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1749                                          Callee), MachinePointerInfo::getGOT(),
1750                              false, false, false, 0);
1751     } else {
1752       // On ELF targets for PIC code, direct calls should go through the PLT
1753       unsigned OpFlags = 0;
1754       if (Subtarget->isTargetELF() &&
1755           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1756         OpFlags = ARMII::MO_PLT;
1757       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1758     }
1759   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1760     isDirect = true;
1761     bool isStub = Subtarget->isTargetMachO() &&
1762                   getTargetMachine().getRelocationModel() != Reloc::Static;
1763     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1764     // tBX takes a register source operand.
1765     const char *Sym = S->getSymbol();
1766     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1767       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1768       ARMConstantPoolValue *CPV =
1769         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1770                                       ARMPCLabelIndex, 4);
1771       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1772       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1773       Callee = DAG.getLoad(getPointerTy(), dl,
1774                            DAG.getEntryNode(), CPAddr,
1775                            MachinePointerInfo::getConstantPool(),
1776                            false, false, false, 0);
1777       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1778       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1779                            getPointerTy(), Callee, PICLabel);
1780     } else {
1781       unsigned OpFlags = 0;
1782       // On ELF targets for PIC code, direct calls should go through the PLT
1783       if (Subtarget->isTargetELF() &&
1784                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1785         OpFlags = ARMII::MO_PLT;
1786       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1787     }
1788   }
1789
1790   // FIXME: handle tail calls differently.
1791   unsigned CallOpc;
1792   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1793   if (Subtarget->isThumb()) {
1794     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1795       CallOpc = ARMISD::CALL_NOLINK;
1796     else
1797       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1798   } else {
1799     if (!isDirect && !Subtarget->hasV5TOps())
1800       CallOpc = ARMISD::CALL_NOLINK;
1801     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1802                // Emit regular call when code size is the priority
1803                !HasMinSizeAttr)
1804       // "mov lr, pc; b _foo" to avoid confusing the RSP
1805       CallOpc = ARMISD::CALL_NOLINK;
1806     else
1807       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1808   }
1809
1810   std::vector<SDValue> Ops;
1811   Ops.push_back(Chain);
1812   Ops.push_back(Callee);
1813
1814   // Add argument registers to the end of the list so that they are known live
1815   // into the call.
1816   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1817     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1818                                   RegsToPass[i].second.getValueType()));
1819
1820   // Add a register mask operand representing the call-preserved registers.
1821   if (!isTailCall) {
1822     const uint32_t *Mask;
1823     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1824     if (isThisReturn) {
1825       // For 'this' returns, use the R0-preserving mask if applicable
1826       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1827       if (!Mask) {
1828         // Set isThisReturn to false if the calling convention is not one that
1829         // allows 'returned' to be modeled in this way, so LowerCallResult does
1830         // not try to pass 'this' straight through
1831         isThisReturn = false;
1832         Mask = ARI->getCallPreservedMask(MF, CallConv);
1833       }
1834     } else
1835       Mask = ARI->getCallPreservedMask(MF, CallConv);
1836
1837     assert(Mask && "Missing call preserved mask for calling convention");
1838     Ops.push_back(DAG.getRegisterMask(Mask));
1839   }
1840
1841   if (InFlag.getNode())
1842     Ops.push_back(InFlag);
1843
1844   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1845   if (isTailCall)
1846     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1847
1848   // Returns a chain and a flag for retval copy to use.
1849   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1850   InFlag = Chain.getValue(1);
1851
1852   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1853                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1854   if (!Ins.empty())
1855     InFlag = Chain.getValue(1);
1856
1857   // Handle result values, copying them out of physregs into vregs that we
1858   // return.
1859   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1860                          InVals, isThisReturn,
1861                          isThisReturn ? OutVals[0] : SDValue());
1862 }
1863
1864 /// HandleByVal - Every parameter *after* a byval parameter is passed
1865 /// on the stack.  Remember the next parameter register to allocate,
1866 /// and then confiscate the rest of the parameter registers to insure
1867 /// this.
1868 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1869                                     unsigned Align) const {
1870   assert((State->getCallOrPrologue() == Prologue ||
1871           State->getCallOrPrologue() == Call) &&
1872          "unhandled ParmContext");
1873
1874   // Byval (as with any stack) slots are always at least 4 byte aligned.
1875   Align = std::max(Align, 4U);
1876
1877   unsigned Reg = State->AllocateReg(GPRArgRegs);
1878   if (!Reg)
1879     return;
1880
1881   unsigned AlignInRegs = Align / 4;
1882   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1883   for (unsigned i = 0; i < Waste; ++i)
1884     Reg = State->AllocateReg(GPRArgRegs);
1885
1886   if (!Reg)
1887     return;
1888
1889   unsigned Excess = 4 * (ARM::R4 - Reg);
1890
1891   // Special case when NSAA != SP and parameter size greater than size of
1892   // all remained GPR regs. In that case we can't split parameter, we must
1893   // send it to stack. We also must set NCRN to R4, so waste all
1894   // remained registers.
1895   const unsigned NSAAOffset = State->getNextStackOffset();
1896   if (NSAAOffset != 0 && Size > Excess) {
1897     while (State->AllocateReg(GPRArgRegs))
1898       ;
1899     return;
1900   }
1901
1902   // First register for byval parameter is the first register that wasn't
1903   // allocated before this method call, so it would be "reg".
1904   // If parameter is small enough to be saved in range [reg, r4), then
1905   // the end (first after last) register would be reg + param-size-in-regs,
1906   // else parameter would be splitted between registers and stack,
1907   // end register would be r4 in this case.
1908   unsigned ByValRegBegin = Reg;
1909   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1910   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1911   // Note, first register is allocated in the beginning of function already,
1912   // allocate remained amount of registers we need.
1913   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1914     State->AllocateReg(GPRArgRegs);
1915   // A byval parameter that is split between registers and memory needs its
1916   // size truncated here.
1917   // In the case where the entire structure fits in registers, we set the
1918   // size in memory to zero.
1919   Size = std::max<int>(Size - Excess, 0);
1920 }
1921
1922
1923 /// MatchingStackOffset - Return true if the given stack call argument is
1924 /// already available in the same position (relatively) of the caller's
1925 /// incoming argument stack.
1926 static
1927 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1928                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1929                          const TargetInstrInfo *TII) {
1930   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1931   int FI = INT_MAX;
1932   if (Arg.getOpcode() == ISD::CopyFromReg) {
1933     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1934     if (!TargetRegisterInfo::isVirtualRegister(VR))
1935       return false;
1936     MachineInstr *Def = MRI->getVRegDef(VR);
1937     if (!Def)
1938       return false;
1939     if (!Flags.isByVal()) {
1940       if (!TII->isLoadFromStackSlot(Def, FI))
1941         return false;
1942     } else {
1943       return false;
1944     }
1945   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1946     if (Flags.isByVal())
1947       // ByVal argument is passed in as a pointer but it's now being
1948       // dereferenced. e.g.
1949       // define @foo(%struct.X* %A) {
1950       //   tail call @bar(%struct.X* byval %A)
1951       // }
1952       return false;
1953     SDValue Ptr = Ld->getBasePtr();
1954     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1955     if (!FINode)
1956       return false;
1957     FI = FINode->getIndex();
1958   } else
1959     return false;
1960
1961   assert(FI != INT_MAX);
1962   if (!MFI->isFixedObjectIndex(FI))
1963     return false;
1964   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1965 }
1966
1967 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1968 /// for tail call optimization. Targets which want to do tail call
1969 /// optimization should implement this function.
1970 bool
1971 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1972                                                      CallingConv::ID CalleeCC,
1973                                                      bool isVarArg,
1974                                                      bool isCalleeStructRet,
1975                                                      bool isCallerStructRet,
1976                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1977                                     const SmallVectorImpl<SDValue> &OutVals,
1978                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1979                                                      SelectionDAG& DAG) const {
1980   const Function *CallerF = DAG.getMachineFunction().getFunction();
1981   CallingConv::ID CallerCC = CallerF->getCallingConv();
1982   bool CCMatch = CallerCC == CalleeCC;
1983
1984   // Look for obvious safe cases to perform tail call optimization that do not
1985   // require ABI changes. This is what gcc calls sibcall.
1986
1987   // Do not sibcall optimize vararg calls unless the call site is not passing
1988   // any arguments.
1989   if (isVarArg && !Outs.empty())
1990     return false;
1991
1992   // Exception-handling functions need a special set of instructions to indicate
1993   // a return to the hardware. Tail-calling another function would probably
1994   // break this.
1995   if (CallerF->hasFnAttribute("interrupt"))
1996     return false;
1997
1998   // Also avoid sibcall optimization if either caller or callee uses struct
1999   // return semantics.
2000   if (isCalleeStructRet || isCallerStructRet)
2001     return false;
2002
2003   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2004   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2005   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2006   // support in the assembler and linker to be used. This would need to be
2007   // fixed to fully support tail calls in Thumb1.
2008   //
2009   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2010   // LR.  This means if we need to reload LR, it takes an extra instructions,
2011   // which outweighs the value of the tail call; but here we don't know yet
2012   // whether LR is going to be used.  Probably the right approach is to
2013   // generate the tail call here and turn it back into CALL/RET in
2014   // emitEpilogue if LR is used.
2015
2016   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2017   // but we need to make sure there are enough registers; the only valid
2018   // registers are the 4 used for parameters.  We don't currently do this
2019   // case.
2020   if (Subtarget->isThumb1Only())
2021     return false;
2022
2023   // Externally-defined functions with weak linkage should not be
2024   // tail-called on ARM when the OS does not support dynamic
2025   // pre-emption of symbols, as the AAELF spec requires normal calls
2026   // to undefined weak functions to be replaced with a NOP or jump to the
2027   // next instruction. The behaviour of branch instructions in this
2028   // situation (as used for tail calls) is implementation-defined, so we
2029   // cannot rely on the linker replacing the tail call with a return.
2030   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2031     const GlobalValue *GV = G->getGlobal();
2032     const Triple TT(getTargetMachine().getTargetTriple());
2033     if (GV->hasExternalWeakLinkage() &&
2034         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2035       return false;
2036   }
2037
2038   // If the calling conventions do not match, then we'd better make sure the
2039   // results are returned in the same way as what the caller expects.
2040   if (!CCMatch) {
2041     SmallVector<CCValAssign, 16> RVLocs1;
2042     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2043                        *DAG.getContext(), Call);
2044     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2045
2046     SmallVector<CCValAssign, 16> RVLocs2;
2047     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2048                        *DAG.getContext(), Call);
2049     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2050
2051     if (RVLocs1.size() != RVLocs2.size())
2052       return false;
2053     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2054       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2055         return false;
2056       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2057         return false;
2058       if (RVLocs1[i].isRegLoc()) {
2059         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2060           return false;
2061       } else {
2062         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2063           return false;
2064       }
2065     }
2066   }
2067
2068   // If Caller's vararg or byval argument has been split between registers and
2069   // stack, do not perform tail call, since part of the argument is in caller's
2070   // local frame.
2071   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2072                                       getInfo<ARMFunctionInfo>();
2073   if (AFI_Caller->getArgRegsSaveSize())
2074     return false;
2075
2076   // If the callee takes no arguments then go on to check the results of the
2077   // call.
2078   if (!Outs.empty()) {
2079     // Check if stack adjustment is needed. For now, do not do this if any
2080     // argument is passed on the stack.
2081     SmallVector<CCValAssign, 16> ArgLocs;
2082     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2083                       *DAG.getContext(), Call);
2084     CCInfo.AnalyzeCallOperands(Outs,
2085                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2086     if (CCInfo.getNextStackOffset()) {
2087       MachineFunction &MF = DAG.getMachineFunction();
2088
2089       // Check if the arguments are already laid out in the right way as
2090       // the caller's fixed stack objects.
2091       MachineFrameInfo *MFI = MF.getFrameInfo();
2092       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2093       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2094       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2095            i != e;
2096            ++i, ++realArgIdx) {
2097         CCValAssign &VA = ArgLocs[i];
2098         EVT RegVT = VA.getLocVT();
2099         SDValue Arg = OutVals[realArgIdx];
2100         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2101         if (VA.getLocInfo() == CCValAssign::Indirect)
2102           return false;
2103         if (VA.needsCustom()) {
2104           // f64 and vector types are split into multiple registers or
2105           // register/stack-slot combinations.  The types will not match
2106           // the registers; give up on memory f64 refs until we figure
2107           // out what to do about this.
2108           if (!VA.isRegLoc())
2109             return false;
2110           if (!ArgLocs[++i].isRegLoc())
2111             return false;
2112           if (RegVT == MVT::v2f64) {
2113             if (!ArgLocs[++i].isRegLoc())
2114               return false;
2115             if (!ArgLocs[++i].isRegLoc())
2116               return false;
2117           }
2118         } else if (!VA.isRegLoc()) {
2119           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2120                                    MFI, MRI, TII))
2121             return false;
2122         }
2123       }
2124     }
2125   }
2126
2127   return true;
2128 }
2129
2130 bool
2131 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2132                                   MachineFunction &MF, bool isVarArg,
2133                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2134                                   LLVMContext &Context) const {
2135   SmallVector<CCValAssign, 16> RVLocs;
2136   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2137   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2138                                                     isVarArg));
2139 }
2140
2141 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2142                                     SDLoc DL, SelectionDAG &DAG) {
2143   const MachineFunction &MF = DAG.getMachineFunction();
2144   const Function *F = MF.getFunction();
2145
2146   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2147
2148   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2149   // version of the "preferred return address". These offsets affect the return
2150   // instruction if this is a return from PL1 without hypervisor extensions.
2151   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2152   //    SWI:     0      "subs pc, lr, #0"
2153   //    ABORT:   +4     "subs pc, lr, #4"
2154   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2155   // UNDEF varies depending on where the exception came from ARM or Thumb
2156   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2157
2158   int64_t LROffset;
2159   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2160       IntKind == "ABORT")
2161     LROffset = 4;
2162   else if (IntKind == "SWI" || IntKind == "UNDEF")
2163     LROffset = 0;
2164   else
2165     report_fatal_error("Unsupported interrupt attribute. If present, value "
2166                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2167
2168   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2169
2170   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2171 }
2172
2173 SDValue
2174 ARMTargetLowering::LowerReturn(SDValue Chain,
2175                                CallingConv::ID CallConv, bool isVarArg,
2176                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2177                                const SmallVectorImpl<SDValue> &OutVals,
2178                                SDLoc dl, SelectionDAG &DAG) const {
2179
2180   // CCValAssign - represent the assignment of the return value to a location.
2181   SmallVector<CCValAssign, 16> RVLocs;
2182
2183   // CCState - Info about the registers and stack slots.
2184   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2185                     *DAG.getContext(), Call);
2186
2187   // Analyze outgoing return values.
2188   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2189                                                isVarArg));
2190
2191   SDValue Flag;
2192   SmallVector<SDValue, 4> RetOps;
2193   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2194   bool isLittleEndian = Subtarget->isLittle();
2195
2196   MachineFunction &MF = DAG.getMachineFunction();
2197   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2198   AFI->setReturnRegsCount(RVLocs.size());
2199
2200   // Copy the result values into the output registers.
2201   for (unsigned i = 0, realRVLocIdx = 0;
2202        i != RVLocs.size();
2203        ++i, ++realRVLocIdx) {
2204     CCValAssign &VA = RVLocs[i];
2205     assert(VA.isRegLoc() && "Can only return in registers!");
2206
2207     SDValue Arg = OutVals[realRVLocIdx];
2208
2209     switch (VA.getLocInfo()) {
2210     default: llvm_unreachable("Unknown loc info!");
2211     case CCValAssign::Full: break;
2212     case CCValAssign::BCvt:
2213       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2214       break;
2215     }
2216
2217     if (VA.needsCustom()) {
2218       if (VA.getLocVT() == MVT::v2f64) {
2219         // Extract the first half and return it in two registers.
2220         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2221                                    DAG.getConstant(0, MVT::i32));
2222         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2223                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2224
2225         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2226                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2227                                  Flag);
2228         Flag = Chain.getValue(1);
2229         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2230         VA = RVLocs[++i]; // skip ahead to next loc
2231         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2232                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2233                                  Flag);
2234         Flag = Chain.getValue(1);
2235         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2236         VA = RVLocs[++i]; // skip ahead to next loc
2237
2238         // Extract the 2nd half and fall through to handle it as an f64 value.
2239         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2240                           DAG.getConstant(1, MVT::i32));
2241       }
2242       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2243       // available.
2244       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2245                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2246       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2247                                fmrrd.getValue(isLittleEndian ? 0 : 1),
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       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2253                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2254                                Flag);
2255     } else
2256       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2257
2258     // Guarantee that all emitted copies are
2259     // stuck together, avoiding something bad.
2260     Flag = Chain.getValue(1);
2261     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2262   }
2263
2264   // Update chain and glue.
2265   RetOps[0] = Chain;
2266   if (Flag.getNode())
2267     RetOps.push_back(Flag);
2268
2269   // CPUs which aren't M-class use a special sequence to return from
2270   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2271   // though we use "subs pc, lr, #N").
2272   //
2273   // M-class CPUs actually use a normal return sequence with a special
2274   // (hardware-provided) value in LR, so the normal code path works.
2275   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2276       !Subtarget->isMClass()) {
2277     if (Subtarget->isThumb1Only())
2278       report_fatal_error("interrupt attribute is not supported in Thumb1");
2279     return LowerInterruptReturn(RetOps, dl, DAG);
2280   }
2281
2282   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2283 }
2284
2285 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2286   if (N->getNumValues() != 1)
2287     return false;
2288   if (!N->hasNUsesOfValue(1, 0))
2289     return false;
2290
2291   SDValue TCChain = Chain;
2292   SDNode *Copy = *N->use_begin();
2293   if (Copy->getOpcode() == ISD::CopyToReg) {
2294     // If the copy has a glue operand, we conservatively assume it isn't safe to
2295     // perform a tail call.
2296     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2297       return false;
2298     TCChain = Copy->getOperand(0);
2299   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2300     SDNode *VMov = Copy;
2301     // f64 returned in a pair of GPRs.
2302     SmallPtrSet<SDNode*, 2> Copies;
2303     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2304          UI != UE; ++UI) {
2305       if (UI->getOpcode() != ISD::CopyToReg)
2306         return false;
2307       Copies.insert(*UI);
2308     }
2309     if (Copies.size() > 2)
2310       return false;
2311
2312     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2313          UI != UE; ++UI) {
2314       SDValue UseChain = UI->getOperand(0);
2315       if (Copies.count(UseChain.getNode()))
2316         // Second CopyToReg
2317         Copy = *UI;
2318       else {
2319         // We are at the top of this chain.
2320         // If the copy has a glue operand, we conservatively assume it
2321         // isn't safe to perform a tail call.
2322         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2323           return false;
2324         // First CopyToReg
2325         TCChain = UseChain;
2326       }
2327     }
2328   } else if (Copy->getOpcode() == ISD::BITCAST) {
2329     // f32 returned in a single GPR.
2330     if (!Copy->hasOneUse())
2331       return false;
2332     Copy = *Copy->use_begin();
2333     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2334       return false;
2335     // If the copy has a glue operand, we conservatively assume it isn't safe to
2336     // perform a tail call.
2337     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2338       return false;
2339     TCChain = Copy->getOperand(0);
2340   } else {
2341     return false;
2342   }
2343
2344   bool HasRet = false;
2345   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2346        UI != UE; ++UI) {
2347     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2348         UI->getOpcode() != ARMISD::INTRET_FLAG)
2349       return false;
2350     HasRet = true;
2351   }
2352
2353   if (!HasRet)
2354     return false;
2355
2356   Chain = TCChain;
2357   return true;
2358 }
2359
2360 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2361   if (!Subtarget->supportsTailCall())
2362     return false;
2363
2364   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2365     return false;
2366
2367   return !Subtarget->isThumb1Only();
2368 }
2369
2370 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2371 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2372 // one of the above mentioned nodes. It has to be wrapped because otherwise
2373 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2374 // be used to form addressing mode. These wrapped nodes will be selected
2375 // into MOVi.
2376 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2377   EVT PtrVT = Op.getValueType();
2378   // FIXME there is no actual debug info here
2379   SDLoc dl(Op);
2380   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2381   SDValue Res;
2382   if (CP->isMachineConstantPoolEntry())
2383     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2384                                     CP->getAlignment());
2385   else
2386     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2387                                     CP->getAlignment());
2388   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2389 }
2390
2391 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2392   return MachineJumpTableInfo::EK_Inline;
2393 }
2394
2395 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2396                                              SelectionDAG &DAG) const {
2397   MachineFunction &MF = DAG.getMachineFunction();
2398   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2399   unsigned ARMPCLabelIndex = 0;
2400   SDLoc DL(Op);
2401   EVT PtrVT = getPointerTy();
2402   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2403   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2404   SDValue CPAddr;
2405   if (RelocM == Reloc::Static) {
2406     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2407   } else {
2408     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2409     ARMPCLabelIndex = AFI->createPICLabelUId();
2410     ARMConstantPoolValue *CPV =
2411       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2412                                       ARMCP::CPBlockAddress, PCAdj);
2413     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2414   }
2415   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2416   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2417                                MachinePointerInfo::getConstantPool(),
2418                                false, false, false, 0);
2419   if (RelocM == Reloc::Static)
2420     return Result;
2421   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2422   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2423 }
2424
2425 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2426 SDValue
2427 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2428                                                  SelectionDAG &DAG) const {
2429   SDLoc dl(GA);
2430   EVT PtrVT = getPointerTy();
2431   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2432   MachineFunction &MF = DAG.getMachineFunction();
2433   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2434   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2435   ARMConstantPoolValue *CPV =
2436     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2437                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2438   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2439   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2440   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2441                          MachinePointerInfo::getConstantPool(),
2442                          false, false, false, 0);
2443   SDValue Chain = Argument.getValue(1);
2444
2445   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2446   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2447
2448   // call __tls_get_addr.
2449   ArgListTy Args;
2450   ArgListEntry Entry;
2451   Entry.Node = Argument;
2452   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2453   Args.push_back(Entry);
2454
2455   // FIXME: is there useful debug info available here?
2456   TargetLowering::CallLoweringInfo CLI(DAG);
2457   CLI.setDebugLoc(dl).setChain(Chain)
2458     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2459                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2460                0);
2461
2462   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2463   return CallResult.first;
2464 }
2465
2466 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2467 // "local exec" model.
2468 SDValue
2469 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2470                                         SelectionDAG &DAG,
2471                                         TLSModel::Model model) const {
2472   const GlobalValue *GV = GA->getGlobal();
2473   SDLoc dl(GA);
2474   SDValue Offset;
2475   SDValue Chain = DAG.getEntryNode();
2476   EVT PtrVT = getPointerTy();
2477   // Get the Thread Pointer
2478   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2479
2480   if (model == TLSModel::InitialExec) {
2481     MachineFunction &MF = DAG.getMachineFunction();
2482     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2483     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2484     // Initial exec model.
2485     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2486     ARMConstantPoolValue *CPV =
2487       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2488                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2489                                       true);
2490     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2491     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2492     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2493                          MachinePointerInfo::getConstantPool(),
2494                          false, false, false, 0);
2495     Chain = Offset.getValue(1);
2496
2497     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2498     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2499
2500     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2501                          MachinePointerInfo::getConstantPool(),
2502                          false, false, false, 0);
2503   } else {
2504     // local exec model
2505     assert(model == TLSModel::LocalExec);
2506     ARMConstantPoolValue *CPV =
2507       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2508     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2509     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2510     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2511                          MachinePointerInfo::getConstantPool(),
2512                          false, false, false, 0);
2513   }
2514
2515   // The address of the thread local variable is the add of the thread
2516   // pointer with the offset of the variable.
2517   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2518 }
2519
2520 SDValue
2521 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2522   // TODO: implement the "local dynamic" model
2523   assert(Subtarget->isTargetELF() &&
2524          "TLS not implemented for non-ELF targets");
2525   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2526
2527   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2528
2529   switch (model) {
2530     case TLSModel::GeneralDynamic:
2531     case TLSModel::LocalDynamic:
2532       return LowerToTLSGeneralDynamicModel(GA, DAG);
2533     case TLSModel::InitialExec:
2534     case TLSModel::LocalExec:
2535       return LowerToTLSExecModels(GA, DAG, model);
2536   }
2537   llvm_unreachable("bogus TLS model");
2538 }
2539
2540 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2541                                                  SelectionDAG &DAG) const {
2542   EVT PtrVT = getPointerTy();
2543   SDLoc dl(Op);
2544   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2545   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2546     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2547     ARMConstantPoolValue *CPV =
2548       ARMConstantPoolConstant::Create(GV,
2549                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2550     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2551     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2552     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2553                                  CPAddr,
2554                                  MachinePointerInfo::getConstantPool(),
2555                                  false, false, false, 0);
2556     SDValue Chain = Result.getValue(1);
2557     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2558     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2559     if (!UseGOTOFF)
2560       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2561                            MachinePointerInfo::getGOT(),
2562                            false, false, false, 0);
2563     return Result;
2564   }
2565
2566   // If we have T2 ops, we can materialize the address directly via movt/movw
2567   // pair. This is always cheaper.
2568   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2569     ++NumMovwMovt;
2570     // FIXME: Once remat is capable of dealing with instructions with register
2571     // operands, expand this into two nodes.
2572     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2573                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2574   } else {
2575     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2576     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2577     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2578                        MachinePointerInfo::getConstantPool(),
2579                        false, false, false, 0);
2580   }
2581 }
2582
2583 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2584                                                     SelectionDAG &DAG) const {
2585   EVT PtrVT = getPointerTy();
2586   SDLoc dl(Op);
2587   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2588   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2589
2590   if (Subtarget->useMovt(DAG.getMachineFunction()))
2591     ++NumMovwMovt;
2592
2593   // FIXME: Once remat is capable of dealing with instructions with register
2594   // operands, expand this into multiple nodes
2595   unsigned Wrapper =
2596       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2597
2598   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2599   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2600
2601   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2602     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2603                          MachinePointerInfo::getGOT(), false, false, false, 0);
2604   return Result;
2605 }
2606
2607 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2608                                                      SelectionDAG &DAG) const {
2609   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2610   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2611          "Windows on ARM expects to use movw/movt");
2612
2613   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2614   const ARMII::TOF TargetFlags =
2615     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2616   EVT PtrVT = getPointerTy();
2617   SDValue Result;
2618   SDLoc DL(Op);
2619
2620   ++NumMovwMovt;
2621
2622   // FIXME: Once remat is capable of dealing with instructions with register
2623   // operands, expand this into two nodes.
2624   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2625                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2626                                                   TargetFlags));
2627   if (GV->hasDLLImportStorageClass())
2628     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2629                          MachinePointerInfo::getGOT(), false, false, false, 0);
2630   return Result;
2631 }
2632
2633 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2634                                                     SelectionDAG &DAG) const {
2635   assert(Subtarget->isTargetELF() &&
2636          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2637   MachineFunction &MF = DAG.getMachineFunction();
2638   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2639   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2640   EVT PtrVT = getPointerTy();
2641   SDLoc dl(Op);
2642   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2643   ARMConstantPoolValue *CPV =
2644     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2645                                   ARMPCLabelIndex, PCAdj);
2646   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2647   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2648   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2649                                MachinePointerInfo::getConstantPool(),
2650                                false, false, false, 0);
2651   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2652   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2653 }
2654
2655 SDValue
2656 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2657   SDLoc dl(Op);
2658   SDValue Val = DAG.getConstant(0, MVT::i32);
2659   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2660                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2661                      Op.getOperand(1), Val);
2662 }
2663
2664 SDValue
2665 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2666   SDLoc dl(Op);
2667   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2668                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2669 }
2670
2671 SDValue
2672 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2673                                           const ARMSubtarget *Subtarget) const {
2674   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2675   SDLoc dl(Op);
2676   switch (IntNo) {
2677   default: return SDValue();    // Don't custom lower most intrinsics.
2678   case Intrinsic::arm_rbit: {
2679     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2680            "RBIT intrinsic must have i32 type!");
2681     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2682   }
2683   case Intrinsic::arm_thread_pointer: {
2684     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2685     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2686   }
2687   case Intrinsic::eh_sjlj_lsda: {
2688     MachineFunction &MF = DAG.getMachineFunction();
2689     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2690     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2691     EVT PtrVT = getPointerTy();
2692     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2693     SDValue CPAddr;
2694     unsigned PCAdj = (RelocM != Reloc::PIC_)
2695       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2696     ARMConstantPoolValue *CPV =
2697       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2698                                       ARMCP::CPLSDA, PCAdj);
2699     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2700     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2701     SDValue Result =
2702       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2703                   MachinePointerInfo::getConstantPool(),
2704                   false, false, false, 0);
2705
2706     if (RelocM == Reloc::PIC_) {
2707       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2708       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2709     }
2710     return Result;
2711   }
2712   case Intrinsic::arm_neon_vmulls:
2713   case Intrinsic::arm_neon_vmullu: {
2714     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2715       ? ARMISD::VMULLs : ARMISD::VMULLu;
2716     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2717                        Op.getOperand(1), Op.getOperand(2));
2718   }
2719   }
2720 }
2721
2722 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2723                                  const ARMSubtarget *Subtarget) {
2724   // FIXME: handle "fence singlethread" more efficiently.
2725   SDLoc dl(Op);
2726   if (!Subtarget->hasDataBarrier()) {
2727     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2728     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2729     // here.
2730     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2731            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2732     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2733                        DAG.getConstant(0, MVT::i32));
2734   }
2735
2736   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2737   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2738   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2739   if (Subtarget->isMClass()) {
2740     // Only a full system barrier exists in the M-class architectures.
2741     Domain = ARM_MB::SY;
2742   } else if (Subtarget->isSwift() && Ord == Release) {
2743     // Swift happens to implement ISHST barriers in a way that's compatible with
2744     // Release semantics but weaker than ISH so we'd be fools not to use
2745     // it. Beware: other processors probably don't!
2746     Domain = ARM_MB::ISHST;
2747   }
2748
2749   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2750                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2751                      DAG.getConstant(Domain, MVT::i32));
2752 }
2753
2754 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2755                              const ARMSubtarget *Subtarget) {
2756   // ARM pre v5TE and Thumb1 does not have preload instructions.
2757   if (!(Subtarget->isThumb2() ||
2758         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2759     // Just preserve the chain.
2760     return Op.getOperand(0);
2761
2762   SDLoc dl(Op);
2763   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2764   if (!isRead &&
2765       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2766     // ARMv7 with MP extension has PLDW.
2767     return Op.getOperand(0);
2768
2769   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2770   if (Subtarget->isThumb()) {
2771     // Invert the bits.
2772     isRead = ~isRead & 1;
2773     isData = ~isData & 1;
2774   }
2775
2776   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2777                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2778                      DAG.getConstant(isData, MVT::i32));
2779 }
2780
2781 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2782   MachineFunction &MF = DAG.getMachineFunction();
2783   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2784
2785   // vastart just stores the address of the VarArgsFrameIndex slot into the
2786   // memory location argument.
2787   SDLoc dl(Op);
2788   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2789   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2790   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2791   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2792                       MachinePointerInfo(SV), false, false, 0);
2793 }
2794
2795 SDValue
2796 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2797                                         SDValue &Root, SelectionDAG &DAG,
2798                                         SDLoc dl) const {
2799   MachineFunction &MF = DAG.getMachineFunction();
2800   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2801
2802   const TargetRegisterClass *RC;
2803   if (AFI->isThumb1OnlyFunction())
2804     RC = &ARM::tGPRRegClass;
2805   else
2806     RC = &ARM::GPRRegClass;
2807
2808   // Transform the arguments stored in physical registers into virtual ones.
2809   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2810   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2811
2812   SDValue ArgValue2;
2813   if (NextVA.isMemLoc()) {
2814     MachineFrameInfo *MFI = MF.getFrameInfo();
2815     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2816
2817     // Create load node to retrieve arguments from the stack.
2818     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2819     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2820                             MachinePointerInfo::getFixedStack(FI),
2821                             false, false, false, 0);
2822   } else {
2823     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2824     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2825   }
2826   if (!Subtarget->isLittle())
2827     std::swap (ArgValue, ArgValue2);
2828   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2829 }
2830
2831 // The remaining GPRs hold either the beginning of variable-argument
2832 // data, or the beginning of an aggregate passed by value (usually
2833 // byval).  Either way, we allocate stack slots adjacent to the data
2834 // provided by our caller, and store the unallocated registers there.
2835 // If this is a variadic function, the va_list pointer will begin with
2836 // these values; otherwise, this reassembles a (byval) structure that
2837 // was split between registers and memory.
2838 // Return: The frame index registers were stored into.
2839 int
2840 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2841                                   SDLoc dl, SDValue &Chain,
2842                                   const Value *OrigArg,
2843                                   unsigned InRegsParamRecordIdx,
2844                                   int ArgOffset,
2845                                   unsigned ArgSize) const {
2846   // Currently, two use-cases possible:
2847   // Case #1. Non-var-args function, and we meet first byval parameter.
2848   //          Setup first unallocated register as first byval register;
2849   //          eat all remained registers
2850   //          (these two actions are performed by HandleByVal method).
2851   //          Then, here, we initialize stack frame with
2852   //          "store-reg" instructions.
2853   // Case #2. Var-args function, that doesn't contain byval parameters.
2854   //          The same: eat all remained unallocated registers,
2855   //          initialize stack frame.
2856
2857   MachineFunction &MF = DAG.getMachineFunction();
2858   MachineFrameInfo *MFI = MF.getFrameInfo();
2859   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2860   unsigned RBegin, REnd;
2861   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2862     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2863   } else {
2864     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2865     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2866     REnd = ARM::R4;
2867   }
2868
2869   if (REnd != RBegin)
2870     ArgOffset = -4 * (ARM::R4 - RBegin);
2871
2872   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2873   SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2874
2875   SmallVector<SDValue, 4> MemOps;
2876   const TargetRegisterClass *RC =
2877       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2878
2879   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2880     unsigned VReg = MF.addLiveIn(Reg, RC);
2881     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2882     SDValue Store =
2883         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2884                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2885     MemOps.push_back(Store);
2886     FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2887                       DAG.getConstant(4, getPointerTy()));
2888   }
2889
2890   if (!MemOps.empty())
2891     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2892   return FrameIndex;
2893 }
2894
2895 // Setup stack frame, the va_list pointer will start from.
2896 void
2897 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2898                                         SDLoc dl, SDValue &Chain,
2899                                         unsigned ArgOffset,
2900                                         unsigned TotalArgRegsSaveSize,
2901                                         bool ForceMutable) const {
2902   MachineFunction &MF = DAG.getMachineFunction();
2903   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2904
2905   // Try to store any remaining integer argument regs
2906   // to their spots on the stack so that they may be loaded by deferencing
2907   // the result of va_next.
2908   // If there is no regs to be stored, just point address after last
2909   // argument passed via stack.
2910   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2911                                   CCInfo.getInRegsParamsCount(),
2912                                   CCInfo.getNextStackOffset(), 4);
2913   AFI->setVarArgsFrameIndex(FrameIndex);
2914 }
2915
2916 SDValue
2917 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2918                                         CallingConv::ID CallConv, bool isVarArg,
2919                                         const SmallVectorImpl<ISD::InputArg>
2920                                           &Ins,
2921                                         SDLoc dl, SelectionDAG &DAG,
2922                                         SmallVectorImpl<SDValue> &InVals)
2923                                           const {
2924   MachineFunction &MF = DAG.getMachineFunction();
2925   MachineFrameInfo *MFI = MF.getFrameInfo();
2926
2927   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2928
2929   // Assign locations to all of the incoming arguments.
2930   SmallVector<CCValAssign, 16> ArgLocs;
2931   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2932                     *DAG.getContext(), Prologue);
2933   CCInfo.AnalyzeFormalArguments(Ins,
2934                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2935                                                   isVarArg));
2936
2937   SmallVector<SDValue, 16> ArgValues;
2938   SDValue ArgValue;
2939   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2940   unsigned CurArgIdx = 0;
2941
2942   // Initially ArgRegsSaveSize is zero.
2943   // Then we increase this value each time we meet byval parameter.
2944   // We also increase this value in case of varargs function.
2945   AFI->setArgRegsSaveSize(0);
2946
2947   // Calculate the amount of stack space that we need to allocate to store
2948   // byval and variadic arguments that are passed in registers.
2949   // We need to know this before we allocate the first byval or variadic
2950   // argument, as they will be allocated a stack slot below the CFA (Canonical
2951   // Frame Address, the stack pointer at entry to the function).
2952   unsigned ArgRegBegin = ARM::R4;
2953   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2954     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
2955       break;
2956
2957     CCValAssign &VA = ArgLocs[i];
2958     unsigned Index = VA.getValNo();
2959     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
2960     if (!Flags.isByVal())
2961       continue;
2962
2963     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
2964     unsigned RBegin, REnd;
2965     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
2966     ArgRegBegin = std::min(ArgRegBegin, RBegin);
2967
2968     CCInfo.nextInRegsParam();
2969   }
2970   CCInfo.rewindByValRegsInfo();
2971
2972   int lastInsIndex = -1;
2973   if (isVarArg && MFI->hasVAStart()) {
2974     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2975     if (RegIdx != array_lengthof(GPRArgRegs))
2976       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
2977   }
2978
2979   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
2980   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
2981
2982   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2983     CCValAssign &VA = ArgLocs[i];
2984     if (Ins[VA.getValNo()].isOrigArg()) {
2985       std::advance(CurOrigArg,
2986                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
2987       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
2988     }
2989     // Arguments stored in registers.
2990     if (VA.isRegLoc()) {
2991       EVT RegVT = VA.getLocVT();
2992
2993       if (VA.needsCustom()) {
2994         // f64 and vector types are split up into multiple registers or
2995         // combinations of registers and stack slots.
2996         if (VA.getLocVT() == MVT::v2f64) {
2997           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2998                                                    Chain, DAG, dl);
2999           VA = ArgLocs[++i]; // skip ahead to next loc
3000           SDValue ArgValue2;
3001           if (VA.isMemLoc()) {
3002             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3003             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3004             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3005                                     MachinePointerInfo::getFixedStack(FI),
3006                                     false, false, false, 0);
3007           } else {
3008             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3009                                              Chain, DAG, dl);
3010           }
3011           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3012           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3013                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3014           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3015                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3016         } else
3017           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3018
3019       } else {
3020         const TargetRegisterClass *RC;
3021
3022         if (RegVT == MVT::f32)
3023           RC = &ARM::SPRRegClass;
3024         else if (RegVT == MVT::f64)
3025           RC = &ARM::DPRRegClass;
3026         else if (RegVT == MVT::v2f64)
3027           RC = &ARM::QPRRegClass;
3028         else if (RegVT == MVT::i32)
3029           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3030                                            : &ARM::GPRRegClass;
3031         else
3032           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3033
3034         // Transform the arguments in physical registers into virtual ones.
3035         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3036         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3037       }
3038
3039       // If this is an 8 or 16-bit value, it is really passed promoted
3040       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3041       // truncate to the right size.
3042       switch (VA.getLocInfo()) {
3043       default: llvm_unreachable("Unknown loc info!");
3044       case CCValAssign::Full: break;
3045       case CCValAssign::BCvt:
3046         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3047         break;
3048       case CCValAssign::SExt:
3049         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3050                                DAG.getValueType(VA.getValVT()));
3051         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3052         break;
3053       case CCValAssign::ZExt:
3054         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3055                                DAG.getValueType(VA.getValVT()));
3056         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3057         break;
3058       }
3059
3060       InVals.push_back(ArgValue);
3061
3062     } else { // VA.isRegLoc()
3063
3064       // sanity check
3065       assert(VA.isMemLoc());
3066       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3067
3068       int index = VA.getValNo();
3069
3070       // Some Ins[] entries become multiple ArgLoc[] entries.
3071       // Process them only once.
3072       if (index != lastInsIndex)
3073         {
3074           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3075           // FIXME: For now, all byval parameter objects are marked mutable.
3076           // This can be changed with more analysis.
3077           // In case of tail call optimization mark all arguments mutable.
3078           // Since they could be overwritten by lowering of arguments in case of
3079           // a tail call.
3080           if (Flags.isByVal()) {
3081             assert(Ins[index].isOrigArg() &&
3082                    "Byval arguments cannot be implicit");
3083             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3084
3085             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3086                                             CurByValIndex, VA.getLocMemOffset(),
3087                                             Flags.getByValSize());
3088             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3089             CCInfo.nextInRegsParam();
3090           } else {
3091             unsigned FIOffset = VA.getLocMemOffset();
3092             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3093                                             FIOffset, true);
3094
3095             // Create load nodes to retrieve arguments from the stack.
3096             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3097             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3098                                          MachinePointerInfo::getFixedStack(FI),
3099                                          false, false, false, 0));
3100           }
3101           lastInsIndex = index;
3102         }
3103     }
3104   }
3105
3106   // varargs
3107   if (isVarArg && MFI->hasVAStart())
3108     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3109                          CCInfo.getNextStackOffset(),
3110                          TotalArgRegsSaveSize);
3111
3112   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3113
3114   return Chain;
3115 }
3116
3117 /// isFloatingPointZero - Return true if this is +0.0.
3118 static bool isFloatingPointZero(SDValue Op) {
3119   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3120     return CFP->getValueAPF().isPosZero();
3121   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3122     // Maybe this has already been legalized into the constant pool?
3123     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3124       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3125       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3126         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3127           return CFP->getValueAPF().isPosZero();
3128     }
3129   } else if (Op->getOpcode() == ISD::BITCAST &&
3130              Op->getValueType(0) == MVT::f64) {
3131     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3132     // created by LowerConstantFP().
3133     SDValue BitcastOp = Op->getOperand(0);
3134     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3135       SDValue MoveOp = BitcastOp->getOperand(0);
3136       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3137           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3138         return true;
3139       }
3140     }
3141   }
3142   return false;
3143 }
3144
3145 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3146 /// the given operands.
3147 SDValue
3148 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3149                              SDValue &ARMcc, SelectionDAG &DAG,
3150                              SDLoc dl) const {
3151   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3152     unsigned C = RHSC->getZExtValue();
3153     if (!isLegalICmpImmediate(C)) {
3154       // Constant does not fit, try adjusting it by one?
3155       switch (CC) {
3156       default: break;
3157       case ISD::SETLT:
3158       case ISD::SETGE:
3159         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3160           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3161           RHS = DAG.getConstant(C-1, MVT::i32);
3162         }
3163         break;
3164       case ISD::SETULT:
3165       case ISD::SETUGE:
3166         if (C != 0 && isLegalICmpImmediate(C-1)) {
3167           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3168           RHS = DAG.getConstant(C-1, MVT::i32);
3169         }
3170         break;
3171       case ISD::SETLE:
3172       case ISD::SETGT:
3173         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3174           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3175           RHS = DAG.getConstant(C+1, MVT::i32);
3176         }
3177         break;
3178       case ISD::SETULE:
3179       case ISD::SETUGT:
3180         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3181           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3182           RHS = DAG.getConstant(C+1, MVT::i32);
3183         }
3184         break;
3185       }
3186     }
3187   }
3188
3189   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3190   ARMISD::NodeType CompareType;
3191   switch (CondCode) {
3192   default:
3193     CompareType = ARMISD::CMP;
3194     break;
3195   case ARMCC::EQ:
3196   case ARMCC::NE:
3197     // Uses only Z Flag
3198     CompareType = ARMISD::CMPZ;
3199     break;
3200   }
3201   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3202   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3203 }
3204
3205 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3206 SDValue
3207 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3208                              SDLoc dl) const {
3209   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3210   SDValue Cmp;
3211   if (!isFloatingPointZero(RHS))
3212     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3213   else
3214     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3215   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3216 }
3217
3218 /// duplicateCmp - Glue values can have only one use, so this function
3219 /// duplicates a comparison node.
3220 SDValue
3221 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3222   unsigned Opc = Cmp.getOpcode();
3223   SDLoc DL(Cmp);
3224   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3225     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3226
3227   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3228   Cmp = Cmp.getOperand(0);
3229   Opc = Cmp.getOpcode();
3230   if (Opc == ARMISD::CMPFP)
3231     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3232   else {
3233     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3234     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3235   }
3236   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3237 }
3238
3239 std::pair<SDValue, SDValue>
3240 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3241                                  SDValue &ARMcc) const {
3242   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3243
3244   SDValue Value, OverflowCmp;
3245   SDValue LHS = Op.getOperand(0);
3246   SDValue RHS = Op.getOperand(1);
3247
3248
3249   // FIXME: We are currently always generating CMPs because we don't support
3250   // generating CMN through the backend. This is not as good as the natural
3251   // CMP case because it causes a register dependency and cannot be folded
3252   // later.
3253
3254   switch (Op.getOpcode()) {
3255   default:
3256     llvm_unreachable("Unknown overflow instruction!");
3257   case ISD::SADDO:
3258     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3259     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3260     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3261     break;
3262   case ISD::UADDO:
3263     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3264     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3265     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3266     break;
3267   case ISD::SSUBO:
3268     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3269     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3270     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3271     break;
3272   case ISD::USUBO:
3273     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3274     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3275     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3276     break;
3277   } // switch (...)
3278
3279   return std::make_pair(Value, OverflowCmp);
3280 }
3281
3282
3283 SDValue
3284 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3285   // Let legalize expand this if it isn't a legal type yet.
3286   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3287     return SDValue();
3288
3289   SDValue Value, OverflowCmp;
3290   SDValue ARMcc;
3291   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3292   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3293   // We use 0 and 1 as false and true values.
3294   SDValue TVal = DAG.getConstant(1, MVT::i32);
3295   SDValue FVal = DAG.getConstant(0, MVT::i32);
3296   EVT VT = Op.getValueType();
3297
3298   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3299                                  ARMcc, CCR, OverflowCmp);
3300
3301   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3302   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3303 }
3304
3305
3306 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3307   SDValue Cond = Op.getOperand(0);
3308   SDValue SelectTrue = Op.getOperand(1);
3309   SDValue SelectFalse = Op.getOperand(2);
3310   SDLoc dl(Op);
3311   unsigned Opc = Cond.getOpcode();
3312
3313   if (Cond.getResNo() == 1 &&
3314       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3315        Opc == ISD::USUBO)) {
3316     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3317       return SDValue();
3318
3319     SDValue Value, OverflowCmp;
3320     SDValue ARMcc;
3321     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3322     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3323     EVT VT = Op.getValueType();
3324
3325     return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3326                    OverflowCmp, DAG);
3327   }
3328
3329   // Convert:
3330   //
3331   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3332   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3333   //
3334   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3335     const ConstantSDNode *CMOVTrue =
3336       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3337     const ConstantSDNode *CMOVFalse =
3338       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3339
3340     if (CMOVTrue && CMOVFalse) {
3341       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3342       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3343
3344       SDValue True;
3345       SDValue False;
3346       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3347         True = SelectTrue;
3348         False = SelectFalse;
3349       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3350         True = SelectFalse;
3351         False = SelectTrue;
3352       }
3353
3354       if (True.getNode() && False.getNode()) {
3355         EVT VT = Op.getValueType();
3356         SDValue ARMcc = Cond.getOperand(2);
3357         SDValue CCR = Cond.getOperand(3);
3358         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3359         assert(True.getValueType() == VT);
3360         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3361       }
3362     }
3363   }
3364
3365   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3366   // undefined bits before doing a full-word comparison with zero.
3367   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3368                      DAG.getConstant(1, Cond.getValueType()));
3369
3370   return DAG.getSelectCC(dl, Cond,
3371                          DAG.getConstant(0, Cond.getValueType()),
3372                          SelectTrue, SelectFalse, ISD::SETNE);
3373 }
3374
3375 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3376   if (CC == ISD::SETNE)
3377     return ISD::SETEQ;
3378   return ISD::getSetCCInverse(CC, true);
3379 }
3380
3381 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3382                                  bool &swpCmpOps, bool &swpVselOps) {
3383   // Start by selecting the GE condition code for opcodes that return true for
3384   // 'equality'
3385   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3386       CC == ISD::SETULE)
3387     CondCode = ARMCC::GE;
3388
3389   // and GT for opcodes that return false for 'equality'.
3390   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3391            CC == ISD::SETULT)
3392     CondCode = ARMCC::GT;
3393
3394   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3395   // to swap the compare operands.
3396   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3397       CC == ISD::SETULT)
3398     swpCmpOps = true;
3399
3400   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3401   // If we have an unordered opcode, we need to swap the operands to the VSEL
3402   // instruction (effectively negating the condition).
3403   //
3404   // This also has the effect of swapping which one of 'less' or 'greater'
3405   // returns true, so we also swap the compare operands. It also switches
3406   // whether we return true for 'equality', so we compensate by picking the
3407   // opposite condition code to our original choice.
3408   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3409       CC == ISD::SETUGT) {
3410     swpCmpOps = !swpCmpOps;
3411     swpVselOps = !swpVselOps;
3412     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3413   }
3414
3415   // 'ordered' is 'anything but unordered', so use the VS condition code and
3416   // swap the VSEL operands.
3417   if (CC == ISD::SETO) {
3418     CondCode = ARMCC::VS;
3419     swpVselOps = true;
3420   }
3421
3422   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3423   // code and swap the VSEL operands.
3424   if (CC == ISD::SETUNE) {
3425     CondCode = ARMCC::EQ;
3426     swpVselOps = true;
3427   }
3428 }
3429
3430 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3431                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3432                                    SDValue Cmp, SelectionDAG &DAG) const {
3433   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3434     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3435                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3436     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3437                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3438
3439     SDValue TrueLow = TrueVal.getValue(0);
3440     SDValue TrueHigh = TrueVal.getValue(1);
3441     SDValue FalseLow = FalseVal.getValue(0);
3442     SDValue FalseHigh = FalseVal.getValue(1);
3443
3444     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3445                               ARMcc, CCR, Cmp);
3446     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3447                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3448
3449     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3450   } else {
3451     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3452                        Cmp);
3453   }
3454 }
3455
3456 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3457   EVT VT = Op.getValueType();
3458   SDValue LHS = Op.getOperand(0);
3459   SDValue RHS = Op.getOperand(1);
3460   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3461   SDValue TrueVal = Op.getOperand(2);
3462   SDValue FalseVal = Op.getOperand(3);
3463   SDLoc dl(Op);
3464
3465   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3466     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3467                                                     dl);
3468
3469     // If softenSetCCOperands only returned one value, we should compare it to
3470     // zero.
3471     if (!RHS.getNode()) {
3472       RHS = DAG.getConstant(0, LHS.getValueType());
3473       CC = ISD::SETNE;
3474     }
3475   }
3476
3477   if (LHS.getValueType() == MVT::i32) {
3478     // Try to generate VSEL on ARMv8.
3479     // The VSEL instruction can't use all the usual ARM condition
3480     // codes: it only has two bits to select the condition code, so it's
3481     // constrained to use only GE, GT, VS and EQ.
3482     //
3483     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3484     // swap the operands of the previous compare instruction (effectively
3485     // inverting the compare condition, swapping 'less' and 'greater') and
3486     // sometimes need to swap the operands to the VSEL (which inverts the
3487     // condition in the sense of firing whenever the previous condition didn't)
3488     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3489                                     TrueVal.getValueType() == MVT::f64)) {
3490       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3491       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3492           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3493         CC = getInverseCCForVSEL(CC);
3494         std::swap(TrueVal, FalseVal);
3495       }
3496     }
3497
3498     SDValue ARMcc;
3499     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3500     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3501     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3502   }
3503
3504   ARMCC::CondCodes CondCode, CondCode2;
3505   FPCCToARMCC(CC, CondCode, CondCode2);
3506
3507   // Try to generate VMAXNM/VMINNM on ARMv8.
3508   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3509                                   TrueVal.getValueType() == MVT::f64)) {
3510     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3511     // same operands, as follows:
3512     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3513     //   select c, a, b
3514     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3515     // We only do this transformation in UnsafeFPMath and for no-NaNs
3516     // comparisons, because signed zeros and NaNs are handled differently than
3517     // the original code sequence.
3518     // FIXME: There are more cases that can be transformed even with NaNs,
3519     // signed zeroes and safe math.  E.g. in the following, the result will be
3520     // FalseVal if a is a NaN or -0./0. and that's what vmaxnm will give, too.
3521     //   c = fcmp ogt, a, 0. ; select c, a, 0. => vmaxnm a, 0.
3522     // FIXME: There is similar code that allows some extensions in
3523     // AArch64TargetLowering::LowerSELECT_CC that should be shared with this
3524     // code.
3525     if (getTargetMachine().Options.UnsafeFPMath) {
3526       if (LHS == TrueVal && RHS == FalseVal) {
3527         if (CC == ISD::SETGT || CC == ISD::SETGE)
3528           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3529         if (CC == ISD::SETLT || CC == ISD::SETLE)
3530           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3531       } else if (LHS == FalseVal && RHS == TrueVal) {
3532         if (CC == ISD::SETLT || CC == ISD::SETLE)
3533           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3534         if (CC == ISD::SETGT || CC == ISD::SETGE)
3535           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3536       }
3537     }
3538
3539     bool swpCmpOps = false;
3540     bool swpVselOps = false;
3541     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3542
3543     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3544         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3545       if (swpCmpOps)
3546         std::swap(LHS, RHS);
3547       if (swpVselOps)
3548         std::swap(TrueVal, FalseVal);
3549     }
3550   }
3551
3552   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3553   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3554   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3555   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3556   if (CondCode2 != ARMCC::AL) {
3557     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3558     // FIXME: Needs another CMP because flag can have but one use.
3559     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3560     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3561   }
3562   return Result;
3563 }
3564
3565 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3566 /// to morph to an integer compare sequence.
3567 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3568                            const ARMSubtarget *Subtarget) {
3569   SDNode *N = Op.getNode();
3570   if (!N->hasOneUse())
3571     // Otherwise it requires moving the value from fp to integer registers.
3572     return false;
3573   if (!N->getNumValues())
3574     return false;
3575   EVT VT = Op.getValueType();
3576   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3577     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3578     // vmrs are very slow, e.g. cortex-a8.
3579     return false;
3580
3581   if (isFloatingPointZero(Op)) {
3582     SeenZero = true;
3583     return true;
3584   }
3585   return ISD::isNormalLoad(N);
3586 }
3587
3588 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3589   if (isFloatingPointZero(Op))
3590     return DAG.getConstant(0, MVT::i32);
3591
3592   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3593     return DAG.getLoad(MVT::i32, SDLoc(Op),
3594                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3595                        Ld->isVolatile(), Ld->isNonTemporal(),
3596                        Ld->isInvariant(), Ld->getAlignment());
3597
3598   llvm_unreachable("Unknown VFP cmp argument!");
3599 }
3600
3601 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3602                            SDValue &RetVal1, SDValue &RetVal2) {
3603   if (isFloatingPointZero(Op)) {
3604     RetVal1 = DAG.getConstant(0, MVT::i32);
3605     RetVal2 = DAG.getConstant(0, MVT::i32);
3606     return;
3607   }
3608
3609   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3610     SDValue Ptr = Ld->getBasePtr();
3611     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3612                           Ld->getChain(), Ptr,
3613                           Ld->getPointerInfo(),
3614                           Ld->isVolatile(), Ld->isNonTemporal(),
3615                           Ld->isInvariant(), Ld->getAlignment());
3616
3617     EVT PtrType = Ptr.getValueType();
3618     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3619     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3620                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3621     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3622                           Ld->getChain(), NewPtr,
3623                           Ld->getPointerInfo().getWithOffset(4),
3624                           Ld->isVolatile(), Ld->isNonTemporal(),
3625                           Ld->isInvariant(), NewAlign);
3626     return;
3627   }
3628
3629   llvm_unreachable("Unknown VFP cmp argument!");
3630 }
3631
3632 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3633 /// f32 and even f64 comparisons to integer ones.
3634 SDValue
3635 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3636   SDValue Chain = Op.getOperand(0);
3637   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3638   SDValue LHS = Op.getOperand(2);
3639   SDValue RHS = Op.getOperand(3);
3640   SDValue Dest = Op.getOperand(4);
3641   SDLoc dl(Op);
3642
3643   bool LHSSeenZero = false;
3644   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3645   bool RHSSeenZero = false;
3646   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3647   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3648     // If unsafe fp math optimization is enabled and there are no other uses of
3649     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3650     // to an integer comparison.
3651     if (CC == ISD::SETOEQ)
3652       CC = ISD::SETEQ;
3653     else if (CC == ISD::SETUNE)
3654       CC = ISD::SETNE;
3655
3656     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3657     SDValue ARMcc;
3658     if (LHS.getValueType() == MVT::f32) {
3659       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3660                         bitcastf32Toi32(LHS, DAG), Mask);
3661       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3662                         bitcastf32Toi32(RHS, DAG), Mask);
3663       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3664       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3665       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3666                          Chain, Dest, ARMcc, CCR, Cmp);
3667     }
3668
3669     SDValue LHS1, LHS2;
3670     SDValue RHS1, RHS2;
3671     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3672     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3673     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3674     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3675     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3676     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3677     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3678     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3679     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3680   }
3681
3682   return SDValue();
3683 }
3684
3685 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3686   SDValue Chain = Op.getOperand(0);
3687   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3688   SDValue LHS = Op.getOperand(2);
3689   SDValue RHS = Op.getOperand(3);
3690   SDValue Dest = Op.getOperand(4);
3691   SDLoc dl(Op);
3692
3693   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3694     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3695                                                     dl);
3696
3697     // If softenSetCCOperands only returned one value, we should compare it to
3698     // zero.
3699     if (!RHS.getNode()) {
3700       RHS = DAG.getConstant(0, LHS.getValueType());
3701       CC = ISD::SETNE;
3702     }
3703   }
3704
3705   if (LHS.getValueType() == MVT::i32) {
3706     SDValue ARMcc;
3707     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3708     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3709     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3710                        Chain, Dest, ARMcc, CCR, Cmp);
3711   }
3712
3713   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3714
3715   if (getTargetMachine().Options.UnsafeFPMath &&
3716       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3717        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3718     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3719     if (Result.getNode())
3720       return Result;
3721   }
3722
3723   ARMCC::CondCodes CondCode, CondCode2;
3724   FPCCToARMCC(CC, CondCode, CondCode2);
3725
3726   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3727   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3728   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3729   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3730   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3731   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3732   if (CondCode2 != ARMCC::AL) {
3733     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3734     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3735     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3736   }
3737   return Res;
3738 }
3739
3740 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3741   SDValue Chain = Op.getOperand(0);
3742   SDValue Table = Op.getOperand(1);
3743   SDValue Index = Op.getOperand(2);
3744   SDLoc dl(Op);
3745
3746   EVT PTy = getPointerTy();
3747   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3748   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3749   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3750   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3751   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3752   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3753   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3754   if (Subtarget->isThumb2()) {
3755     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3756     // which does another jump to the destination. This also makes it easier
3757     // to translate it to TBB / TBH later.
3758     // FIXME: This might not work if the function is extremely large.
3759     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3760                        Addr, Op.getOperand(2), JTI, UId);
3761   }
3762   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3763     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3764                        MachinePointerInfo::getJumpTable(),
3765                        false, false, false, 0);
3766     Chain = Addr.getValue(1);
3767     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3768     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3769   } else {
3770     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3771                        MachinePointerInfo::getJumpTable(),
3772                        false, false, false, 0);
3773     Chain = Addr.getValue(1);
3774     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3775   }
3776 }
3777
3778 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3779   EVT VT = Op.getValueType();
3780   SDLoc dl(Op);
3781
3782   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3783     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3784       return Op;
3785     return DAG.UnrollVectorOp(Op.getNode());
3786   }
3787
3788   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3789          "Invalid type for custom lowering!");
3790   if (VT != MVT::v4i16)
3791     return DAG.UnrollVectorOp(Op.getNode());
3792
3793   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3794   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3795 }
3796
3797 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3798   EVT VT = Op.getValueType();
3799   if (VT.isVector())
3800     return LowerVectorFP_TO_INT(Op, DAG);
3801   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3802     RTLIB::Libcall LC;
3803     if (Op.getOpcode() == ISD::FP_TO_SINT)
3804       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3805                               Op.getValueType());
3806     else
3807       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3808                               Op.getValueType());
3809     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3810                        /*isSigned*/ false, SDLoc(Op)).first;
3811   }
3812
3813   return Op;
3814 }
3815
3816 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3817   EVT VT = Op.getValueType();
3818   SDLoc dl(Op);
3819
3820   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3821     if (VT.getVectorElementType() == MVT::f32)
3822       return Op;
3823     return DAG.UnrollVectorOp(Op.getNode());
3824   }
3825
3826   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3827          "Invalid type for custom lowering!");
3828   if (VT != MVT::v4f32)
3829     return DAG.UnrollVectorOp(Op.getNode());
3830
3831   unsigned CastOpc;
3832   unsigned Opc;
3833   switch (Op.getOpcode()) {
3834   default: llvm_unreachable("Invalid opcode!");
3835   case ISD::SINT_TO_FP:
3836     CastOpc = ISD::SIGN_EXTEND;
3837     Opc = ISD::SINT_TO_FP;
3838     break;
3839   case ISD::UINT_TO_FP:
3840     CastOpc = ISD::ZERO_EXTEND;
3841     Opc = ISD::UINT_TO_FP;
3842     break;
3843   }
3844
3845   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3846   return DAG.getNode(Opc, dl, VT, Op);
3847 }
3848
3849 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3850   EVT VT = Op.getValueType();
3851   if (VT.isVector())
3852     return LowerVectorINT_TO_FP(Op, DAG);
3853   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3854     RTLIB::Libcall LC;
3855     if (Op.getOpcode() == ISD::SINT_TO_FP)
3856       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3857                               Op.getValueType());
3858     else
3859       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3860                               Op.getValueType());
3861     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3862                        /*isSigned*/ false, SDLoc(Op)).first;
3863   }
3864
3865   return Op;
3866 }
3867
3868 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3869   // Implement fcopysign with a fabs and a conditional fneg.
3870   SDValue Tmp0 = Op.getOperand(0);
3871   SDValue Tmp1 = Op.getOperand(1);
3872   SDLoc dl(Op);
3873   EVT VT = Op.getValueType();
3874   EVT SrcVT = Tmp1.getValueType();
3875   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3876     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3877   bool UseNEON = !InGPR && Subtarget->hasNEON();
3878
3879   if (UseNEON) {
3880     // Use VBSL to copy the sign bit.
3881     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3882     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3883                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3884     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3885     if (VT == MVT::f64)
3886       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3887                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3888                          DAG.getConstant(32, MVT::i32));
3889     else /*if (VT == MVT::f32)*/
3890       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3891     if (SrcVT == MVT::f32) {
3892       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3893       if (VT == MVT::f64)
3894         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3895                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3896                            DAG.getConstant(32, MVT::i32));
3897     } else if (VT == MVT::f32)
3898       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3899                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3900                          DAG.getConstant(32, MVT::i32));
3901     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3902     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3903
3904     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3905                                             MVT::i32);
3906     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3907     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3908                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3909
3910     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3911                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3912                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3913     if (VT == MVT::f32) {
3914       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3915       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3916                         DAG.getConstant(0, MVT::i32));
3917     } else {
3918       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3919     }
3920
3921     return Res;
3922   }
3923
3924   // Bitcast operand 1 to i32.
3925   if (SrcVT == MVT::f64)
3926     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3927                        Tmp1).getValue(1);
3928   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3929
3930   // Or in the signbit with integer operations.
3931   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3932   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3933   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3934   if (VT == MVT::f32) {
3935     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3936                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3937     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3938                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3939   }
3940
3941   // f64: Or the high part with signbit and then combine two parts.
3942   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3943                      Tmp0);
3944   SDValue Lo = Tmp0.getValue(0);
3945   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3946   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3947   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3948 }
3949
3950 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3951   MachineFunction &MF = DAG.getMachineFunction();
3952   MachineFrameInfo *MFI = MF.getFrameInfo();
3953   MFI->setReturnAddressIsTaken(true);
3954
3955   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3956     return SDValue();
3957
3958   EVT VT = Op.getValueType();
3959   SDLoc dl(Op);
3960   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3961   if (Depth) {
3962     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3963     SDValue Offset = DAG.getConstant(4, MVT::i32);
3964     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3965                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3966                        MachinePointerInfo(), false, false, false, 0);
3967   }
3968
3969   // Return LR, which contains the return address. Mark it an implicit live-in.
3970   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3971   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3972 }
3973
3974 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3975   const ARMBaseRegisterInfo &ARI =
3976     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3977   MachineFunction &MF = DAG.getMachineFunction();
3978   MachineFrameInfo *MFI = MF.getFrameInfo();
3979   MFI->setFrameAddressIsTaken(true);
3980
3981   EVT VT = Op.getValueType();
3982   SDLoc dl(Op);  // FIXME probably not meaningful
3983   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3984   unsigned FrameReg = ARI.getFrameRegister(MF);
3985   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3986   while (Depth--)
3987     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3988                             MachinePointerInfo(),
3989                             false, false, false, 0);
3990   return FrameAddr;
3991 }
3992
3993 // FIXME? Maybe this could be a TableGen attribute on some registers and
3994 // this table could be generated automatically from RegInfo.
3995 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3996                                               EVT VT) const {
3997   unsigned Reg = StringSwitch<unsigned>(RegName)
3998                        .Case("sp", ARM::SP)
3999                        .Default(0);
4000   if (Reg)
4001     return Reg;
4002   report_fatal_error("Invalid register name global variable");
4003 }
4004
4005 /// ExpandBITCAST - If the target supports VFP, this function is called to
4006 /// expand a bit convert where either the source or destination type is i64 to
4007 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4008 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4009 /// vectors), since the legalizer won't know what to do with that.
4010 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4011   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4012   SDLoc dl(N);
4013   SDValue Op = N->getOperand(0);
4014
4015   // This function is only supposed to be called for i64 types, either as the
4016   // source or destination of the bit convert.
4017   EVT SrcVT = Op.getValueType();
4018   EVT DstVT = N->getValueType(0);
4019   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4020          "ExpandBITCAST called for non-i64 type");
4021
4022   // Turn i64->f64 into VMOVDRR.
4023   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4024     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4025                              DAG.getConstant(0, MVT::i32));
4026     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4027                              DAG.getConstant(1, MVT::i32));
4028     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4029                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4030   }
4031
4032   // Turn f64->i64 into VMOVRRD.
4033   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4034     SDValue Cvt;
4035     if (TLI.isBigEndian() && SrcVT.isVector() &&
4036         SrcVT.getVectorNumElements() > 1)
4037       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4038                         DAG.getVTList(MVT::i32, MVT::i32),
4039                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4040     else
4041       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4042                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4043     // Merge the pieces into a single i64 value.
4044     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4045   }
4046
4047   return SDValue();
4048 }
4049
4050 /// getZeroVector - Returns a vector of specified type with all zero elements.
4051 /// Zero vectors are used to represent vector negation and in those cases
4052 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4053 /// not support i64 elements, so sometimes the zero vectors will need to be
4054 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4055 /// zero vector.
4056 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4057   assert(VT.isVector() && "Expected a vector type");
4058   // The canonical modified immediate encoding of a zero vector is....0!
4059   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4060   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4061   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4062   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4063 }
4064
4065 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4066 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4067 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4068                                                 SelectionDAG &DAG) const {
4069   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4070   EVT VT = Op.getValueType();
4071   unsigned VTBits = VT.getSizeInBits();
4072   SDLoc dl(Op);
4073   SDValue ShOpLo = Op.getOperand(0);
4074   SDValue ShOpHi = Op.getOperand(1);
4075   SDValue ShAmt  = Op.getOperand(2);
4076   SDValue ARMcc;
4077   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4078
4079   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4080
4081   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4082                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4083   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4084   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4085                                    DAG.getConstant(VTBits, MVT::i32));
4086   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4087   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4088   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4089
4090   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4091   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4092                           ARMcc, DAG, dl);
4093   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4094   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4095                            CCR, Cmp);
4096
4097   SDValue Ops[2] = { Lo, Hi };
4098   return DAG.getMergeValues(Ops, dl);
4099 }
4100
4101 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4102 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4103 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4104                                                SelectionDAG &DAG) const {
4105   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4106   EVT VT = Op.getValueType();
4107   unsigned VTBits = VT.getSizeInBits();
4108   SDLoc dl(Op);
4109   SDValue ShOpLo = Op.getOperand(0);
4110   SDValue ShOpHi = Op.getOperand(1);
4111   SDValue ShAmt  = Op.getOperand(2);
4112   SDValue ARMcc;
4113
4114   assert(Op.getOpcode() == ISD::SHL_PARTS);
4115   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4116                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4117   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4118   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4119                                    DAG.getConstant(VTBits, MVT::i32));
4120   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4121   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4122
4123   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4124   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4125   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4126                           ARMcc, DAG, dl);
4127   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4128   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4129                            CCR, Cmp);
4130
4131   SDValue Ops[2] = { Lo, Hi };
4132   return DAG.getMergeValues(Ops, dl);
4133 }
4134
4135 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4136                                             SelectionDAG &DAG) const {
4137   // The rounding mode is in bits 23:22 of the FPSCR.
4138   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4139   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4140   // so that the shift + and get folded into a bitfield extract.
4141   SDLoc dl(Op);
4142   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4143                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4144                                               MVT::i32));
4145   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4146                                   DAG.getConstant(1U << 22, MVT::i32));
4147   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4148                               DAG.getConstant(22, MVT::i32));
4149   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4150                      DAG.getConstant(3, MVT::i32));
4151 }
4152
4153 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4154                          const ARMSubtarget *ST) {
4155   EVT VT = N->getValueType(0);
4156   SDLoc dl(N);
4157
4158   if (!ST->hasV6T2Ops())
4159     return SDValue();
4160
4161   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4162   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4163 }
4164
4165 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4166 /// for each 16-bit element from operand, repeated.  The basic idea is to
4167 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4168 ///
4169 /// Trace for v4i16:
4170 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4171 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4172 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4173 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4174 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4175 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4176 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4177 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4178 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4179   EVT VT = N->getValueType(0);
4180   SDLoc DL(N);
4181
4182   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4183   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4184   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4185   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4186   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4187   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4188 }
4189
4190 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4191 /// bit-count for each 16-bit element from the operand.  We need slightly
4192 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4193 /// 64/128-bit registers.
4194 ///
4195 /// Trace for v4i16:
4196 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4197 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4198 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4199 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4200 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4201   EVT VT = N->getValueType(0);
4202   SDLoc DL(N);
4203
4204   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4205   if (VT.is64BitVector()) {
4206     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4207     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4208                        DAG.getIntPtrConstant(0));
4209   } else {
4210     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4211                                     BitCounts, DAG.getIntPtrConstant(0));
4212     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4213   }
4214 }
4215
4216 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4217 /// bit-count for each 32-bit element from the operand.  The idea here is
4218 /// to split the vector into 16-bit elements, leverage the 16-bit count
4219 /// routine, and then combine the results.
4220 ///
4221 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4222 /// input    = [v0    v1    ] (vi: 32-bit elements)
4223 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4224 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4225 /// vrev: N0 = [k1 k0 k3 k2 ]
4226 ///            [k0 k1 k2 k3 ]
4227 ///       N1 =+[k1 k0 k3 k2 ]
4228 ///            [k0 k2 k1 k3 ]
4229 ///       N2 =+[k1 k3 k0 k2 ]
4230 ///            [k0    k2    k1    k3    ]
4231 /// Extended =+[k1    k3    k0    k2    ]
4232 ///            [k0    k2    ]
4233 /// Extracted=+[k1    k3    ]
4234 ///
4235 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4236   EVT VT = N->getValueType(0);
4237   SDLoc DL(N);
4238
4239   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4240
4241   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4242   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4243   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4244   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4245   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4246
4247   if (VT.is64BitVector()) {
4248     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4249     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4250                        DAG.getIntPtrConstant(0));
4251   } else {
4252     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4253                                     DAG.getIntPtrConstant(0));
4254     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4255   }
4256 }
4257
4258 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4259                           const ARMSubtarget *ST) {
4260   EVT VT = N->getValueType(0);
4261
4262   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4263   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4264           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4265          "Unexpected type for custom ctpop lowering");
4266
4267   if (VT.getVectorElementType() == MVT::i32)
4268     return lowerCTPOP32BitElements(N, DAG);
4269   else
4270     return lowerCTPOP16BitElements(N, DAG);
4271 }
4272
4273 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4274                           const ARMSubtarget *ST) {
4275   EVT VT = N->getValueType(0);
4276   SDLoc dl(N);
4277
4278   if (!VT.isVector())
4279     return SDValue();
4280
4281   // Lower vector shifts on NEON to use VSHL.
4282   assert(ST->hasNEON() && "unexpected vector shift");
4283
4284   // Left shifts translate directly to the vshiftu intrinsic.
4285   if (N->getOpcode() == ISD::SHL)
4286     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4287                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4288                        N->getOperand(0), N->getOperand(1));
4289
4290   assert((N->getOpcode() == ISD::SRA ||
4291           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4292
4293   // NEON uses the same intrinsics for both left and right shifts.  For
4294   // right shifts, the shift amounts are negative, so negate the vector of
4295   // shift amounts.
4296   EVT ShiftVT = N->getOperand(1).getValueType();
4297   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4298                                      getZeroVector(ShiftVT, DAG, dl),
4299                                      N->getOperand(1));
4300   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4301                              Intrinsic::arm_neon_vshifts :
4302                              Intrinsic::arm_neon_vshiftu);
4303   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4304                      DAG.getConstant(vshiftInt, MVT::i32),
4305                      N->getOperand(0), NegatedCount);
4306 }
4307
4308 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4309                                 const ARMSubtarget *ST) {
4310   EVT VT = N->getValueType(0);
4311   SDLoc dl(N);
4312
4313   // We can get here for a node like i32 = ISD::SHL i32, i64
4314   if (VT != MVT::i64)
4315     return SDValue();
4316
4317   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4318          "Unknown shift to lower!");
4319
4320   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4321   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4322       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4323     return SDValue();
4324
4325   // If we are in thumb mode, we don't have RRX.
4326   if (ST->isThumb1Only()) return SDValue();
4327
4328   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4329   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4330                            DAG.getConstant(0, MVT::i32));
4331   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4332                            DAG.getConstant(1, MVT::i32));
4333
4334   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4335   // captures the result into a carry flag.
4336   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4337   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4338
4339   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4340   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4341
4342   // Merge the pieces into a single i64 value.
4343  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4344 }
4345
4346 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4347   SDValue TmpOp0, TmpOp1;
4348   bool Invert = false;
4349   bool Swap = false;
4350   unsigned Opc = 0;
4351
4352   SDValue Op0 = Op.getOperand(0);
4353   SDValue Op1 = Op.getOperand(1);
4354   SDValue CC = Op.getOperand(2);
4355   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4356   EVT VT = Op.getValueType();
4357   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4358   SDLoc dl(Op);
4359
4360   if (Op1.getValueType().isFloatingPoint()) {
4361     switch (SetCCOpcode) {
4362     default: llvm_unreachable("Illegal FP comparison");
4363     case ISD::SETUNE:
4364     case ISD::SETNE:  Invert = true; // Fallthrough
4365     case ISD::SETOEQ:
4366     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4367     case ISD::SETOLT:
4368     case ISD::SETLT: Swap = true; // Fallthrough
4369     case ISD::SETOGT:
4370     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4371     case ISD::SETOLE:
4372     case ISD::SETLE:  Swap = true; // Fallthrough
4373     case ISD::SETOGE:
4374     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4375     case ISD::SETUGE: Swap = true; // Fallthrough
4376     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4377     case ISD::SETUGT: Swap = true; // Fallthrough
4378     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4379     case ISD::SETUEQ: Invert = true; // Fallthrough
4380     case ISD::SETONE:
4381       // Expand this to (OLT | OGT).
4382       TmpOp0 = Op0;
4383       TmpOp1 = Op1;
4384       Opc = ISD::OR;
4385       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4386       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4387       break;
4388     case ISD::SETUO: Invert = true; // Fallthrough
4389     case ISD::SETO:
4390       // Expand this to (OLT | OGE).
4391       TmpOp0 = Op0;
4392       TmpOp1 = Op1;
4393       Opc = ISD::OR;
4394       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4395       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4396       break;
4397     }
4398   } else {
4399     // Integer comparisons.
4400     switch (SetCCOpcode) {
4401     default: llvm_unreachable("Illegal integer comparison");
4402     case ISD::SETNE:  Invert = true;
4403     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4404     case ISD::SETLT:  Swap = true;
4405     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4406     case ISD::SETLE:  Swap = true;
4407     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4408     case ISD::SETULT: Swap = true;
4409     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4410     case ISD::SETULE: Swap = true;
4411     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4412     }
4413
4414     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4415     if (Opc == ARMISD::VCEQ) {
4416
4417       SDValue AndOp;
4418       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4419         AndOp = Op0;
4420       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4421         AndOp = Op1;
4422
4423       // Ignore bitconvert.
4424       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4425         AndOp = AndOp.getOperand(0);
4426
4427       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4428         Opc = ARMISD::VTST;
4429         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4430         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4431         Invert = !Invert;
4432       }
4433     }
4434   }
4435
4436   if (Swap)
4437     std::swap(Op0, Op1);
4438
4439   // If one of the operands is a constant vector zero, attempt to fold the
4440   // comparison to a specialized compare-against-zero form.
4441   SDValue SingleOp;
4442   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4443     SingleOp = Op0;
4444   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4445     if (Opc == ARMISD::VCGE)
4446       Opc = ARMISD::VCLEZ;
4447     else if (Opc == ARMISD::VCGT)
4448       Opc = ARMISD::VCLTZ;
4449     SingleOp = Op1;
4450   }
4451
4452   SDValue Result;
4453   if (SingleOp.getNode()) {
4454     switch (Opc) {
4455     case ARMISD::VCEQ:
4456       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4457     case ARMISD::VCGE:
4458       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4459     case ARMISD::VCLEZ:
4460       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4461     case ARMISD::VCGT:
4462       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4463     case ARMISD::VCLTZ:
4464       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4465     default:
4466       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4467     }
4468   } else {
4469      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4470   }
4471
4472   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4473
4474   if (Invert)
4475     Result = DAG.getNOT(dl, Result, VT);
4476
4477   return Result;
4478 }
4479
4480 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4481 /// valid vector constant for a NEON instruction with a "modified immediate"
4482 /// operand (e.g., VMOV).  If so, return the encoded value.
4483 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4484                                  unsigned SplatBitSize, SelectionDAG &DAG,
4485                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4486   unsigned OpCmode, Imm;
4487
4488   // SplatBitSize is set to the smallest size that splats the vector, so a
4489   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4490   // immediate instructions others than VMOV do not support the 8-bit encoding
4491   // of a zero vector, and the default encoding of zero is supposed to be the
4492   // 32-bit version.
4493   if (SplatBits == 0)
4494     SplatBitSize = 32;
4495
4496   switch (SplatBitSize) {
4497   case 8:
4498     if (type != VMOVModImm)
4499       return SDValue();
4500     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4501     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4502     OpCmode = 0xe;
4503     Imm = SplatBits;
4504     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4505     break;
4506
4507   case 16:
4508     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4509     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4510     if ((SplatBits & ~0xff) == 0) {
4511       // Value = 0x00nn: Op=x, Cmode=100x.
4512       OpCmode = 0x8;
4513       Imm = SplatBits;
4514       break;
4515     }
4516     if ((SplatBits & ~0xff00) == 0) {
4517       // Value = 0xnn00: Op=x, Cmode=101x.
4518       OpCmode = 0xa;
4519       Imm = SplatBits >> 8;
4520       break;
4521     }
4522     return SDValue();
4523
4524   case 32:
4525     // NEON's 32-bit VMOV supports splat values where:
4526     // * only one byte is nonzero, or
4527     // * the least significant byte is 0xff and the second byte is nonzero, or
4528     // * the least significant 2 bytes are 0xff and the third is nonzero.
4529     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4530     if ((SplatBits & ~0xff) == 0) {
4531       // Value = 0x000000nn: Op=x, Cmode=000x.
4532       OpCmode = 0;
4533       Imm = SplatBits;
4534       break;
4535     }
4536     if ((SplatBits & ~0xff00) == 0) {
4537       // Value = 0x0000nn00: Op=x, Cmode=001x.
4538       OpCmode = 0x2;
4539       Imm = SplatBits >> 8;
4540       break;
4541     }
4542     if ((SplatBits & ~0xff0000) == 0) {
4543       // Value = 0x00nn0000: Op=x, Cmode=010x.
4544       OpCmode = 0x4;
4545       Imm = SplatBits >> 16;
4546       break;
4547     }
4548     if ((SplatBits & ~0xff000000) == 0) {
4549       // Value = 0xnn000000: Op=x, Cmode=011x.
4550       OpCmode = 0x6;
4551       Imm = SplatBits >> 24;
4552       break;
4553     }
4554
4555     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4556     if (type == OtherModImm) return SDValue();
4557
4558     if ((SplatBits & ~0xffff) == 0 &&
4559         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4560       // Value = 0x0000nnff: Op=x, Cmode=1100.
4561       OpCmode = 0xc;
4562       Imm = SplatBits >> 8;
4563       break;
4564     }
4565
4566     if ((SplatBits & ~0xffffff) == 0 &&
4567         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4568       // Value = 0x00nnffff: Op=x, Cmode=1101.
4569       OpCmode = 0xd;
4570       Imm = SplatBits >> 16;
4571       break;
4572     }
4573
4574     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4575     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4576     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4577     // and fall through here to test for a valid 64-bit splat.  But, then the
4578     // caller would also need to check and handle the change in size.
4579     return SDValue();
4580
4581   case 64: {
4582     if (type != VMOVModImm)
4583       return SDValue();
4584     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4585     uint64_t BitMask = 0xff;
4586     uint64_t Val = 0;
4587     unsigned ImmMask = 1;
4588     Imm = 0;
4589     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4590       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4591         Val |= BitMask;
4592         Imm |= ImmMask;
4593       } else if ((SplatBits & BitMask) != 0) {
4594         return SDValue();
4595       }
4596       BitMask <<= 8;
4597       ImmMask <<= 1;
4598     }
4599
4600     if (DAG.getTargetLoweringInfo().isBigEndian())
4601       // swap higher and lower 32 bit word
4602       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4603
4604     // Op=1, Cmode=1110.
4605     OpCmode = 0x1e;
4606     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4607     break;
4608   }
4609
4610   default:
4611     llvm_unreachable("unexpected size for isNEONModifiedImm");
4612   }
4613
4614   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4615   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4616 }
4617
4618 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4619                                            const ARMSubtarget *ST) const {
4620   if (!ST->hasVFP3())
4621     return SDValue();
4622
4623   bool IsDouble = Op.getValueType() == MVT::f64;
4624   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4625
4626   // Use the default (constant pool) lowering for double constants when we have
4627   // an SP-only FPU
4628   if (IsDouble && Subtarget->isFPOnlySP())
4629     return SDValue();
4630
4631   // Try splatting with a VMOV.f32...
4632   APFloat FPVal = CFP->getValueAPF();
4633   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4634
4635   if (ImmVal != -1) {
4636     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4637       // We have code in place to select a valid ConstantFP already, no need to
4638       // do any mangling.
4639       return Op;
4640     }
4641
4642     // It's a float and we are trying to use NEON operations where
4643     // possible. Lower it to a splat followed by an extract.
4644     SDLoc DL(Op);
4645     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4646     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4647                                       NewVal);
4648     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4649                        DAG.getConstant(0, MVT::i32));
4650   }
4651
4652   // The rest of our options are NEON only, make sure that's allowed before
4653   // proceeding..
4654   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4655     return SDValue();
4656
4657   EVT VMovVT;
4658   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4659
4660   // It wouldn't really be worth bothering for doubles except for one very
4661   // important value, which does happen to match: 0.0. So make sure we don't do
4662   // anything stupid.
4663   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4664     return SDValue();
4665
4666   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4667   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4668                                      false, VMOVModImm);
4669   if (NewVal != SDValue()) {
4670     SDLoc DL(Op);
4671     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4672                                       NewVal);
4673     if (IsDouble)
4674       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4675
4676     // It's a float: cast and extract a vector element.
4677     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4678                                        VecConstant);
4679     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4680                        DAG.getConstant(0, MVT::i32));
4681   }
4682
4683   // Finally, try a VMVN.i32
4684   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4685                              false, VMVNModImm);
4686   if (NewVal != SDValue()) {
4687     SDLoc DL(Op);
4688     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4689
4690     if (IsDouble)
4691       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4692
4693     // It's a float: cast and extract a vector element.
4694     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4695                                        VecConstant);
4696     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4697                        DAG.getConstant(0, MVT::i32));
4698   }
4699
4700   return SDValue();
4701 }
4702
4703 // check if an VEXT instruction can handle the shuffle mask when the
4704 // vector sources of the shuffle are the same.
4705 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4706   unsigned NumElts = VT.getVectorNumElements();
4707
4708   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4709   if (M[0] < 0)
4710     return false;
4711
4712   Imm = M[0];
4713
4714   // If this is a VEXT shuffle, the immediate value is the index of the first
4715   // element.  The other shuffle indices must be the successive elements after
4716   // the first one.
4717   unsigned ExpectedElt = Imm;
4718   for (unsigned i = 1; i < NumElts; ++i) {
4719     // Increment the expected index.  If it wraps around, just follow it
4720     // back to index zero and keep going.
4721     ++ExpectedElt;
4722     if (ExpectedElt == NumElts)
4723       ExpectedElt = 0;
4724
4725     if (M[i] < 0) continue; // ignore UNDEF indices
4726     if (ExpectedElt != static_cast<unsigned>(M[i]))
4727       return false;
4728   }
4729
4730   return true;
4731 }
4732
4733
4734 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4735                        bool &ReverseVEXT, unsigned &Imm) {
4736   unsigned NumElts = VT.getVectorNumElements();
4737   ReverseVEXT = false;
4738
4739   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4740   if (M[0] < 0)
4741     return false;
4742
4743   Imm = M[0];
4744
4745   // If this is a VEXT shuffle, the immediate value is the index of the first
4746   // element.  The other shuffle indices must be the successive elements after
4747   // the first one.
4748   unsigned ExpectedElt = Imm;
4749   for (unsigned i = 1; i < NumElts; ++i) {
4750     // Increment the expected index.  If it wraps around, it may still be
4751     // a VEXT but the source vectors must be swapped.
4752     ExpectedElt += 1;
4753     if (ExpectedElt == NumElts * 2) {
4754       ExpectedElt = 0;
4755       ReverseVEXT = true;
4756     }
4757
4758     if (M[i] < 0) continue; // ignore UNDEF indices
4759     if (ExpectedElt != static_cast<unsigned>(M[i]))
4760       return false;
4761   }
4762
4763   // Adjust the index value if the source operands will be swapped.
4764   if (ReverseVEXT)
4765     Imm -= NumElts;
4766
4767   return true;
4768 }
4769
4770 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4771 /// instruction with the specified blocksize.  (The order of the elements
4772 /// within each block of the vector is reversed.)
4773 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4774   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4775          "Only possible block sizes for VREV are: 16, 32, 64");
4776
4777   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4778   if (EltSz == 64)
4779     return false;
4780
4781   unsigned NumElts = VT.getVectorNumElements();
4782   unsigned BlockElts = M[0] + 1;
4783   // If the first shuffle index is UNDEF, be optimistic.
4784   if (M[0] < 0)
4785     BlockElts = BlockSize / EltSz;
4786
4787   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4788     return false;
4789
4790   for (unsigned i = 0; i < NumElts; ++i) {
4791     if (M[i] < 0) continue; // ignore UNDEF indices
4792     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4793       return false;
4794   }
4795
4796   return true;
4797 }
4798
4799 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4800   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4801   // range, then 0 is placed into the resulting vector. So pretty much any mask
4802   // of 8 elements can work here.
4803   return VT == MVT::v8i8 && M.size() == 8;
4804 }
4805
4806 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4807   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4808   if (EltSz == 64)
4809     return false;
4810
4811   unsigned NumElts = VT.getVectorNumElements();
4812   WhichResult = (M[0] == 0 ? 0 : 1);
4813   for (unsigned i = 0; i < NumElts; i += 2) {
4814     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4815         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4816       return false;
4817   }
4818   return true;
4819 }
4820
4821 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4822 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4823 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4824 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4825   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4826   if (EltSz == 64)
4827     return false;
4828
4829   unsigned NumElts = VT.getVectorNumElements();
4830   WhichResult = (M[0] == 0 ? 0 : 1);
4831   for (unsigned i = 0; i < NumElts; i += 2) {
4832     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4833         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4834       return false;
4835   }
4836   return true;
4837 }
4838
4839 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4840   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4841   if (EltSz == 64)
4842     return false;
4843
4844   unsigned NumElts = VT.getVectorNumElements();
4845   WhichResult = (M[0] == 0 ? 0 : 1);
4846   for (unsigned i = 0; i != NumElts; ++i) {
4847     if (M[i] < 0) continue; // ignore UNDEF indices
4848     if ((unsigned) M[i] != 2 * i + WhichResult)
4849       return false;
4850   }
4851
4852   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4853   if (VT.is64BitVector() && EltSz == 32)
4854     return false;
4855
4856   return true;
4857 }
4858
4859 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4860 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4861 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4862 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4863   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4864   if (EltSz == 64)
4865     return false;
4866
4867   unsigned Half = VT.getVectorNumElements() / 2;
4868   WhichResult = (M[0] == 0 ? 0 : 1);
4869   for (unsigned j = 0; j != 2; ++j) {
4870     unsigned Idx = WhichResult;
4871     for (unsigned i = 0; i != Half; ++i) {
4872       int MIdx = M[i + j * Half];
4873       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4874         return false;
4875       Idx += 2;
4876     }
4877   }
4878
4879   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4880   if (VT.is64BitVector() && EltSz == 32)
4881     return false;
4882
4883   return true;
4884 }
4885
4886 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4887   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4888   if (EltSz == 64)
4889     return false;
4890
4891   unsigned NumElts = VT.getVectorNumElements();
4892   WhichResult = (M[0] == 0 ? 0 : 1);
4893   unsigned Idx = WhichResult * NumElts / 2;
4894   for (unsigned i = 0; i != NumElts; i += 2) {
4895     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4896         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4897       return false;
4898     Idx += 1;
4899   }
4900
4901   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4902   if (VT.is64BitVector() && EltSz == 32)
4903     return false;
4904
4905   return true;
4906 }
4907
4908 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4909 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4910 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4911 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4912   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4913   if (EltSz == 64)
4914     return false;
4915
4916   unsigned NumElts = VT.getVectorNumElements();
4917   WhichResult = (M[0] == 0 ? 0 : 1);
4918   unsigned Idx = WhichResult * NumElts / 2;
4919   for (unsigned i = 0; i != NumElts; i += 2) {
4920     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4921         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4922       return false;
4923     Idx += 1;
4924   }
4925
4926   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4927   if (VT.is64BitVector() && EltSz == 32)
4928     return false;
4929
4930   return true;
4931 }
4932
4933 /// \return true if this is a reverse operation on an vector.
4934 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4935   unsigned NumElts = VT.getVectorNumElements();
4936   // Make sure the mask has the right size.
4937   if (NumElts != M.size())
4938       return false;
4939
4940   // Look for <15, ..., 3, -1, 1, 0>.
4941   for (unsigned i = 0; i != NumElts; ++i)
4942     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4943       return false;
4944
4945   return true;
4946 }
4947
4948 // If N is an integer constant that can be moved into a register in one
4949 // instruction, return an SDValue of such a constant (will become a MOV
4950 // instruction).  Otherwise return null.
4951 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4952                                      const ARMSubtarget *ST, SDLoc dl) {
4953   uint64_t Val;
4954   if (!isa<ConstantSDNode>(N))
4955     return SDValue();
4956   Val = cast<ConstantSDNode>(N)->getZExtValue();
4957
4958   if (ST->isThumb1Only()) {
4959     if (Val <= 255 || ~Val <= 255)
4960       return DAG.getConstant(Val, MVT::i32);
4961   } else {
4962     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4963       return DAG.getConstant(Val, MVT::i32);
4964   }
4965   return SDValue();
4966 }
4967
4968 // If this is a case we can't handle, return null and let the default
4969 // expansion code take care of it.
4970 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4971                                              const ARMSubtarget *ST) const {
4972   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4973   SDLoc dl(Op);
4974   EVT VT = Op.getValueType();
4975
4976   APInt SplatBits, SplatUndef;
4977   unsigned SplatBitSize;
4978   bool HasAnyUndefs;
4979   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4980     if (SplatBitSize <= 64) {
4981       // Check if an immediate VMOV works.
4982       EVT VmovVT;
4983       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4984                                       SplatUndef.getZExtValue(), SplatBitSize,
4985                                       DAG, VmovVT, VT.is128BitVector(),
4986                                       VMOVModImm);
4987       if (Val.getNode()) {
4988         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4989         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4990       }
4991
4992       // Try an immediate VMVN.
4993       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4994       Val = isNEONModifiedImm(NegatedImm,
4995                                       SplatUndef.getZExtValue(), SplatBitSize,
4996                                       DAG, VmovVT, VT.is128BitVector(),
4997                                       VMVNModImm);
4998       if (Val.getNode()) {
4999         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5000         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5001       }
5002
5003       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5004       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5005         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5006         if (ImmVal != -1) {
5007           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5008           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5009         }
5010       }
5011     }
5012   }
5013
5014   // Scan through the operands to see if only one value is used.
5015   //
5016   // As an optimisation, even if more than one value is used it may be more
5017   // profitable to splat with one value then change some lanes.
5018   //
5019   // Heuristically we decide to do this if the vector has a "dominant" value,
5020   // defined as splatted to more than half of the lanes.
5021   unsigned NumElts = VT.getVectorNumElements();
5022   bool isOnlyLowElement = true;
5023   bool usesOnlyOneValue = true;
5024   bool hasDominantValue = false;
5025   bool isConstant = true;
5026
5027   // Map of the number of times a particular SDValue appears in the
5028   // element list.
5029   DenseMap<SDValue, unsigned> ValueCounts;
5030   SDValue Value;
5031   for (unsigned i = 0; i < NumElts; ++i) {
5032     SDValue V = Op.getOperand(i);
5033     if (V.getOpcode() == ISD::UNDEF)
5034       continue;
5035     if (i > 0)
5036       isOnlyLowElement = false;
5037     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5038       isConstant = false;
5039
5040     ValueCounts.insert(std::make_pair(V, 0));
5041     unsigned &Count = ValueCounts[V];
5042
5043     // Is this value dominant? (takes up more than half of the lanes)
5044     if (++Count > (NumElts / 2)) {
5045       hasDominantValue = true;
5046       Value = V;
5047     }
5048   }
5049   if (ValueCounts.size() != 1)
5050     usesOnlyOneValue = false;
5051   if (!Value.getNode() && ValueCounts.size() > 0)
5052     Value = ValueCounts.begin()->first;
5053
5054   if (ValueCounts.size() == 0)
5055     return DAG.getUNDEF(VT);
5056
5057   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5058   // Keep going if we are hitting this case.
5059   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5060     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5061
5062   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5063
5064   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5065   // i32 and try again.
5066   if (hasDominantValue && EltSize <= 32) {
5067     if (!isConstant) {
5068       SDValue N;
5069
5070       // If we are VDUPing a value that comes directly from a vector, that will
5071       // cause an unnecessary move to and from a GPR, where instead we could
5072       // just use VDUPLANE. We can only do this if the lane being extracted
5073       // is at a constant index, as the VDUP from lane instructions only have
5074       // constant-index forms.
5075       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5076           isa<ConstantSDNode>(Value->getOperand(1))) {
5077         // We need to create a new undef vector to use for the VDUPLANE if the
5078         // size of the vector from which we get the value is different than the
5079         // size of the vector that we need to create. We will insert the element
5080         // such that the register coalescer will remove unnecessary copies.
5081         if (VT != Value->getOperand(0).getValueType()) {
5082           ConstantSDNode *constIndex;
5083           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5084           assert(constIndex && "The index is not a constant!");
5085           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5086                              VT.getVectorNumElements();
5087           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5088                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5089                         Value, DAG.getConstant(index, MVT::i32)),
5090                            DAG.getConstant(index, MVT::i32));
5091         } else
5092           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5093                         Value->getOperand(0), Value->getOperand(1));
5094       } else
5095         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5096
5097       if (!usesOnlyOneValue) {
5098         // The dominant value was splatted as 'N', but we now have to insert
5099         // all differing elements.
5100         for (unsigned I = 0; I < NumElts; ++I) {
5101           if (Op.getOperand(I) == Value)
5102             continue;
5103           SmallVector<SDValue, 3> Ops;
5104           Ops.push_back(N);
5105           Ops.push_back(Op.getOperand(I));
5106           Ops.push_back(DAG.getConstant(I, MVT::i32));
5107           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5108         }
5109       }
5110       return N;
5111     }
5112     if (VT.getVectorElementType().isFloatingPoint()) {
5113       SmallVector<SDValue, 8> Ops;
5114       for (unsigned i = 0; i < NumElts; ++i)
5115         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5116                                   Op.getOperand(i)));
5117       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5118       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5119       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5120       if (Val.getNode())
5121         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5122     }
5123     if (usesOnlyOneValue) {
5124       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5125       if (isConstant && Val.getNode())
5126         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5127     }
5128   }
5129
5130   // If all elements are constants and the case above didn't get hit, fall back
5131   // to the default expansion, which will generate a load from the constant
5132   // pool.
5133   if (isConstant)
5134     return SDValue();
5135
5136   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5137   if (NumElts >= 4) {
5138     SDValue shuffle = ReconstructShuffle(Op, DAG);
5139     if (shuffle != SDValue())
5140       return shuffle;
5141   }
5142
5143   // Vectors with 32- or 64-bit elements can be built by directly assigning
5144   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5145   // will be legalized.
5146   if (EltSize >= 32) {
5147     // Do the expansion with floating-point types, since that is what the VFP
5148     // registers are defined to use, and since i64 is not legal.
5149     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5150     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5151     SmallVector<SDValue, 8> Ops;
5152     for (unsigned i = 0; i < NumElts; ++i)
5153       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5154     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5155     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5156   }
5157
5158   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5159   // know the default expansion would otherwise fall back on something even
5160   // worse. For a vector with one or two non-undef values, that's
5161   // scalar_to_vector for the elements followed by a shuffle (provided the
5162   // shuffle is valid for the target) and materialization element by element
5163   // on the stack followed by a load for everything else.
5164   if (!isConstant && !usesOnlyOneValue) {
5165     SDValue Vec = DAG.getUNDEF(VT);
5166     for (unsigned i = 0 ; i < NumElts; ++i) {
5167       SDValue V = Op.getOperand(i);
5168       if (V.getOpcode() == ISD::UNDEF)
5169         continue;
5170       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5171       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5172     }
5173     return Vec;
5174   }
5175
5176   return SDValue();
5177 }
5178
5179 // Gather data to see if the operation can be modelled as a
5180 // shuffle in combination with VEXTs.
5181 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5182                                               SelectionDAG &DAG) const {
5183   SDLoc dl(Op);
5184   EVT VT = Op.getValueType();
5185   unsigned NumElts = VT.getVectorNumElements();
5186
5187   SmallVector<SDValue, 2> SourceVecs;
5188   SmallVector<unsigned, 2> MinElts;
5189   SmallVector<unsigned, 2> MaxElts;
5190
5191   for (unsigned i = 0; i < NumElts; ++i) {
5192     SDValue V = Op.getOperand(i);
5193     if (V.getOpcode() == ISD::UNDEF)
5194       continue;
5195     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5196       // A shuffle can only come from building a vector from various
5197       // elements of other vectors.
5198       return SDValue();
5199     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5200                VT.getVectorElementType()) {
5201       // This code doesn't know how to handle shuffles where the vector
5202       // element types do not match (this happens because type legalization
5203       // promotes the return type of EXTRACT_VECTOR_ELT).
5204       // FIXME: It might be appropriate to extend this code to handle
5205       // mismatched types.
5206       return SDValue();
5207     }
5208
5209     // Record this extraction against the appropriate vector if possible...
5210     SDValue SourceVec = V.getOperand(0);
5211     // If the element number isn't a constant, we can't effectively
5212     // analyze what's going on.
5213     if (!isa<ConstantSDNode>(V.getOperand(1)))
5214       return SDValue();
5215     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5216     bool FoundSource = false;
5217     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5218       if (SourceVecs[j] == SourceVec) {
5219         if (MinElts[j] > EltNo)
5220           MinElts[j] = EltNo;
5221         if (MaxElts[j] < EltNo)
5222           MaxElts[j] = EltNo;
5223         FoundSource = true;
5224         break;
5225       }
5226     }
5227
5228     // Or record a new source if not...
5229     if (!FoundSource) {
5230       SourceVecs.push_back(SourceVec);
5231       MinElts.push_back(EltNo);
5232       MaxElts.push_back(EltNo);
5233     }
5234   }
5235
5236   // Currently only do something sane when at most two source vectors
5237   // involved.
5238   if (SourceVecs.size() > 2)
5239     return SDValue();
5240
5241   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5242   int VEXTOffsets[2] = {0, 0};
5243
5244   // This loop extracts the usage patterns of the source vectors
5245   // and prepares appropriate SDValues for a shuffle if possible.
5246   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5247     if (SourceVecs[i].getValueType() == VT) {
5248       // No VEXT necessary
5249       ShuffleSrcs[i] = SourceVecs[i];
5250       VEXTOffsets[i] = 0;
5251       continue;
5252     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5253       // It probably isn't worth padding out a smaller vector just to
5254       // break it down again in a shuffle.
5255       return SDValue();
5256     }
5257
5258     // Since only 64-bit and 128-bit vectors are legal on ARM and
5259     // we've eliminated the other cases...
5260     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5261            "unexpected vector sizes in ReconstructShuffle");
5262
5263     if (MaxElts[i] - MinElts[i] >= NumElts) {
5264       // Span too large for a VEXT to cope
5265       return SDValue();
5266     }
5267
5268     if (MinElts[i] >= NumElts) {
5269       // The extraction can just take the second half
5270       VEXTOffsets[i] = NumElts;
5271       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5272                                    SourceVecs[i],
5273                                    DAG.getIntPtrConstant(NumElts));
5274     } else if (MaxElts[i] < NumElts) {
5275       // The extraction can just take the first half
5276       VEXTOffsets[i] = 0;
5277       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5278                                    SourceVecs[i],
5279                                    DAG.getIntPtrConstant(0));
5280     } else {
5281       // An actual VEXT is needed
5282       VEXTOffsets[i] = MinElts[i];
5283       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5284                                      SourceVecs[i],
5285                                      DAG.getIntPtrConstant(0));
5286       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5287                                      SourceVecs[i],
5288                                      DAG.getIntPtrConstant(NumElts));
5289       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5290                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5291     }
5292   }
5293
5294   SmallVector<int, 8> Mask;
5295
5296   for (unsigned i = 0; i < NumElts; ++i) {
5297     SDValue Entry = Op.getOperand(i);
5298     if (Entry.getOpcode() == ISD::UNDEF) {
5299       Mask.push_back(-1);
5300       continue;
5301     }
5302
5303     SDValue ExtractVec = Entry.getOperand(0);
5304     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5305                                           .getOperand(1))->getSExtValue();
5306     if (ExtractVec == SourceVecs[0]) {
5307       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5308     } else {
5309       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5310     }
5311   }
5312
5313   // Final check before we try to produce nonsense...
5314   if (isShuffleMaskLegal(Mask, VT))
5315     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5316                                 &Mask[0]);
5317
5318   return SDValue();
5319 }
5320
5321 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5322 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5323 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5324 /// are assumed to be legal.
5325 bool
5326 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5327                                       EVT VT) const {
5328   if (VT.getVectorNumElements() == 4 &&
5329       (VT.is128BitVector() || VT.is64BitVector())) {
5330     unsigned PFIndexes[4];
5331     for (unsigned i = 0; i != 4; ++i) {
5332       if (M[i] < 0)
5333         PFIndexes[i] = 8;
5334       else
5335         PFIndexes[i] = M[i];
5336     }
5337
5338     // Compute the index in the perfect shuffle table.
5339     unsigned PFTableIndex =
5340       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5341     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5342     unsigned Cost = (PFEntry >> 30);
5343
5344     if (Cost <= 4)
5345       return true;
5346   }
5347
5348   bool ReverseVEXT;
5349   unsigned Imm, WhichResult;
5350
5351   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5352   return (EltSize >= 32 ||
5353           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5354           isVREVMask(M, VT, 64) ||
5355           isVREVMask(M, VT, 32) ||
5356           isVREVMask(M, VT, 16) ||
5357           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5358           isVTBLMask(M, VT) ||
5359           isVTRNMask(M, VT, WhichResult) ||
5360           isVUZPMask(M, VT, WhichResult) ||
5361           isVZIPMask(M, VT, WhichResult) ||
5362           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5363           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5364           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5365           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5366 }
5367
5368 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5369 /// the specified operations to build the shuffle.
5370 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5371                                       SDValue RHS, SelectionDAG &DAG,
5372                                       SDLoc dl) {
5373   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5374   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5375   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5376
5377   enum {
5378     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5379     OP_VREV,
5380     OP_VDUP0,
5381     OP_VDUP1,
5382     OP_VDUP2,
5383     OP_VDUP3,
5384     OP_VEXT1,
5385     OP_VEXT2,
5386     OP_VEXT3,
5387     OP_VUZPL, // VUZP, left result
5388     OP_VUZPR, // VUZP, right result
5389     OP_VZIPL, // VZIP, left result
5390     OP_VZIPR, // VZIP, right result
5391     OP_VTRNL, // VTRN, left result
5392     OP_VTRNR  // VTRN, right result
5393   };
5394
5395   if (OpNum == OP_COPY) {
5396     if (LHSID == (1*9+2)*9+3) return LHS;
5397     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5398     return RHS;
5399   }
5400
5401   SDValue OpLHS, OpRHS;
5402   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5403   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5404   EVT VT = OpLHS.getValueType();
5405
5406   switch (OpNum) {
5407   default: llvm_unreachable("Unknown shuffle opcode!");
5408   case OP_VREV:
5409     // VREV divides the vector in half and swaps within the half.
5410     if (VT.getVectorElementType() == MVT::i32 ||
5411         VT.getVectorElementType() == MVT::f32)
5412       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5413     // vrev <4 x i16> -> VREV32
5414     if (VT.getVectorElementType() == MVT::i16)
5415       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5416     // vrev <4 x i8> -> VREV16
5417     assert(VT.getVectorElementType() == MVT::i8);
5418     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5419   case OP_VDUP0:
5420   case OP_VDUP1:
5421   case OP_VDUP2:
5422   case OP_VDUP3:
5423     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5424                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5425   case OP_VEXT1:
5426   case OP_VEXT2:
5427   case OP_VEXT3:
5428     return DAG.getNode(ARMISD::VEXT, dl, VT,
5429                        OpLHS, OpRHS,
5430                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5431   case OP_VUZPL:
5432   case OP_VUZPR:
5433     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5434                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5435   case OP_VZIPL:
5436   case OP_VZIPR:
5437     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5438                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5439   case OP_VTRNL:
5440   case OP_VTRNR:
5441     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5442                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5443   }
5444 }
5445
5446 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5447                                        ArrayRef<int> ShuffleMask,
5448                                        SelectionDAG &DAG) {
5449   // Check to see if we can use the VTBL instruction.
5450   SDValue V1 = Op.getOperand(0);
5451   SDValue V2 = Op.getOperand(1);
5452   SDLoc DL(Op);
5453
5454   SmallVector<SDValue, 8> VTBLMask;
5455   for (ArrayRef<int>::iterator
5456          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5457     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5458
5459   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5460     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5461                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5462
5463   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5464                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5465 }
5466
5467 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5468                                                       SelectionDAG &DAG) {
5469   SDLoc DL(Op);
5470   SDValue OpLHS = Op.getOperand(0);
5471   EVT VT = OpLHS.getValueType();
5472
5473   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5474          "Expect an v8i16/v16i8 type");
5475   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5476   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5477   // extract the first 8 bytes into the top double word and the last 8 bytes
5478   // into the bottom double word. The v8i16 case is similar.
5479   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5480   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5481                      DAG.getConstant(ExtractNum, MVT::i32));
5482 }
5483
5484 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5485   SDValue V1 = Op.getOperand(0);
5486   SDValue V2 = Op.getOperand(1);
5487   SDLoc dl(Op);
5488   EVT VT = Op.getValueType();
5489   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5490
5491   // Convert shuffles that are directly supported on NEON to target-specific
5492   // DAG nodes, instead of keeping them as shuffles and matching them again
5493   // during code selection.  This is more efficient and avoids the possibility
5494   // of inconsistencies between legalization and selection.
5495   // FIXME: floating-point vectors should be canonicalized to integer vectors
5496   // of the same time so that they get CSEd properly.
5497   ArrayRef<int> ShuffleMask = SVN->getMask();
5498
5499   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5500   if (EltSize <= 32) {
5501     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5502       int Lane = SVN->getSplatIndex();
5503       // If this is undef splat, generate it via "just" vdup, if possible.
5504       if (Lane == -1) Lane = 0;
5505
5506       // Test if V1 is a SCALAR_TO_VECTOR.
5507       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5508         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5509       }
5510       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5511       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5512       // reaches it).
5513       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5514           !isa<ConstantSDNode>(V1.getOperand(0))) {
5515         bool IsScalarToVector = true;
5516         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5517           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5518             IsScalarToVector = false;
5519             break;
5520           }
5521         if (IsScalarToVector)
5522           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5523       }
5524       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5525                          DAG.getConstant(Lane, MVT::i32));
5526     }
5527
5528     bool ReverseVEXT;
5529     unsigned Imm;
5530     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5531       if (ReverseVEXT)
5532         std::swap(V1, V2);
5533       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5534                          DAG.getConstant(Imm, MVT::i32));
5535     }
5536
5537     if (isVREVMask(ShuffleMask, VT, 64))
5538       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5539     if (isVREVMask(ShuffleMask, VT, 32))
5540       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5541     if (isVREVMask(ShuffleMask, VT, 16))
5542       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5543
5544     if (V2->getOpcode() == ISD::UNDEF &&
5545         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5546       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5547                          DAG.getConstant(Imm, MVT::i32));
5548     }
5549
5550     // Check for Neon shuffles that modify both input vectors in place.
5551     // If both results are used, i.e., if there are two shuffles with the same
5552     // source operands and with masks corresponding to both results of one of
5553     // these operations, DAG memoization will ensure that a single node is
5554     // used for both shuffles.
5555     unsigned WhichResult;
5556     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5557       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5558                          V1, V2).getValue(WhichResult);
5559     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5560       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5561                          V1, V2).getValue(WhichResult);
5562     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5563       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5564                          V1, V2).getValue(WhichResult);
5565
5566     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5567       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5568                          V1, V1).getValue(WhichResult);
5569     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5570       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5571                          V1, V1).getValue(WhichResult);
5572     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5573       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5574                          V1, V1).getValue(WhichResult);
5575   }
5576
5577   // If the shuffle is not directly supported and it has 4 elements, use
5578   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5579   unsigned NumElts = VT.getVectorNumElements();
5580   if (NumElts == 4) {
5581     unsigned PFIndexes[4];
5582     for (unsigned i = 0; i != 4; ++i) {
5583       if (ShuffleMask[i] < 0)
5584         PFIndexes[i] = 8;
5585       else
5586         PFIndexes[i] = ShuffleMask[i];
5587     }
5588
5589     // Compute the index in the perfect shuffle table.
5590     unsigned PFTableIndex =
5591       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5592     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5593     unsigned Cost = (PFEntry >> 30);
5594
5595     if (Cost <= 4)
5596       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5597   }
5598
5599   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5600   if (EltSize >= 32) {
5601     // Do the expansion with floating-point types, since that is what the VFP
5602     // registers are defined to use, and since i64 is not legal.
5603     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5604     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5605     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5606     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5607     SmallVector<SDValue, 8> Ops;
5608     for (unsigned i = 0; i < NumElts; ++i) {
5609       if (ShuffleMask[i] < 0)
5610         Ops.push_back(DAG.getUNDEF(EltVT));
5611       else
5612         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5613                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5614                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5615                                                   MVT::i32)));
5616     }
5617     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5618     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5619   }
5620
5621   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5622     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5623
5624   if (VT == MVT::v8i8) {
5625     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5626     if (NewOp.getNode())
5627       return NewOp;
5628   }
5629
5630   return SDValue();
5631 }
5632
5633 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5634   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5635   SDValue Lane = Op.getOperand(2);
5636   if (!isa<ConstantSDNode>(Lane))
5637     return SDValue();
5638
5639   return Op;
5640 }
5641
5642 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5643   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5644   SDValue Lane = Op.getOperand(1);
5645   if (!isa<ConstantSDNode>(Lane))
5646     return SDValue();
5647
5648   SDValue Vec = Op.getOperand(0);
5649   if (Op.getValueType() == MVT::i32 &&
5650       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5651     SDLoc dl(Op);
5652     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5653   }
5654
5655   return Op;
5656 }
5657
5658 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5659   // The only time a CONCAT_VECTORS operation can have legal types is when
5660   // two 64-bit vectors are concatenated to a 128-bit vector.
5661   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5662          "unexpected CONCAT_VECTORS");
5663   SDLoc dl(Op);
5664   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5665   SDValue Op0 = Op.getOperand(0);
5666   SDValue Op1 = Op.getOperand(1);
5667   if (Op0.getOpcode() != ISD::UNDEF)
5668     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5669                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5670                       DAG.getIntPtrConstant(0));
5671   if (Op1.getOpcode() != ISD::UNDEF)
5672     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5673                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5674                       DAG.getIntPtrConstant(1));
5675   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5676 }
5677
5678 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5679 /// element has been zero/sign-extended, depending on the isSigned parameter,
5680 /// from an integer type half its size.
5681 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5682                                    bool isSigned) {
5683   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5684   EVT VT = N->getValueType(0);
5685   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5686     SDNode *BVN = N->getOperand(0).getNode();
5687     if (BVN->getValueType(0) != MVT::v4i32 ||
5688         BVN->getOpcode() != ISD::BUILD_VECTOR)
5689       return false;
5690     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5691     unsigned HiElt = 1 - LoElt;
5692     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5693     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5694     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5695     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5696     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5697       return false;
5698     if (isSigned) {
5699       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5700           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5701         return true;
5702     } else {
5703       if (Hi0->isNullValue() && Hi1->isNullValue())
5704         return true;
5705     }
5706     return false;
5707   }
5708
5709   if (N->getOpcode() != ISD::BUILD_VECTOR)
5710     return false;
5711
5712   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5713     SDNode *Elt = N->getOperand(i).getNode();
5714     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5715       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5716       unsigned HalfSize = EltSize / 2;
5717       if (isSigned) {
5718         if (!isIntN(HalfSize, C->getSExtValue()))
5719           return false;
5720       } else {
5721         if (!isUIntN(HalfSize, C->getZExtValue()))
5722           return false;
5723       }
5724       continue;
5725     }
5726     return false;
5727   }
5728
5729   return true;
5730 }
5731
5732 /// isSignExtended - Check if a node is a vector value that is sign-extended
5733 /// or a constant BUILD_VECTOR with sign-extended elements.
5734 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5735   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5736     return true;
5737   if (isExtendedBUILD_VECTOR(N, DAG, true))
5738     return true;
5739   return false;
5740 }
5741
5742 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5743 /// or a constant BUILD_VECTOR with zero-extended elements.
5744 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5745   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5746     return true;
5747   if (isExtendedBUILD_VECTOR(N, DAG, false))
5748     return true;
5749   return false;
5750 }
5751
5752 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5753   if (OrigVT.getSizeInBits() >= 64)
5754     return OrigVT;
5755
5756   assert(OrigVT.isSimple() && "Expecting a simple value type");
5757
5758   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5759   switch (OrigSimpleTy) {
5760   default: llvm_unreachable("Unexpected Vector Type");
5761   case MVT::v2i8:
5762   case MVT::v2i16:
5763      return MVT::v2i32;
5764   case MVT::v4i8:
5765     return  MVT::v4i16;
5766   }
5767 }
5768
5769 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5770 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5771 /// We insert the required extension here to get the vector to fill a D register.
5772 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5773                                             const EVT &OrigTy,
5774                                             const EVT &ExtTy,
5775                                             unsigned ExtOpcode) {
5776   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5777   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5778   // 64-bits we need to insert a new extension so that it will be 64-bits.
5779   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5780   if (OrigTy.getSizeInBits() >= 64)
5781     return N;
5782
5783   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5784   EVT NewVT = getExtensionTo64Bits(OrigTy);
5785
5786   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5787 }
5788
5789 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5790 /// does not do any sign/zero extension. If the original vector is less
5791 /// than 64 bits, an appropriate extension will be added after the load to
5792 /// reach a total size of 64 bits. We have to add the extension separately
5793 /// because ARM does not have a sign/zero extending load for vectors.
5794 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5795   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5796
5797   // The load already has the right type.
5798   if (ExtendedTy == LD->getMemoryVT())
5799     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5800                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5801                 LD->isNonTemporal(), LD->isInvariant(),
5802                 LD->getAlignment());
5803
5804   // We need to create a zextload/sextload. We cannot just create a load
5805   // followed by a zext/zext node because LowerMUL is also run during normal
5806   // operation legalization where we can't create illegal types.
5807   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5808                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5809                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5810                         LD->isNonTemporal(), LD->getAlignment());
5811 }
5812
5813 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5814 /// extending load, or BUILD_VECTOR with extended elements, return the
5815 /// unextended value. The unextended vector should be 64 bits so that it can
5816 /// be used as an operand to a VMULL instruction. If the original vector size
5817 /// before extension is less than 64 bits we add a an extension to resize
5818 /// the vector to 64 bits.
5819 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5820   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5821     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5822                                         N->getOperand(0)->getValueType(0),
5823                                         N->getValueType(0),
5824                                         N->getOpcode());
5825
5826   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5827     return SkipLoadExtensionForVMULL(LD, DAG);
5828
5829   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5830   // have been legalized as a BITCAST from v4i32.
5831   if (N->getOpcode() == ISD::BITCAST) {
5832     SDNode *BVN = N->getOperand(0).getNode();
5833     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5834            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5835     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5836     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5837                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5838   }
5839   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5840   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5841   EVT VT = N->getValueType(0);
5842   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5843   unsigned NumElts = VT.getVectorNumElements();
5844   MVT TruncVT = MVT::getIntegerVT(EltSize);
5845   SmallVector<SDValue, 8> Ops;
5846   for (unsigned i = 0; i != NumElts; ++i) {
5847     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5848     const APInt &CInt = C->getAPIntValue();
5849     // Element types smaller than 32 bits are not legal, so use i32 elements.
5850     // The values are implicitly truncated so sext vs. zext doesn't matter.
5851     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5852   }
5853   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5854                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5855 }
5856
5857 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5858   unsigned Opcode = N->getOpcode();
5859   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5860     SDNode *N0 = N->getOperand(0).getNode();
5861     SDNode *N1 = N->getOperand(1).getNode();
5862     return N0->hasOneUse() && N1->hasOneUse() &&
5863       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5864   }
5865   return false;
5866 }
5867
5868 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5869   unsigned Opcode = N->getOpcode();
5870   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5871     SDNode *N0 = N->getOperand(0).getNode();
5872     SDNode *N1 = N->getOperand(1).getNode();
5873     return N0->hasOneUse() && N1->hasOneUse() &&
5874       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5875   }
5876   return false;
5877 }
5878
5879 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5880   // Multiplications are only custom-lowered for 128-bit vectors so that
5881   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5882   EVT VT = Op.getValueType();
5883   assert(VT.is128BitVector() && VT.isInteger() &&
5884          "unexpected type for custom-lowering ISD::MUL");
5885   SDNode *N0 = Op.getOperand(0).getNode();
5886   SDNode *N1 = Op.getOperand(1).getNode();
5887   unsigned NewOpc = 0;
5888   bool isMLA = false;
5889   bool isN0SExt = isSignExtended(N0, DAG);
5890   bool isN1SExt = isSignExtended(N1, DAG);
5891   if (isN0SExt && isN1SExt)
5892     NewOpc = ARMISD::VMULLs;
5893   else {
5894     bool isN0ZExt = isZeroExtended(N0, DAG);
5895     bool isN1ZExt = isZeroExtended(N1, DAG);
5896     if (isN0ZExt && isN1ZExt)
5897       NewOpc = ARMISD::VMULLu;
5898     else if (isN1SExt || isN1ZExt) {
5899       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5900       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5901       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5902         NewOpc = ARMISD::VMULLs;
5903         isMLA = true;
5904       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5905         NewOpc = ARMISD::VMULLu;
5906         isMLA = true;
5907       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5908         std::swap(N0, N1);
5909         NewOpc = ARMISD::VMULLu;
5910         isMLA = true;
5911       }
5912     }
5913
5914     if (!NewOpc) {
5915       if (VT == MVT::v2i64)
5916         // Fall through to expand this.  It is not legal.
5917         return SDValue();
5918       else
5919         // Other vector multiplications are legal.
5920         return Op;
5921     }
5922   }
5923
5924   // Legalize to a VMULL instruction.
5925   SDLoc DL(Op);
5926   SDValue Op0;
5927   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5928   if (!isMLA) {
5929     Op0 = SkipExtensionForVMULL(N0, DAG);
5930     assert(Op0.getValueType().is64BitVector() &&
5931            Op1.getValueType().is64BitVector() &&
5932            "unexpected types for extended operands to VMULL");
5933     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5934   }
5935
5936   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5937   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5938   //   vmull q0, d4, d6
5939   //   vmlal q0, d5, d6
5940   // is faster than
5941   //   vaddl q0, d4, d5
5942   //   vmovl q1, d6
5943   //   vmul  q0, q0, q1
5944   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5945   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5946   EVT Op1VT = Op1.getValueType();
5947   return DAG.getNode(N0->getOpcode(), DL, VT,
5948                      DAG.getNode(NewOpc, DL, VT,
5949                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5950                      DAG.getNode(NewOpc, DL, VT,
5951                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5952 }
5953
5954 static SDValue
5955 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5956   // Convert to float
5957   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5958   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5959   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5960   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5961   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5962   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5963   // Get reciprocal estimate.
5964   // float4 recip = vrecpeq_f32(yf);
5965   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5966                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5967   // Because char has a smaller range than uchar, we can actually get away
5968   // without any newton steps.  This requires that we use a weird bias
5969   // of 0xb000, however (again, this has been exhaustively tested).
5970   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5971   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5972   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5973   Y = DAG.getConstant(0xb000, MVT::i32);
5974   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5975   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5976   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5977   // Convert back to short.
5978   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5979   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5980   return X;
5981 }
5982
5983 static SDValue
5984 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5985   SDValue N2;
5986   // Convert to float.
5987   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5988   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5989   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5990   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5991   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5992   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5993
5994   // Use reciprocal estimate and one refinement step.
5995   // float4 recip = vrecpeq_f32(yf);
5996   // recip *= vrecpsq_f32(yf, recip);
5997   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5998                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5999   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6000                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6001                    N1, N2);
6002   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6003   // Because short has a smaller range than ushort, we can actually get away
6004   // with only a single newton step.  This requires that we use a weird bias
6005   // of 89, however (again, this has been exhaustively tested).
6006   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6007   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6008   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6009   N1 = DAG.getConstant(0x89, MVT::i32);
6010   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6011   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6012   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6013   // Convert back to integer and return.
6014   // return vmovn_s32(vcvt_s32_f32(result));
6015   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6016   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6017   return N0;
6018 }
6019
6020 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6021   EVT VT = Op.getValueType();
6022   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6023          "unexpected type for custom-lowering ISD::SDIV");
6024
6025   SDLoc dl(Op);
6026   SDValue N0 = Op.getOperand(0);
6027   SDValue N1 = Op.getOperand(1);
6028   SDValue N2, N3;
6029
6030   if (VT == MVT::v8i8) {
6031     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6032     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6033
6034     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6035                      DAG.getIntPtrConstant(4));
6036     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6037                      DAG.getIntPtrConstant(4));
6038     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6039                      DAG.getIntPtrConstant(0));
6040     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6041                      DAG.getIntPtrConstant(0));
6042
6043     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6044     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6045
6046     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6047     N0 = LowerCONCAT_VECTORS(N0, DAG);
6048
6049     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6050     return N0;
6051   }
6052   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6053 }
6054
6055 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6056   EVT VT = Op.getValueType();
6057   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6058          "unexpected type for custom-lowering ISD::UDIV");
6059
6060   SDLoc dl(Op);
6061   SDValue N0 = Op.getOperand(0);
6062   SDValue N1 = Op.getOperand(1);
6063   SDValue N2, N3;
6064
6065   if (VT == MVT::v8i8) {
6066     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6067     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6068
6069     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6070                      DAG.getIntPtrConstant(4));
6071     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6072                      DAG.getIntPtrConstant(4));
6073     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6074                      DAG.getIntPtrConstant(0));
6075     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6076                      DAG.getIntPtrConstant(0));
6077
6078     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6079     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6080
6081     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6082     N0 = LowerCONCAT_VECTORS(N0, DAG);
6083
6084     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6085                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6086                      N0);
6087     return N0;
6088   }
6089
6090   // v4i16 sdiv ... Convert to float.
6091   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6092   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6093   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6094   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6095   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6096   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6097
6098   // Use reciprocal estimate and two refinement steps.
6099   // float4 recip = vrecpeq_f32(yf);
6100   // recip *= vrecpsq_f32(yf, recip);
6101   // recip *= vrecpsq_f32(yf, recip);
6102   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6103                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6104   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6105                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6106                    BN1, N2);
6107   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6108   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6109                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6110                    BN1, N2);
6111   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6112   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6113   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6114   // and that it will never cause us to return an answer too large).
6115   // float4 result = as_float4(as_int4(xf*recip) + 2);
6116   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6117   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6118   N1 = DAG.getConstant(2, MVT::i32);
6119   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6120   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6121   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6122   // Convert back to integer and return.
6123   // return vmovn_u32(vcvt_s32_f32(result));
6124   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6125   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6126   return N0;
6127 }
6128
6129 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6130   EVT VT = Op.getNode()->getValueType(0);
6131   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6132
6133   unsigned Opc;
6134   bool ExtraOp = false;
6135   switch (Op.getOpcode()) {
6136   default: llvm_unreachable("Invalid code");
6137   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6138   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6139   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6140   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6141   }
6142
6143   if (!ExtraOp)
6144     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6145                        Op.getOperand(1));
6146   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6147                      Op.getOperand(1), Op.getOperand(2));
6148 }
6149
6150 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6151   assert(Subtarget->isTargetDarwin());
6152
6153   // For iOS, we want to call an alternative entry point: __sincos_stret,
6154   // return values are passed via sret.
6155   SDLoc dl(Op);
6156   SDValue Arg = Op.getOperand(0);
6157   EVT ArgVT = Arg.getValueType();
6158   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6159
6160   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6161   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6162
6163   // Pair of floats / doubles used to pass the result.
6164   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6165
6166   // Create stack object for sret.
6167   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6168   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6169   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6170   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6171
6172   ArgListTy Args;
6173   ArgListEntry Entry;
6174
6175   Entry.Node = SRet;
6176   Entry.Ty = RetTy->getPointerTo();
6177   Entry.isSExt = false;
6178   Entry.isZExt = false;
6179   Entry.isSRet = true;
6180   Args.push_back(Entry);
6181
6182   Entry.Node = Arg;
6183   Entry.Ty = ArgTy;
6184   Entry.isSExt = false;
6185   Entry.isZExt = false;
6186   Args.push_back(Entry);
6187
6188   const char *LibcallName  = (ArgVT == MVT::f64)
6189   ? "__sincos_stret" : "__sincosf_stret";
6190   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6191
6192   TargetLowering::CallLoweringInfo CLI(DAG);
6193   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6194     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6195                std::move(Args), 0)
6196     .setDiscardResult();
6197
6198   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6199
6200   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6201                                 MachinePointerInfo(), false, false, false, 0);
6202
6203   // Address of cos field.
6204   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6205                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6206   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6207                                 MachinePointerInfo(), false, false, false, 0);
6208
6209   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6210   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6211                      LoadSin.getValue(0), LoadCos.getValue(0));
6212 }
6213
6214 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6215   // Monotonic load/store is legal for all targets
6216   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6217     return Op;
6218
6219   // Acquire/Release load/store is not legal for targets without a
6220   // dmb or equivalent available.
6221   return SDValue();
6222 }
6223
6224 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6225                                     SmallVectorImpl<SDValue> &Results,
6226                                     SelectionDAG &DAG,
6227                                     const ARMSubtarget *Subtarget) {
6228   SDLoc DL(N);
6229   SDValue Cycles32, OutChain;
6230
6231   if (Subtarget->hasPerfMon()) {
6232     // Under Power Management extensions, the cycle-count is:
6233     //    mrc p15, #0, <Rt>, c9, c13, #0
6234     SDValue Ops[] = { N->getOperand(0), // Chain
6235                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6236                       DAG.getConstant(15, MVT::i32),
6237                       DAG.getConstant(0, MVT::i32),
6238                       DAG.getConstant(9, MVT::i32),
6239                       DAG.getConstant(13, MVT::i32),
6240                       DAG.getConstant(0, MVT::i32)
6241     };
6242
6243     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6244                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6245     OutChain = Cycles32.getValue(1);
6246   } else {
6247     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6248     // there are older ARM CPUs that have implementation-specific ways of
6249     // obtaining this information (FIXME!).
6250     Cycles32 = DAG.getConstant(0, MVT::i32);
6251     OutChain = DAG.getEntryNode();
6252   }
6253
6254
6255   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6256                                  Cycles32, DAG.getConstant(0, MVT::i32));
6257   Results.push_back(Cycles64);
6258   Results.push_back(OutChain);
6259 }
6260
6261 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6262   switch (Op.getOpcode()) {
6263   default: llvm_unreachable("Don't know how to custom lower this!");
6264   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6265   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6266   case ISD::GlobalAddress:
6267     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6268     default: llvm_unreachable("unknown object format");
6269     case Triple::COFF:
6270       return LowerGlobalAddressWindows(Op, DAG);
6271     case Triple::ELF:
6272       return LowerGlobalAddressELF(Op, DAG);
6273     case Triple::MachO:
6274       return LowerGlobalAddressDarwin(Op, DAG);
6275     }
6276   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6277   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6278   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6279   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6280   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6281   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6282   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6283   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6284   case ISD::SINT_TO_FP:
6285   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6286   case ISD::FP_TO_SINT:
6287   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6288   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6289   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6290   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6291   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6292   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6293   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6294   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6295                                                                Subtarget);
6296   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6297   case ISD::SHL:
6298   case ISD::SRL:
6299   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6300   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6301   case ISD::SRL_PARTS:
6302   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6303   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6304   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6305   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6306   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6307   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6308   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6309   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6310   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6311   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6312   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6313   case ISD::MUL:           return LowerMUL(Op, DAG);
6314   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6315   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6316   case ISD::ADDC:
6317   case ISD::ADDE:
6318   case ISD::SUBC:
6319   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6320   case ISD::SADDO:
6321   case ISD::UADDO:
6322   case ISD::SSUBO:
6323   case ISD::USUBO:
6324     return LowerXALUO(Op, DAG);
6325   case ISD::ATOMIC_LOAD:
6326   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6327   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6328   case ISD::SDIVREM:
6329   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6330   case ISD::DYNAMIC_STACKALLOC:
6331     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6332       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6333     llvm_unreachable("Don't know how to custom lower this!");
6334   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6335   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6336   }
6337 }
6338
6339 /// ReplaceNodeResults - Replace the results of node with an illegal result
6340 /// type with new values built out of custom code.
6341 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6342                                            SmallVectorImpl<SDValue>&Results,
6343                                            SelectionDAG &DAG) const {
6344   SDValue Res;
6345   switch (N->getOpcode()) {
6346   default:
6347     llvm_unreachable("Don't know how to custom expand this!");
6348   case ISD::BITCAST:
6349     Res = ExpandBITCAST(N, DAG);
6350     break;
6351   case ISD::SRL:
6352   case ISD::SRA:
6353     Res = Expand64BitShift(N, DAG, Subtarget);
6354     break;
6355   case ISD::READCYCLECOUNTER:
6356     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6357     return;
6358   }
6359   if (Res.getNode())
6360     Results.push_back(Res);
6361 }
6362
6363 //===----------------------------------------------------------------------===//
6364 //                           ARM Scheduler Hooks
6365 //===----------------------------------------------------------------------===//
6366
6367 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6368 /// registers the function context.
6369 void ARMTargetLowering::
6370 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6371                        MachineBasicBlock *DispatchBB, int FI) const {
6372   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6373   DebugLoc dl = MI->getDebugLoc();
6374   MachineFunction *MF = MBB->getParent();
6375   MachineRegisterInfo *MRI = &MF->getRegInfo();
6376   MachineConstantPool *MCP = MF->getConstantPool();
6377   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6378   const Function *F = MF->getFunction();
6379
6380   bool isThumb = Subtarget->isThumb();
6381   bool isThumb2 = Subtarget->isThumb2();
6382
6383   unsigned PCLabelId = AFI->createPICLabelUId();
6384   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6385   ARMConstantPoolValue *CPV =
6386     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6387   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6388
6389   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6390                                            : &ARM::GPRRegClass;
6391
6392   // Grab constant pool and fixed stack memory operands.
6393   MachineMemOperand *CPMMO =
6394     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6395                              MachineMemOperand::MOLoad, 4, 4);
6396
6397   MachineMemOperand *FIMMOSt =
6398     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6399                              MachineMemOperand::MOStore, 4, 4);
6400
6401   // Load the address of the dispatch MBB into the jump buffer.
6402   if (isThumb2) {
6403     // Incoming value: jbuf
6404     //   ldr.n  r5, LCPI1_1
6405     //   orr    r5, r5, #1
6406     //   add    r5, pc
6407     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6408     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6409     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6410                    .addConstantPoolIndex(CPI)
6411                    .addMemOperand(CPMMO));
6412     // Set the low bit because of thumb mode.
6413     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6414     AddDefaultCC(
6415       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6416                      .addReg(NewVReg1, RegState::Kill)
6417                      .addImm(0x01)));
6418     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6419     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6420       .addReg(NewVReg2, RegState::Kill)
6421       .addImm(PCLabelId);
6422     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6423                    .addReg(NewVReg3, RegState::Kill)
6424                    .addFrameIndex(FI)
6425                    .addImm(36)  // &jbuf[1] :: pc
6426                    .addMemOperand(FIMMOSt));
6427   } else if (isThumb) {
6428     // Incoming value: jbuf
6429     //   ldr.n  r1, LCPI1_4
6430     //   add    r1, pc
6431     //   mov    r2, #1
6432     //   orrs   r1, r2
6433     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6434     //   str    r1, [r2]
6435     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6436     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6437                    .addConstantPoolIndex(CPI)
6438                    .addMemOperand(CPMMO));
6439     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6440     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6441       .addReg(NewVReg1, RegState::Kill)
6442       .addImm(PCLabelId);
6443     // Set the low bit because of thumb mode.
6444     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6445     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6446                    .addReg(ARM::CPSR, RegState::Define)
6447                    .addImm(1));
6448     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6449     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6450                    .addReg(ARM::CPSR, RegState::Define)
6451                    .addReg(NewVReg2, RegState::Kill)
6452                    .addReg(NewVReg3, RegState::Kill));
6453     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6454     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6455             .addFrameIndex(FI)
6456             .addImm(36); // &jbuf[1] :: pc
6457     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6458                    .addReg(NewVReg4, RegState::Kill)
6459                    .addReg(NewVReg5, RegState::Kill)
6460                    .addImm(0)
6461                    .addMemOperand(FIMMOSt));
6462   } else {
6463     // Incoming value: jbuf
6464     //   ldr  r1, LCPI1_1
6465     //   add  r1, pc, r1
6466     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6467     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6468     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6469                    .addConstantPoolIndex(CPI)
6470                    .addImm(0)
6471                    .addMemOperand(CPMMO));
6472     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6473     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6474                    .addReg(NewVReg1, RegState::Kill)
6475                    .addImm(PCLabelId));
6476     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6477                    .addReg(NewVReg2, RegState::Kill)
6478                    .addFrameIndex(FI)
6479                    .addImm(36)  // &jbuf[1] :: pc
6480                    .addMemOperand(FIMMOSt));
6481   }
6482 }
6483
6484 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6485                                               MachineBasicBlock *MBB) const {
6486   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6487   DebugLoc dl = MI->getDebugLoc();
6488   MachineFunction *MF = MBB->getParent();
6489   MachineRegisterInfo *MRI = &MF->getRegInfo();
6490   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6491   MachineFrameInfo *MFI = MF->getFrameInfo();
6492   int FI = MFI->getFunctionContextIndex();
6493
6494   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6495                                                         : &ARM::GPRnopcRegClass;
6496
6497   // Get a mapping of the call site numbers to all of the landing pads they're
6498   // associated with.
6499   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6500   unsigned MaxCSNum = 0;
6501   MachineModuleInfo &MMI = MF->getMMI();
6502   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6503        ++BB) {
6504     if (!BB->isLandingPad()) continue;
6505
6506     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6507     // pad.
6508     for (MachineBasicBlock::iterator
6509            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6510       if (!II->isEHLabel()) continue;
6511
6512       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6513       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6514
6515       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6516       for (SmallVectorImpl<unsigned>::iterator
6517              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6518            CSI != CSE; ++CSI) {
6519         CallSiteNumToLPad[*CSI].push_back(BB);
6520         MaxCSNum = std::max(MaxCSNum, *CSI);
6521       }
6522       break;
6523     }
6524   }
6525
6526   // Get an ordered list of the machine basic blocks for the jump table.
6527   std::vector<MachineBasicBlock*> LPadList;
6528   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6529   LPadList.reserve(CallSiteNumToLPad.size());
6530   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6531     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6532     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6533            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6534       LPadList.push_back(*II);
6535       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6536     }
6537   }
6538
6539   assert(!LPadList.empty() &&
6540          "No landing pad destinations for the dispatch jump table!");
6541
6542   // Create the jump table and associated information.
6543   MachineJumpTableInfo *JTI =
6544     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6545   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6546   unsigned UId = AFI->createJumpTableUId();
6547   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6548
6549   // Create the MBBs for the dispatch code.
6550
6551   // Shove the dispatch's address into the return slot in the function context.
6552   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6553   DispatchBB->setIsLandingPad();
6554
6555   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6556   unsigned trap_opcode;
6557   if (Subtarget->isThumb())
6558     trap_opcode = ARM::tTRAP;
6559   else
6560     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6561
6562   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6563   DispatchBB->addSuccessor(TrapBB);
6564
6565   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6566   DispatchBB->addSuccessor(DispContBB);
6567
6568   // Insert and MBBs.
6569   MF->insert(MF->end(), DispatchBB);
6570   MF->insert(MF->end(), DispContBB);
6571   MF->insert(MF->end(), TrapBB);
6572
6573   // Insert code into the entry block that creates and registers the function
6574   // context.
6575   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6576
6577   MachineMemOperand *FIMMOLd =
6578     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6579                              MachineMemOperand::MOLoad |
6580                              MachineMemOperand::MOVolatile, 4, 4);
6581
6582   MachineInstrBuilder MIB;
6583   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6584
6585   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6586   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6587
6588   // Add a register mask with no preserved registers.  This results in all
6589   // registers being marked as clobbered.
6590   MIB.addRegMask(RI.getNoPreservedMask());
6591
6592   unsigned NumLPads = LPadList.size();
6593   if (Subtarget->isThumb2()) {
6594     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6595     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6596                    .addFrameIndex(FI)
6597                    .addImm(4)
6598                    .addMemOperand(FIMMOLd));
6599
6600     if (NumLPads < 256) {
6601       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6602                      .addReg(NewVReg1)
6603                      .addImm(LPadList.size()));
6604     } else {
6605       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6606       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6607                      .addImm(NumLPads & 0xFFFF));
6608
6609       unsigned VReg2 = VReg1;
6610       if ((NumLPads & 0xFFFF0000) != 0) {
6611         VReg2 = MRI->createVirtualRegister(TRC);
6612         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6613                        .addReg(VReg1)
6614                        .addImm(NumLPads >> 16));
6615       }
6616
6617       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6618                      .addReg(NewVReg1)
6619                      .addReg(VReg2));
6620     }
6621
6622     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6623       .addMBB(TrapBB)
6624       .addImm(ARMCC::HI)
6625       .addReg(ARM::CPSR);
6626
6627     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6628     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6629                    .addJumpTableIndex(MJTI)
6630                    .addImm(UId));
6631
6632     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6633     AddDefaultCC(
6634       AddDefaultPred(
6635         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6636         .addReg(NewVReg3, RegState::Kill)
6637         .addReg(NewVReg1)
6638         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6639
6640     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6641       .addReg(NewVReg4, RegState::Kill)
6642       .addReg(NewVReg1)
6643       .addJumpTableIndex(MJTI)
6644       .addImm(UId);
6645   } else if (Subtarget->isThumb()) {
6646     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6647     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6648                    .addFrameIndex(FI)
6649                    .addImm(1)
6650                    .addMemOperand(FIMMOLd));
6651
6652     if (NumLPads < 256) {
6653       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6654                      .addReg(NewVReg1)
6655                      .addImm(NumLPads));
6656     } else {
6657       MachineConstantPool *ConstantPool = MF->getConstantPool();
6658       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6659       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6660
6661       // MachineConstantPool wants an explicit alignment.
6662       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6663       if (Align == 0)
6664         Align = getDataLayout()->getTypeAllocSize(C->getType());
6665       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6666
6667       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6668       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6669                      .addReg(VReg1, RegState::Define)
6670                      .addConstantPoolIndex(Idx));
6671       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6672                      .addReg(NewVReg1)
6673                      .addReg(VReg1));
6674     }
6675
6676     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6677       .addMBB(TrapBB)
6678       .addImm(ARMCC::HI)
6679       .addReg(ARM::CPSR);
6680
6681     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6682     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6683                    .addReg(ARM::CPSR, RegState::Define)
6684                    .addReg(NewVReg1)
6685                    .addImm(2));
6686
6687     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6688     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6689                    .addJumpTableIndex(MJTI)
6690                    .addImm(UId));
6691
6692     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6693     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6694                    .addReg(ARM::CPSR, RegState::Define)
6695                    .addReg(NewVReg2, RegState::Kill)
6696                    .addReg(NewVReg3));
6697
6698     MachineMemOperand *JTMMOLd =
6699       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6700                                MachineMemOperand::MOLoad, 4, 4);
6701
6702     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6703     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6704                    .addReg(NewVReg4, RegState::Kill)
6705                    .addImm(0)
6706                    .addMemOperand(JTMMOLd));
6707
6708     unsigned NewVReg6 = NewVReg5;
6709     if (RelocM == Reloc::PIC_) {
6710       NewVReg6 = MRI->createVirtualRegister(TRC);
6711       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6712                      .addReg(ARM::CPSR, RegState::Define)
6713                      .addReg(NewVReg5, RegState::Kill)
6714                      .addReg(NewVReg3));
6715     }
6716
6717     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6718       .addReg(NewVReg6, RegState::Kill)
6719       .addJumpTableIndex(MJTI)
6720       .addImm(UId);
6721   } else {
6722     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6723     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6724                    .addFrameIndex(FI)
6725                    .addImm(4)
6726                    .addMemOperand(FIMMOLd));
6727
6728     if (NumLPads < 256) {
6729       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6730                      .addReg(NewVReg1)
6731                      .addImm(NumLPads));
6732     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6733       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6734       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6735                      .addImm(NumLPads & 0xFFFF));
6736
6737       unsigned VReg2 = VReg1;
6738       if ((NumLPads & 0xFFFF0000) != 0) {
6739         VReg2 = MRI->createVirtualRegister(TRC);
6740         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6741                        .addReg(VReg1)
6742                        .addImm(NumLPads >> 16));
6743       }
6744
6745       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6746                      .addReg(NewVReg1)
6747                      .addReg(VReg2));
6748     } else {
6749       MachineConstantPool *ConstantPool = MF->getConstantPool();
6750       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6751       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6752
6753       // MachineConstantPool wants an explicit alignment.
6754       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6755       if (Align == 0)
6756         Align = getDataLayout()->getTypeAllocSize(C->getType());
6757       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6758
6759       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6760       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6761                      .addReg(VReg1, RegState::Define)
6762                      .addConstantPoolIndex(Idx)
6763                      .addImm(0));
6764       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6765                      .addReg(NewVReg1)
6766                      .addReg(VReg1, RegState::Kill));
6767     }
6768
6769     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6770       .addMBB(TrapBB)
6771       .addImm(ARMCC::HI)
6772       .addReg(ARM::CPSR);
6773
6774     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6775     AddDefaultCC(
6776       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6777                      .addReg(NewVReg1)
6778                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6779     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6780     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6781                    .addJumpTableIndex(MJTI)
6782                    .addImm(UId));
6783
6784     MachineMemOperand *JTMMOLd =
6785       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6786                                MachineMemOperand::MOLoad, 4, 4);
6787     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6788     AddDefaultPred(
6789       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6790       .addReg(NewVReg3, RegState::Kill)
6791       .addReg(NewVReg4)
6792       .addImm(0)
6793       .addMemOperand(JTMMOLd));
6794
6795     if (RelocM == Reloc::PIC_) {
6796       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6797         .addReg(NewVReg5, RegState::Kill)
6798         .addReg(NewVReg4)
6799         .addJumpTableIndex(MJTI)
6800         .addImm(UId);
6801     } else {
6802       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6803         .addReg(NewVReg5, RegState::Kill)
6804         .addJumpTableIndex(MJTI)
6805         .addImm(UId);
6806     }
6807   }
6808
6809   // Add the jump table entries as successors to the MBB.
6810   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6811   for (std::vector<MachineBasicBlock*>::iterator
6812          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6813     MachineBasicBlock *CurMBB = *I;
6814     if (SeenMBBs.insert(CurMBB).second)
6815       DispContBB->addSuccessor(CurMBB);
6816   }
6817
6818   // N.B. the order the invoke BBs are processed in doesn't matter here.
6819   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6820   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6821   for (MachineBasicBlock *BB : InvokeBBs) {
6822
6823     // Remove the landing pad successor from the invoke block and replace it
6824     // with the new dispatch block.
6825     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6826                                                   BB->succ_end());
6827     while (!Successors.empty()) {
6828       MachineBasicBlock *SMBB = Successors.pop_back_val();
6829       if (SMBB->isLandingPad()) {
6830         BB->removeSuccessor(SMBB);
6831         MBBLPads.push_back(SMBB);
6832       }
6833     }
6834
6835     BB->addSuccessor(DispatchBB);
6836
6837     // Find the invoke call and mark all of the callee-saved registers as
6838     // 'implicit defined' so that they're spilled. This prevents code from
6839     // moving instructions to before the EH block, where they will never be
6840     // executed.
6841     for (MachineBasicBlock::reverse_iterator
6842            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6843       if (!II->isCall()) continue;
6844
6845       DenseMap<unsigned, bool> DefRegs;
6846       for (MachineInstr::mop_iterator
6847              OI = II->operands_begin(), OE = II->operands_end();
6848            OI != OE; ++OI) {
6849         if (!OI->isReg()) continue;
6850         DefRegs[OI->getReg()] = true;
6851       }
6852
6853       MachineInstrBuilder MIB(*MF, &*II);
6854
6855       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6856         unsigned Reg = SavedRegs[i];
6857         if (Subtarget->isThumb2() &&
6858             !ARM::tGPRRegClass.contains(Reg) &&
6859             !ARM::hGPRRegClass.contains(Reg))
6860           continue;
6861         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6862           continue;
6863         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6864           continue;
6865         if (!DefRegs[Reg])
6866           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6867       }
6868
6869       break;
6870     }
6871   }
6872
6873   // Mark all former landing pads as non-landing pads. The dispatch is the only
6874   // landing pad now.
6875   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6876          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6877     (*I)->setIsLandingPad(false);
6878
6879   // The instruction is gone now.
6880   MI->eraseFromParent();
6881 }
6882
6883 static
6884 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6885   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6886        E = MBB->succ_end(); I != E; ++I)
6887     if (*I != Succ)
6888       return *I;
6889   llvm_unreachable("Expecting a BB with two successors!");
6890 }
6891
6892 /// Return the load opcode for a given load size. If load size >= 8,
6893 /// neon opcode will be returned.
6894 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6895   if (LdSize >= 8)
6896     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6897                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6898   if (IsThumb1)
6899     return LdSize == 4 ? ARM::tLDRi
6900                        : LdSize == 2 ? ARM::tLDRHi
6901                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6902   if (IsThumb2)
6903     return LdSize == 4 ? ARM::t2LDR_POST
6904                        : LdSize == 2 ? ARM::t2LDRH_POST
6905                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6906   return LdSize == 4 ? ARM::LDR_POST_IMM
6907                      : LdSize == 2 ? ARM::LDRH_POST
6908                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6909 }
6910
6911 /// Return the store opcode for a given store size. If store size >= 8,
6912 /// neon opcode will be returned.
6913 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6914   if (StSize >= 8)
6915     return StSize == 16 ? ARM::VST1q32wb_fixed
6916                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6917   if (IsThumb1)
6918     return StSize == 4 ? ARM::tSTRi
6919                        : StSize == 2 ? ARM::tSTRHi
6920                                      : StSize == 1 ? ARM::tSTRBi : 0;
6921   if (IsThumb2)
6922     return StSize == 4 ? ARM::t2STR_POST
6923                        : StSize == 2 ? ARM::t2STRH_POST
6924                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6925   return StSize == 4 ? ARM::STR_POST_IMM
6926                      : StSize == 2 ? ARM::STRH_POST
6927                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6928 }
6929
6930 /// Emit a post-increment load operation with given size. The instructions
6931 /// will be added to BB at Pos.
6932 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6933                        const TargetInstrInfo *TII, DebugLoc dl,
6934                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6935                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6936   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6937   assert(LdOpc != 0 && "Should have a load opcode");
6938   if (LdSize >= 8) {
6939     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6940                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6941                        .addImm(0));
6942   } else if (IsThumb1) {
6943     // load + update AddrIn
6944     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6945                        .addReg(AddrIn).addImm(0));
6946     MachineInstrBuilder MIB =
6947         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6948     MIB = AddDefaultT1CC(MIB);
6949     MIB.addReg(AddrIn).addImm(LdSize);
6950     AddDefaultPred(MIB);
6951   } else if (IsThumb2) {
6952     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6953                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6954                        .addImm(LdSize));
6955   } else { // arm
6956     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6957                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6958                        .addReg(0).addImm(LdSize));
6959   }
6960 }
6961
6962 /// Emit a post-increment store operation with given size. The instructions
6963 /// will be added to BB at Pos.
6964 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6965                        const TargetInstrInfo *TII, DebugLoc dl,
6966                        unsigned StSize, unsigned Data, unsigned AddrIn,
6967                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6968   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6969   assert(StOpc != 0 && "Should have a store opcode");
6970   if (StSize >= 8) {
6971     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6972                        .addReg(AddrIn).addImm(0).addReg(Data));
6973   } else if (IsThumb1) {
6974     // store + update AddrIn
6975     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6976                        .addReg(AddrIn).addImm(0));
6977     MachineInstrBuilder MIB =
6978         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6979     MIB = AddDefaultT1CC(MIB);
6980     MIB.addReg(AddrIn).addImm(StSize);
6981     AddDefaultPred(MIB);
6982   } else if (IsThumb2) {
6983     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6984                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6985   } else { // arm
6986     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6987                        .addReg(Data).addReg(AddrIn).addReg(0)
6988                        .addImm(StSize));
6989   }
6990 }
6991
6992 MachineBasicBlock *
6993 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6994                                    MachineBasicBlock *BB) const {
6995   // This pseudo instruction has 3 operands: dst, src, size
6996   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6997   // Otherwise, we will generate unrolled scalar copies.
6998   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6999   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7000   MachineFunction::iterator It = BB;
7001   ++It;
7002
7003   unsigned dest = MI->getOperand(0).getReg();
7004   unsigned src = MI->getOperand(1).getReg();
7005   unsigned SizeVal = MI->getOperand(2).getImm();
7006   unsigned Align = MI->getOperand(3).getImm();
7007   DebugLoc dl = MI->getDebugLoc();
7008
7009   MachineFunction *MF = BB->getParent();
7010   MachineRegisterInfo &MRI = MF->getRegInfo();
7011   unsigned UnitSize = 0;
7012   const TargetRegisterClass *TRC = nullptr;
7013   const TargetRegisterClass *VecTRC = nullptr;
7014
7015   bool IsThumb1 = Subtarget->isThumb1Only();
7016   bool IsThumb2 = Subtarget->isThumb2();
7017
7018   if (Align & 1) {
7019     UnitSize = 1;
7020   } else if (Align & 2) {
7021     UnitSize = 2;
7022   } else {
7023     // Check whether we can use NEON instructions.
7024     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7025         Subtarget->hasNEON()) {
7026       if ((Align % 16 == 0) && SizeVal >= 16)
7027         UnitSize = 16;
7028       else if ((Align % 8 == 0) && SizeVal >= 8)
7029         UnitSize = 8;
7030     }
7031     // Can't use NEON instructions.
7032     if (UnitSize == 0)
7033       UnitSize = 4;
7034   }
7035
7036   // Select the correct opcode and register class for unit size load/store
7037   bool IsNeon = UnitSize >= 8;
7038   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7039   if (IsNeon)
7040     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7041                             : UnitSize == 8 ? &ARM::DPRRegClass
7042                                             : nullptr;
7043
7044   unsigned BytesLeft = SizeVal % UnitSize;
7045   unsigned LoopSize = SizeVal - BytesLeft;
7046
7047   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7048     // Use LDR and STR to copy.
7049     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7050     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7051     unsigned srcIn = src;
7052     unsigned destIn = dest;
7053     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7054       unsigned srcOut = MRI.createVirtualRegister(TRC);
7055       unsigned destOut = MRI.createVirtualRegister(TRC);
7056       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7057       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7058                  IsThumb1, IsThumb2);
7059       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7060                  IsThumb1, IsThumb2);
7061       srcIn = srcOut;
7062       destIn = destOut;
7063     }
7064
7065     // Handle the leftover bytes with LDRB and STRB.
7066     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7067     // [destOut] = STRB_POST(scratch, destIn, 1)
7068     for (unsigned i = 0; i < BytesLeft; i++) {
7069       unsigned srcOut = MRI.createVirtualRegister(TRC);
7070       unsigned destOut = MRI.createVirtualRegister(TRC);
7071       unsigned scratch = MRI.createVirtualRegister(TRC);
7072       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7073                  IsThumb1, IsThumb2);
7074       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7075                  IsThumb1, IsThumb2);
7076       srcIn = srcOut;
7077       destIn = destOut;
7078     }
7079     MI->eraseFromParent();   // The instruction is gone now.
7080     return BB;
7081   }
7082
7083   // Expand the pseudo op to a loop.
7084   // thisMBB:
7085   //   ...
7086   //   movw varEnd, # --> with thumb2
7087   //   movt varEnd, #
7088   //   ldrcp varEnd, idx --> without thumb2
7089   //   fallthrough --> loopMBB
7090   // loopMBB:
7091   //   PHI varPhi, varEnd, varLoop
7092   //   PHI srcPhi, src, srcLoop
7093   //   PHI destPhi, dst, destLoop
7094   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7095   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7096   //   subs varLoop, varPhi, #UnitSize
7097   //   bne loopMBB
7098   //   fallthrough --> exitMBB
7099   // exitMBB:
7100   //   epilogue to handle left-over bytes
7101   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7102   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7103   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7104   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7105   MF->insert(It, loopMBB);
7106   MF->insert(It, exitMBB);
7107
7108   // Transfer the remainder of BB and its successor edges to exitMBB.
7109   exitMBB->splice(exitMBB->begin(), BB,
7110                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7111   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7112
7113   // Load an immediate to varEnd.
7114   unsigned varEnd = MRI.createVirtualRegister(TRC);
7115   if (Subtarget->useMovt(*MF)) {
7116     unsigned Vtmp = varEnd;
7117     if ((LoopSize & 0xFFFF0000) != 0)
7118       Vtmp = MRI.createVirtualRegister(TRC);
7119     AddDefaultPred(BuildMI(BB, dl,
7120                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7121                            Vtmp).addImm(LoopSize & 0xFFFF));
7122
7123     if ((LoopSize & 0xFFFF0000) != 0)
7124       AddDefaultPred(BuildMI(BB, dl,
7125                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7126                              varEnd)
7127                          .addReg(Vtmp)
7128                          .addImm(LoopSize >> 16));
7129   } else {
7130     MachineConstantPool *ConstantPool = MF->getConstantPool();
7131     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7132     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7133
7134     // MachineConstantPool wants an explicit alignment.
7135     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7136     if (Align == 0)
7137       Align = getDataLayout()->getTypeAllocSize(C->getType());
7138     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7139
7140     if (IsThumb1)
7141       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7142           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7143     else
7144       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7145           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7146   }
7147   BB->addSuccessor(loopMBB);
7148
7149   // Generate the loop body:
7150   //   varPhi = PHI(varLoop, varEnd)
7151   //   srcPhi = PHI(srcLoop, src)
7152   //   destPhi = PHI(destLoop, dst)
7153   MachineBasicBlock *entryBB = BB;
7154   BB = loopMBB;
7155   unsigned varLoop = MRI.createVirtualRegister(TRC);
7156   unsigned varPhi = MRI.createVirtualRegister(TRC);
7157   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7158   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7159   unsigned destLoop = MRI.createVirtualRegister(TRC);
7160   unsigned destPhi = MRI.createVirtualRegister(TRC);
7161
7162   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7163     .addReg(varLoop).addMBB(loopMBB)
7164     .addReg(varEnd).addMBB(entryBB);
7165   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7166     .addReg(srcLoop).addMBB(loopMBB)
7167     .addReg(src).addMBB(entryBB);
7168   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7169     .addReg(destLoop).addMBB(loopMBB)
7170     .addReg(dest).addMBB(entryBB);
7171
7172   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7173   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7174   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7175   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7176              IsThumb1, IsThumb2);
7177   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7178              IsThumb1, IsThumb2);
7179
7180   // Decrement loop variable by UnitSize.
7181   if (IsThumb1) {
7182     MachineInstrBuilder MIB =
7183         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7184     MIB = AddDefaultT1CC(MIB);
7185     MIB.addReg(varPhi).addImm(UnitSize);
7186     AddDefaultPred(MIB);
7187   } else {
7188     MachineInstrBuilder MIB =
7189         BuildMI(*BB, BB->end(), dl,
7190                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7191     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7192     MIB->getOperand(5).setReg(ARM::CPSR);
7193     MIB->getOperand(5).setIsDef(true);
7194   }
7195   BuildMI(*BB, BB->end(), dl,
7196           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7197       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7198
7199   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7200   BB->addSuccessor(loopMBB);
7201   BB->addSuccessor(exitMBB);
7202
7203   // Add epilogue to handle BytesLeft.
7204   BB = exitMBB;
7205   MachineInstr *StartOfExit = exitMBB->begin();
7206
7207   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7208   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7209   unsigned srcIn = srcLoop;
7210   unsigned destIn = destLoop;
7211   for (unsigned i = 0; i < BytesLeft; i++) {
7212     unsigned srcOut = MRI.createVirtualRegister(TRC);
7213     unsigned destOut = MRI.createVirtualRegister(TRC);
7214     unsigned scratch = MRI.createVirtualRegister(TRC);
7215     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7216                IsThumb1, IsThumb2);
7217     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7218                IsThumb1, IsThumb2);
7219     srcIn = srcOut;
7220     destIn = destOut;
7221   }
7222
7223   MI->eraseFromParent();   // The instruction is gone now.
7224   return BB;
7225 }
7226
7227 MachineBasicBlock *
7228 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7229                                        MachineBasicBlock *MBB) const {
7230   const TargetMachine &TM = getTargetMachine();
7231   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7232   DebugLoc DL = MI->getDebugLoc();
7233
7234   assert(Subtarget->isTargetWindows() &&
7235          "__chkstk is only supported on Windows");
7236   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7237
7238   // __chkstk takes the number of words to allocate on the stack in R4, and
7239   // returns the stack adjustment in number of bytes in R4.  This will not
7240   // clober any other registers (other than the obvious lr).
7241   //
7242   // Although, technically, IP should be considered a register which may be
7243   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7244   // thumb-2 environment, so there is no interworking required.  As a result, we
7245   // do not expect a veneer to be emitted by the linker, clobbering IP.
7246   //
7247   // Each module receives its own copy of __chkstk, so no import thunk is
7248   // required, again, ensuring that IP is not clobbered.
7249   //
7250   // Finally, although some linkers may theoretically provide a trampoline for
7251   // out of range calls (which is quite common due to a 32M range limitation of
7252   // branches for Thumb), we can generate the long-call version via
7253   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7254   // IP.
7255
7256   switch (TM.getCodeModel()) {
7257   case CodeModel::Small:
7258   case CodeModel::Medium:
7259   case CodeModel::Default:
7260   case CodeModel::Kernel:
7261     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7262       .addImm((unsigned)ARMCC::AL).addReg(0)
7263       .addExternalSymbol("__chkstk")
7264       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7265       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7266       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7267     break;
7268   case CodeModel::Large:
7269   case CodeModel::JITDefault: {
7270     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7271     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7272
7273     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7274       .addExternalSymbol("__chkstk");
7275     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7276       .addImm((unsigned)ARMCC::AL).addReg(0)
7277       .addReg(Reg, RegState::Kill)
7278       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7279       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7280       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7281     break;
7282   }
7283   }
7284
7285   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7286                                       ARM::SP)
7287                               .addReg(ARM::SP).addReg(ARM::R4)));
7288
7289   MI->eraseFromParent();
7290   return MBB;
7291 }
7292
7293 MachineBasicBlock *
7294 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7295                                                MachineBasicBlock *BB) const {
7296   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7297   DebugLoc dl = MI->getDebugLoc();
7298   bool isThumb2 = Subtarget->isThumb2();
7299   switch (MI->getOpcode()) {
7300   default: {
7301     MI->dump();
7302     llvm_unreachable("Unexpected instr type to insert");
7303   }
7304   // The Thumb2 pre-indexed stores have the same MI operands, they just
7305   // define them differently in the .td files from the isel patterns, so
7306   // they need pseudos.
7307   case ARM::t2STR_preidx:
7308     MI->setDesc(TII->get(ARM::t2STR_PRE));
7309     return BB;
7310   case ARM::t2STRB_preidx:
7311     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7312     return BB;
7313   case ARM::t2STRH_preidx:
7314     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7315     return BB;
7316
7317   case ARM::STRi_preidx:
7318   case ARM::STRBi_preidx: {
7319     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7320       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7321     // Decode the offset.
7322     unsigned Offset = MI->getOperand(4).getImm();
7323     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7324     Offset = ARM_AM::getAM2Offset(Offset);
7325     if (isSub)
7326       Offset = -Offset;
7327
7328     MachineMemOperand *MMO = *MI->memoperands_begin();
7329     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7330       .addOperand(MI->getOperand(0))  // Rn_wb
7331       .addOperand(MI->getOperand(1))  // Rt
7332       .addOperand(MI->getOperand(2))  // Rn
7333       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7334       .addOperand(MI->getOperand(5))  // pred
7335       .addOperand(MI->getOperand(6))
7336       .addMemOperand(MMO);
7337     MI->eraseFromParent();
7338     return BB;
7339   }
7340   case ARM::STRr_preidx:
7341   case ARM::STRBr_preidx:
7342   case ARM::STRH_preidx: {
7343     unsigned NewOpc;
7344     switch (MI->getOpcode()) {
7345     default: llvm_unreachable("unexpected opcode!");
7346     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7347     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7348     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7349     }
7350     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7351     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7352       MIB.addOperand(MI->getOperand(i));
7353     MI->eraseFromParent();
7354     return BB;
7355   }
7356
7357   case ARM::tMOVCCr_pseudo: {
7358     // To "insert" a SELECT_CC instruction, we actually have to insert the
7359     // diamond control-flow pattern.  The incoming instruction knows the
7360     // destination vreg to set, the condition code register to branch on, the
7361     // true/false values to select between, and a branch opcode to use.
7362     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7363     MachineFunction::iterator It = BB;
7364     ++It;
7365
7366     //  thisMBB:
7367     //  ...
7368     //   TrueVal = ...
7369     //   cmpTY ccX, r1, r2
7370     //   bCC copy1MBB
7371     //   fallthrough --> copy0MBB
7372     MachineBasicBlock *thisMBB  = BB;
7373     MachineFunction *F = BB->getParent();
7374     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7375     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7376     F->insert(It, copy0MBB);
7377     F->insert(It, sinkMBB);
7378
7379     // Transfer the remainder of BB and its successor edges to sinkMBB.
7380     sinkMBB->splice(sinkMBB->begin(), BB,
7381                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7382     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7383
7384     BB->addSuccessor(copy0MBB);
7385     BB->addSuccessor(sinkMBB);
7386
7387     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7388       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7389
7390     //  copy0MBB:
7391     //   %FalseValue = ...
7392     //   # fallthrough to sinkMBB
7393     BB = copy0MBB;
7394
7395     // Update machine-CFG edges
7396     BB->addSuccessor(sinkMBB);
7397
7398     //  sinkMBB:
7399     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7400     //  ...
7401     BB = sinkMBB;
7402     BuildMI(*BB, BB->begin(), dl,
7403             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7404       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7405       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7406
7407     MI->eraseFromParent();   // The pseudo instruction is gone now.
7408     return BB;
7409   }
7410
7411   case ARM::BCCi64:
7412   case ARM::BCCZi64: {
7413     // If there is an unconditional branch to the other successor, remove it.
7414     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7415
7416     // Compare both parts that make up the double comparison separately for
7417     // equality.
7418     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7419
7420     unsigned LHS1 = MI->getOperand(1).getReg();
7421     unsigned LHS2 = MI->getOperand(2).getReg();
7422     if (RHSisZero) {
7423       AddDefaultPred(BuildMI(BB, dl,
7424                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7425                      .addReg(LHS1).addImm(0));
7426       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7427         .addReg(LHS2).addImm(0)
7428         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7429     } else {
7430       unsigned RHS1 = MI->getOperand(3).getReg();
7431       unsigned RHS2 = MI->getOperand(4).getReg();
7432       AddDefaultPred(BuildMI(BB, dl,
7433                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7434                      .addReg(LHS1).addReg(RHS1));
7435       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7436         .addReg(LHS2).addReg(RHS2)
7437         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7438     }
7439
7440     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7441     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7442     if (MI->getOperand(0).getImm() == ARMCC::NE)
7443       std::swap(destMBB, exitMBB);
7444
7445     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7446       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7447     if (isThumb2)
7448       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7449     else
7450       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7451
7452     MI->eraseFromParent();   // The pseudo instruction is gone now.
7453     return BB;
7454   }
7455
7456   case ARM::Int_eh_sjlj_setjmp:
7457   case ARM::Int_eh_sjlj_setjmp_nofp:
7458   case ARM::tInt_eh_sjlj_setjmp:
7459   case ARM::t2Int_eh_sjlj_setjmp:
7460   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7461     EmitSjLjDispatchBlock(MI, BB);
7462     return BB;
7463
7464   case ARM::ABS:
7465   case ARM::t2ABS: {
7466     // To insert an ABS instruction, we have to insert the
7467     // diamond control-flow pattern.  The incoming instruction knows the
7468     // source vreg to test against 0, the destination vreg to set,
7469     // the condition code register to branch on, the
7470     // true/false values to select between, and a branch opcode to use.
7471     // It transforms
7472     //     V1 = ABS V0
7473     // into
7474     //     V2 = MOVS V0
7475     //     BCC                      (branch to SinkBB if V0 >= 0)
7476     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7477     //     SinkBB: V1 = PHI(V2, V3)
7478     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7479     MachineFunction::iterator BBI = BB;
7480     ++BBI;
7481     MachineFunction *Fn = BB->getParent();
7482     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7483     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7484     Fn->insert(BBI, RSBBB);
7485     Fn->insert(BBI, SinkBB);
7486
7487     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7488     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7489     bool isThumb2 = Subtarget->isThumb2();
7490     MachineRegisterInfo &MRI = Fn->getRegInfo();
7491     // In Thumb mode S must not be specified if source register is the SP or
7492     // PC and if destination register is the SP, so restrict register class
7493     unsigned NewRsbDstReg =
7494       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7495
7496     // Transfer the remainder of BB and its successor edges to sinkMBB.
7497     SinkBB->splice(SinkBB->begin(), BB,
7498                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7499     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7500
7501     BB->addSuccessor(RSBBB);
7502     BB->addSuccessor(SinkBB);
7503
7504     // fall through to SinkMBB
7505     RSBBB->addSuccessor(SinkBB);
7506
7507     // insert a cmp at the end of BB
7508     AddDefaultPred(BuildMI(BB, dl,
7509                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7510                    .addReg(ABSSrcReg).addImm(0));
7511
7512     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7513     BuildMI(BB, dl,
7514       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7515       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7516
7517     // insert rsbri in RSBBB
7518     // Note: BCC and rsbri will be converted into predicated rsbmi
7519     // by if-conversion pass
7520     BuildMI(*RSBBB, RSBBB->begin(), dl,
7521       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7522       .addReg(ABSSrcReg, RegState::Kill)
7523       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7524
7525     // insert PHI in SinkBB,
7526     // reuse ABSDstReg to not change uses of ABS instruction
7527     BuildMI(*SinkBB, SinkBB->begin(), dl,
7528       TII->get(ARM::PHI), ABSDstReg)
7529       .addReg(NewRsbDstReg).addMBB(RSBBB)
7530       .addReg(ABSSrcReg).addMBB(BB);
7531
7532     // remove ABS instruction
7533     MI->eraseFromParent();
7534
7535     // return last added BB
7536     return SinkBB;
7537   }
7538   case ARM::COPY_STRUCT_BYVAL_I32:
7539     ++NumLoopByVals;
7540     return EmitStructByval(MI, BB);
7541   case ARM::WIN__CHKSTK:
7542     return EmitLowered__chkstk(MI, BB);
7543   }
7544 }
7545
7546 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7547                                                       SDNode *Node) const {
7548   const MCInstrDesc *MCID = &MI->getDesc();
7549   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7550   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7551   // operand is still set to noreg. If needed, set the optional operand's
7552   // register to CPSR, and remove the redundant implicit def.
7553   //
7554   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7555
7556   // Rename pseudo opcodes.
7557   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7558   if (NewOpc) {
7559     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7560     MCID = &TII->get(NewOpc);
7561
7562     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7563            "converted opcode should be the same except for cc_out");
7564
7565     MI->setDesc(*MCID);
7566
7567     // Add the optional cc_out operand
7568     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7569   }
7570   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7571
7572   // Any ARM instruction that sets the 's' bit should specify an optional
7573   // "cc_out" operand in the last operand position.
7574   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7575     assert(!NewOpc && "Optional cc_out operand required");
7576     return;
7577   }
7578   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7579   // since we already have an optional CPSR def.
7580   bool definesCPSR = false;
7581   bool deadCPSR = false;
7582   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7583        i != e; ++i) {
7584     const MachineOperand &MO = MI->getOperand(i);
7585     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7586       definesCPSR = true;
7587       if (MO.isDead())
7588         deadCPSR = true;
7589       MI->RemoveOperand(i);
7590       break;
7591     }
7592   }
7593   if (!definesCPSR) {
7594     assert(!NewOpc && "Optional cc_out operand required");
7595     return;
7596   }
7597   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7598   if (deadCPSR) {
7599     assert(!MI->getOperand(ccOutIdx).getReg() &&
7600            "expect uninitialized optional cc_out operand");
7601     return;
7602   }
7603
7604   // If this instruction was defined with an optional CPSR def and its dag node
7605   // had a live implicit CPSR def, then activate the optional CPSR def.
7606   MachineOperand &MO = MI->getOperand(ccOutIdx);
7607   MO.setReg(ARM::CPSR);
7608   MO.setIsDef(true);
7609 }
7610
7611 //===----------------------------------------------------------------------===//
7612 //                           ARM Optimization Hooks
7613 //===----------------------------------------------------------------------===//
7614
7615 // Helper function that checks if N is a null or all ones constant.
7616 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7617   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7618   if (!C)
7619     return false;
7620   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7621 }
7622
7623 // Return true if N is conditionally 0 or all ones.
7624 // Detects these expressions where cc is an i1 value:
7625 //
7626 //   (select cc 0, y)   [AllOnes=0]
7627 //   (select cc y, 0)   [AllOnes=0]
7628 //   (zext cc)          [AllOnes=0]
7629 //   (sext cc)          [AllOnes=0/1]
7630 //   (select cc -1, y)  [AllOnes=1]
7631 //   (select cc y, -1)  [AllOnes=1]
7632 //
7633 // Invert is set when N is the null/all ones constant when CC is false.
7634 // OtherOp is set to the alternative value of N.
7635 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7636                                        SDValue &CC, bool &Invert,
7637                                        SDValue &OtherOp,
7638                                        SelectionDAG &DAG) {
7639   switch (N->getOpcode()) {
7640   default: return false;
7641   case ISD::SELECT: {
7642     CC = N->getOperand(0);
7643     SDValue N1 = N->getOperand(1);
7644     SDValue N2 = N->getOperand(2);
7645     if (isZeroOrAllOnes(N1, AllOnes)) {
7646       Invert = false;
7647       OtherOp = N2;
7648       return true;
7649     }
7650     if (isZeroOrAllOnes(N2, AllOnes)) {
7651       Invert = true;
7652       OtherOp = N1;
7653       return true;
7654     }
7655     return false;
7656   }
7657   case ISD::ZERO_EXTEND:
7658     // (zext cc) can never be the all ones value.
7659     if (AllOnes)
7660       return false;
7661     // Fall through.
7662   case ISD::SIGN_EXTEND: {
7663     EVT VT = N->getValueType(0);
7664     CC = N->getOperand(0);
7665     if (CC.getValueType() != MVT::i1)
7666       return false;
7667     Invert = !AllOnes;
7668     if (AllOnes)
7669       // When looking for an AllOnes constant, N is an sext, and the 'other'
7670       // value is 0.
7671       OtherOp = DAG.getConstant(0, VT);
7672     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7673       // When looking for a 0 constant, N can be zext or sext.
7674       OtherOp = DAG.getConstant(1, VT);
7675     else
7676       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7677     return true;
7678   }
7679   }
7680 }
7681
7682 // Combine a constant select operand into its use:
7683 //
7684 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7685 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7686 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7687 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7688 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7689 //
7690 // The transform is rejected if the select doesn't have a constant operand that
7691 // is null, or all ones when AllOnes is set.
7692 //
7693 // Also recognize sext/zext from i1:
7694 //
7695 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7696 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7697 //
7698 // These transformations eventually create predicated instructions.
7699 //
7700 // @param N       The node to transform.
7701 // @param Slct    The N operand that is a select.
7702 // @param OtherOp The other N operand (x above).
7703 // @param DCI     Context.
7704 // @param AllOnes Require the select constant to be all ones instead of null.
7705 // @returns The new node, or SDValue() on failure.
7706 static
7707 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7708                             TargetLowering::DAGCombinerInfo &DCI,
7709                             bool AllOnes = false) {
7710   SelectionDAG &DAG = DCI.DAG;
7711   EVT VT = N->getValueType(0);
7712   SDValue NonConstantVal;
7713   SDValue CCOp;
7714   bool SwapSelectOps;
7715   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7716                                   NonConstantVal, DAG))
7717     return SDValue();
7718
7719   // Slct is now know to be the desired identity constant when CC is true.
7720   SDValue TrueVal = OtherOp;
7721   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7722                                  OtherOp, NonConstantVal);
7723   // Unless SwapSelectOps says CC should be false.
7724   if (SwapSelectOps)
7725     std::swap(TrueVal, FalseVal);
7726
7727   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7728                      CCOp, TrueVal, FalseVal);
7729 }
7730
7731 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7732 static
7733 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7734                                        TargetLowering::DAGCombinerInfo &DCI) {
7735   SDValue N0 = N->getOperand(0);
7736   SDValue N1 = N->getOperand(1);
7737   if (N0.getNode()->hasOneUse()) {
7738     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7739     if (Result.getNode())
7740       return Result;
7741   }
7742   if (N1.getNode()->hasOneUse()) {
7743     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7744     if (Result.getNode())
7745       return Result;
7746   }
7747   return SDValue();
7748 }
7749
7750 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7751 // (only after legalization).
7752 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7753                                  TargetLowering::DAGCombinerInfo &DCI,
7754                                  const ARMSubtarget *Subtarget) {
7755
7756   // Only perform optimization if after legalize, and if NEON is available. We
7757   // also expected both operands to be BUILD_VECTORs.
7758   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7759       || N0.getOpcode() != ISD::BUILD_VECTOR
7760       || N1.getOpcode() != ISD::BUILD_VECTOR)
7761     return SDValue();
7762
7763   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7764   EVT VT = N->getValueType(0);
7765   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7766     return SDValue();
7767
7768   // Check that the vector operands are of the right form.
7769   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7770   // operands, where N is the size of the formed vector.
7771   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7772   // index such that we have a pair wise add pattern.
7773
7774   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7775   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7776     return SDValue();
7777   SDValue Vec = N0->getOperand(0)->getOperand(0);
7778   SDNode *V = Vec.getNode();
7779   unsigned nextIndex = 0;
7780
7781   // For each operands to the ADD which are BUILD_VECTORs,
7782   // check to see if each of their operands are an EXTRACT_VECTOR with
7783   // the same vector and appropriate index.
7784   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7785     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7786         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7787
7788       SDValue ExtVec0 = N0->getOperand(i);
7789       SDValue ExtVec1 = N1->getOperand(i);
7790
7791       // First operand is the vector, verify its the same.
7792       if (V != ExtVec0->getOperand(0).getNode() ||
7793           V != ExtVec1->getOperand(0).getNode())
7794         return SDValue();
7795
7796       // Second is the constant, verify its correct.
7797       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7798       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7799
7800       // For the constant, we want to see all the even or all the odd.
7801       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7802           || C1->getZExtValue() != nextIndex+1)
7803         return SDValue();
7804
7805       // Increment index.
7806       nextIndex+=2;
7807     } else
7808       return SDValue();
7809   }
7810
7811   // Create VPADDL node.
7812   SelectionDAG &DAG = DCI.DAG;
7813   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7814
7815   // Build operand list.
7816   SmallVector<SDValue, 8> Ops;
7817   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7818                                 TLI.getPointerTy()));
7819
7820   // Input is the vector.
7821   Ops.push_back(Vec);
7822
7823   // Get widened type and narrowed type.
7824   MVT widenType;
7825   unsigned numElem = VT.getVectorNumElements();
7826   
7827   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7828   switch (inputLaneType.getSimpleVT().SimpleTy) {
7829     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7830     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7831     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7832     default:
7833       llvm_unreachable("Invalid vector element type for padd optimization.");
7834   }
7835
7836   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7837   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7838   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7839 }
7840
7841 static SDValue findMUL_LOHI(SDValue V) {
7842   if (V->getOpcode() == ISD::UMUL_LOHI ||
7843       V->getOpcode() == ISD::SMUL_LOHI)
7844     return V;
7845   return SDValue();
7846 }
7847
7848 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7849                                      TargetLowering::DAGCombinerInfo &DCI,
7850                                      const ARMSubtarget *Subtarget) {
7851
7852   if (Subtarget->isThumb1Only()) return SDValue();
7853
7854   // Only perform the checks after legalize when the pattern is available.
7855   if (DCI.isBeforeLegalize()) return SDValue();
7856
7857   // Look for multiply add opportunities.
7858   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7859   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7860   // a glue link from the first add to the second add.
7861   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7862   // a S/UMLAL instruction.
7863   //          loAdd   UMUL_LOHI
7864   //            \    / :lo    \ :hi
7865   //             \  /          \          [no multiline comment]
7866   //              ADDC         |  hiAdd
7867   //                 \ :glue  /  /
7868   //                  \      /  /
7869   //                    ADDE
7870   //
7871   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7872   SDValue AddcOp0 = AddcNode->getOperand(0);
7873   SDValue AddcOp1 = AddcNode->getOperand(1);
7874
7875   // Check if the two operands are from the same mul_lohi node.
7876   if (AddcOp0.getNode() == AddcOp1.getNode())
7877     return SDValue();
7878
7879   assert(AddcNode->getNumValues() == 2 &&
7880          AddcNode->getValueType(0) == MVT::i32 &&
7881          "Expect ADDC with two result values. First: i32");
7882
7883   // Check that we have a glued ADDC node.
7884   if (AddcNode->getValueType(1) != MVT::Glue)
7885     return SDValue();
7886
7887   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7888   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7889       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7890       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7891       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7892     return SDValue();
7893
7894   // Look for the glued ADDE.
7895   SDNode* AddeNode = AddcNode->getGluedUser();
7896   if (!AddeNode)
7897     return SDValue();
7898
7899   // Make sure it is really an ADDE.
7900   if (AddeNode->getOpcode() != ISD::ADDE)
7901     return SDValue();
7902
7903   assert(AddeNode->getNumOperands() == 3 &&
7904          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7905          "ADDE node has the wrong inputs");
7906
7907   // Check for the triangle shape.
7908   SDValue AddeOp0 = AddeNode->getOperand(0);
7909   SDValue AddeOp1 = AddeNode->getOperand(1);
7910
7911   // Make sure that the ADDE operands are not coming from the same node.
7912   if (AddeOp0.getNode() == AddeOp1.getNode())
7913     return SDValue();
7914
7915   // Find the MUL_LOHI node walking up ADDE's operands.
7916   bool IsLeftOperandMUL = false;
7917   SDValue MULOp = findMUL_LOHI(AddeOp0);
7918   if (MULOp == SDValue())
7919    MULOp = findMUL_LOHI(AddeOp1);
7920   else
7921     IsLeftOperandMUL = true;
7922   if (MULOp == SDValue())
7923     return SDValue();
7924
7925   // Figure out the right opcode.
7926   unsigned Opc = MULOp->getOpcode();
7927   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7928
7929   // Figure out the high and low input values to the MLAL node.
7930   SDValue* HiAdd = nullptr;
7931   SDValue* LoMul = nullptr;
7932   SDValue* LowAdd = nullptr;
7933
7934   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
7935   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
7936     return SDValue();
7937
7938   if (IsLeftOperandMUL)
7939     HiAdd = &AddeOp1;
7940   else
7941     HiAdd = &AddeOp0;
7942
7943
7944   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
7945   // whose low result is fed to the ADDC we are checking.
7946
7947   if (AddcOp0 == MULOp.getValue(0)) {
7948     LoMul = &AddcOp0;
7949     LowAdd = &AddcOp1;
7950   }
7951   if (AddcOp1 == MULOp.getValue(0)) {
7952     LoMul = &AddcOp1;
7953     LowAdd = &AddcOp0;
7954   }
7955
7956   if (!LoMul)
7957     return SDValue();
7958
7959   // Create the merged node.
7960   SelectionDAG &DAG = DCI.DAG;
7961
7962   // Build operand list.
7963   SmallVector<SDValue, 8> Ops;
7964   Ops.push_back(LoMul->getOperand(0));
7965   Ops.push_back(LoMul->getOperand(1));
7966   Ops.push_back(*LowAdd);
7967   Ops.push_back(*HiAdd);
7968
7969   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7970                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7971
7972   // Replace the ADDs' nodes uses by the MLA node's values.
7973   SDValue HiMLALResult(MLALNode.getNode(), 1);
7974   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7975
7976   SDValue LoMLALResult(MLALNode.getNode(), 0);
7977   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7978
7979   // Return original node to notify the driver to stop replacing.
7980   SDValue resNode(AddcNode, 0);
7981   return resNode;
7982 }
7983
7984 /// PerformADDCCombine - Target-specific dag combine transform from
7985 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7986 static SDValue PerformADDCCombine(SDNode *N,
7987                                  TargetLowering::DAGCombinerInfo &DCI,
7988                                  const ARMSubtarget *Subtarget) {
7989
7990   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7991
7992 }
7993
7994 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7995 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7996 /// called with the default operands, and if that fails, with commuted
7997 /// operands.
7998 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7999                                           TargetLowering::DAGCombinerInfo &DCI,
8000                                           const ARMSubtarget *Subtarget){
8001
8002   // Attempt to create vpaddl for this add.
8003   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8004   if (Result.getNode())
8005     return Result;
8006
8007   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8008   if (N0.getNode()->hasOneUse()) {
8009     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8010     if (Result.getNode()) return Result;
8011   }
8012   return SDValue();
8013 }
8014
8015 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8016 ///
8017 static SDValue PerformADDCombine(SDNode *N,
8018                                  TargetLowering::DAGCombinerInfo &DCI,
8019                                  const ARMSubtarget *Subtarget) {
8020   SDValue N0 = N->getOperand(0);
8021   SDValue N1 = N->getOperand(1);
8022
8023   // First try with the default operand order.
8024   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8025   if (Result.getNode())
8026     return Result;
8027
8028   // If that didn't work, try again with the operands commuted.
8029   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8030 }
8031
8032 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8033 ///
8034 static SDValue PerformSUBCombine(SDNode *N,
8035                                  TargetLowering::DAGCombinerInfo &DCI) {
8036   SDValue N0 = N->getOperand(0);
8037   SDValue N1 = N->getOperand(1);
8038
8039   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8040   if (N1.getNode()->hasOneUse()) {
8041     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8042     if (Result.getNode()) return Result;
8043   }
8044
8045   return SDValue();
8046 }
8047
8048 /// PerformVMULCombine
8049 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8050 /// special multiplier accumulator forwarding.
8051 ///   vmul d3, d0, d2
8052 ///   vmla d3, d1, d2
8053 /// is faster than
8054 ///   vadd d3, d0, d1
8055 ///   vmul d3, d3, d2
8056 //  However, for (A + B) * (A + B),
8057 //    vadd d2, d0, d1
8058 //    vmul d3, d0, d2
8059 //    vmla d3, d1, d2
8060 //  is slower than
8061 //    vadd d2, d0, d1
8062 //    vmul d3, d2, d2
8063 static SDValue PerformVMULCombine(SDNode *N,
8064                                   TargetLowering::DAGCombinerInfo &DCI,
8065                                   const ARMSubtarget *Subtarget) {
8066   if (!Subtarget->hasVMLxForwarding())
8067     return SDValue();
8068
8069   SelectionDAG &DAG = DCI.DAG;
8070   SDValue N0 = N->getOperand(0);
8071   SDValue N1 = N->getOperand(1);
8072   unsigned Opcode = N0.getOpcode();
8073   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8074       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8075     Opcode = N1.getOpcode();
8076     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8077         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8078       return SDValue();
8079     std::swap(N0, N1);
8080   }
8081
8082   if (N0 == N1)
8083     return SDValue();
8084
8085   EVT VT = N->getValueType(0);
8086   SDLoc DL(N);
8087   SDValue N00 = N0->getOperand(0);
8088   SDValue N01 = N0->getOperand(1);
8089   return DAG.getNode(Opcode, DL, VT,
8090                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8091                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8092 }
8093
8094 static SDValue PerformMULCombine(SDNode *N,
8095                                  TargetLowering::DAGCombinerInfo &DCI,
8096                                  const ARMSubtarget *Subtarget) {
8097   SelectionDAG &DAG = DCI.DAG;
8098
8099   if (Subtarget->isThumb1Only())
8100     return SDValue();
8101
8102   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8103     return SDValue();
8104
8105   EVT VT = N->getValueType(0);
8106   if (VT.is64BitVector() || VT.is128BitVector())
8107     return PerformVMULCombine(N, DCI, Subtarget);
8108   if (VT != MVT::i32)
8109     return SDValue();
8110
8111   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8112   if (!C)
8113     return SDValue();
8114
8115   int64_t MulAmt = C->getSExtValue();
8116   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8117
8118   ShiftAmt = ShiftAmt & (32 - 1);
8119   SDValue V = N->getOperand(0);
8120   SDLoc DL(N);
8121
8122   SDValue Res;
8123   MulAmt >>= ShiftAmt;
8124
8125   if (MulAmt >= 0) {
8126     if (isPowerOf2_32(MulAmt - 1)) {
8127       // (mul x, 2^N + 1) => (add (shl x, N), x)
8128       Res = DAG.getNode(ISD::ADD, DL, VT,
8129                         V,
8130                         DAG.getNode(ISD::SHL, DL, VT,
8131                                     V,
8132                                     DAG.getConstant(Log2_32(MulAmt - 1),
8133                                                     MVT::i32)));
8134     } else if (isPowerOf2_32(MulAmt + 1)) {
8135       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8136       Res = DAG.getNode(ISD::SUB, DL, VT,
8137                         DAG.getNode(ISD::SHL, DL, VT,
8138                                     V,
8139                                     DAG.getConstant(Log2_32(MulAmt + 1),
8140                                                     MVT::i32)),
8141                         V);
8142     } else
8143       return SDValue();
8144   } else {
8145     uint64_t MulAmtAbs = -MulAmt;
8146     if (isPowerOf2_32(MulAmtAbs + 1)) {
8147       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8148       Res = DAG.getNode(ISD::SUB, DL, VT,
8149                         V,
8150                         DAG.getNode(ISD::SHL, DL, VT,
8151                                     V,
8152                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8153                                                     MVT::i32)));
8154     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8155       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8156       Res = DAG.getNode(ISD::ADD, DL, VT,
8157                         V,
8158                         DAG.getNode(ISD::SHL, DL, VT,
8159                                     V,
8160                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8161                                                     MVT::i32)));
8162       Res = DAG.getNode(ISD::SUB, DL, VT,
8163                         DAG.getConstant(0, MVT::i32),Res);
8164
8165     } else
8166       return SDValue();
8167   }
8168
8169   if (ShiftAmt != 0)
8170     Res = DAG.getNode(ISD::SHL, DL, VT,
8171                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8172
8173   // Do not add new nodes to DAG combiner worklist.
8174   DCI.CombineTo(N, Res, false);
8175   return SDValue();
8176 }
8177
8178 static SDValue PerformANDCombine(SDNode *N,
8179                                  TargetLowering::DAGCombinerInfo &DCI,
8180                                  const ARMSubtarget *Subtarget) {
8181
8182   // Attempt to use immediate-form VBIC
8183   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8184   SDLoc dl(N);
8185   EVT VT = N->getValueType(0);
8186   SelectionDAG &DAG = DCI.DAG;
8187
8188   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8189     return SDValue();
8190
8191   APInt SplatBits, SplatUndef;
8192   unsigned SplatBitSize;
8193   bool HasAnyUndefs;
8194   if (BVN &&
8195       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8196     if (SplatBitSize <= 64) {
8197       EVT VbicVT;
8198       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8199                                       SplatUndef.getZExtValue(), SplatBitSize,
8200                                       DAG, VbicVT, VT.is128BitVector(),
8201                                       OtherModImm);
8202       if (Val.getNode()) {
8203         SDValue Input =
8204           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8205         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8206         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8207       }
8208     }
8209   }
8210
8211   if (!Subtarget->isThumb1Only()) {
8212     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8213     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8214     if (Result.getNode())
8215       return Result;
8216   }
8217
8218   return SDValue();
8219 }
8220
8221 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8222 static SDValue PerformORCombine(SDNode *N,
8223                                 TargetLowering::DAGCombinerInfo &DCI,
8224                                 const ARMSubtarget *Subtarget) {
8225   // Attempt to use immediate-form VORR
8226   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8227   SDLoc dl(N);
8228   EVT VT = N->getValueType(0);
8229   SelectionDAG &DAG = DCI.DAG;
8230
8231   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8232     return SDValue();
8233
8234   APInt SplatBits, SplatUndef;
8235   unsigned SplatBitSize;
8236   bool HasAnyUndefs;
8237   if (BVN && Subtarget->hasNEON() &&
8238       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8239     if (SplatBitSize <= 64) {
8240       EVT VorrVT;
8241       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8242                                       SplatUndef.getZExtValue(), SplatBitSize,
8243                                       DAG, VorrVT, VT.is128BitVector(),
8244                                       OtherModImm);
8245       if (Val.getNode()) {
8246         SDValue Input =
8247           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8248         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8249         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8250       }
8251     }
8252   }
8253
8254   if (!Subtarget->isThumb1Only()) {
8255     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8256     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8257     if (Result.getNode())
8258       return Result;
8259   }
8260
8261   // The code below optimizes (or (and X, Y), Z).
8262   // The AND operand needs to have a single user to make these optimizations
8263   // profitable.
8264   SDValue N0 = N->getOperand(0);
8265   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8266     return SDValue();
8267   SDValue N1 = N->getOperand(1);
8268
8269   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8270   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8271       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8272     APInt SplatUndef;
8273     unsigned SplatBitSize;
8274     bool HasAnyUndefs;
8275
8276     APInt SplatBits0, SplatBits1;
8277     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8278     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8279     // Ensure that the second operand of both ands are constants
8280     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8281                                       HasAnyUndefs) && !HasAnyUndefs) {
8282         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8283                                           HasAnyUndefs) && !HasAnyUndefs) {
8284             // Ensure that the bit width of the constants are the same and that
8285             // the splat arguments are logical inverses as per the pattern we
8286             // are trying to simplify.
8287             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8288                 SplatBits0 == ~SplatBits1) {
8289                 // Canonicalize the vector type to make instruction selection
8290                 // simpler.
8291                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8292                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8293                                              N0->getOperand(1),
8294                                              N0->getOperand(0),
8295                                              N1->getOperand(0));
8296                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8297             }
8298         }
8299     }
8300   }
8301
8302   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8303   // reasonable.
8304
8305   // BFI is only available on V6T2+
8306   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8307     return SDValue();
8308
8309   SDLoc DL(N);
8310   // 1) or (and A, mask), val => ARMbfi A, val, mask
8311   //      iff (val & mask) == val
8312   //
8313   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8314   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8315   //          && mask == ~mask2
8316   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8317   //          && ~mask == mask2
8318   //  (i.e., copy a bitfield value into another bitfield of the same width)
8319
8320   if (VT != MVT::i32)
8321     return SDValue();
8322
8323   SDValue N00 = N0.getOperand(0);
8324
8325   // The value and the mask need to be constants so we can verify this is
8326   // actually a bitfield set. If the mask is 0xffff, we can do better
8327   // via a movt instruction, so don't use BFI in that case.
8328   SDValue MaskOp = N0.getOperand(1);
8329   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8330   if (!MaskC)
8331     return SDValue();
8332   unsigned Mask = MaskC->getZExtValue();
8333   if (Mask == 0xffff)
8334     return SDValue();
8335   SDValue Res;
8336   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8337   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8338   if (N1C) {
8339     unsigned Val = N1C->getZExtValue();
8340     if ((Val & ~Mask) != Val)
8341       return SDValue();
8342
8343     if (ARM::isBitFieldInvertedMask(Mask)) {
8344       Val >>= countTrailingZeros(~Mask);
8345
8346       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8347                         DAG.getConstant(Val, MVT::i32),
8348                         DAG.getConstant(Mask, MVT::i32));
8349
8350       // Do not add new nodes to DAG combiner worklist.
8351       DCI.CombineTo(N, Res, false);
8352       return SDValue();
8353     }
8354   } else if (N1.getOpcode() == ISD::AND) {
8355     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8356     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8357     if (!N11C)
8358       return SDValue();
8359     unsigned Mask2 = N11C->getZExtValue();
8360
8361     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8362     // as is to match.
8363     if (ARM::isBitFieldInvertedMask(Mask) &&
8364         (Mask == ~Mask2)) {
8365       // The pack halfword instruction works better for masks that fit it,
8366       // so use that when it's available.
8367       if (Subtarget->hasT2ExtractPack() &&
8368           (Mask == 0xffff || Mask == 0xffff0000))
8369         return SDValue();
8370       // 2a
8371       unsigned amt = countTrailingZeros(Mask2);
8372       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8373                         DAG.getConstant(amt, MVT::i32));
8374       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8375                         DAG.getConstant(Mask, MVT::i32));
8376       // Do not add new nodes to DAG combiner worklist.
8377       DCI.CombineTo(N, Res, false);
8378       return SDValue();
8379     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8380                (~Mask == Mask2)) {
8381       // The pack halfword instruction works better for masks that fit it,
8382       // so use that when it's available.
8383       if (Subtarget->hasT2ExtractPack() &&
8384           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8385         return SDValue();
8386       // 2b
8387       unsigned lsb = countTrailingZeros(Mask);
8388       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8389                         DAG.getConstant(lsb, MVT::i32));
8390       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8391                         DAG.getConstant(Mask2, MVT::i32));
8392       // Do not add new nodes to DAG combiner worklist.
8393       DCI.CombineTo(N, Res, false);
8394       return SDValue();
8395     }
8396   }
8397
8398   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8399       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8400       ARM::isBitFieldInvertedMask(~Mask)) {
8401     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8402     // where lsb(mask) == #shamt and masked bits of B are known zero.
8403     SDValue ShAmt = N00.getOperand(1);
8404     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8405     unsigned LSB = countTrailingZeros(Mask);
8406     if (ShAmtC != LSB)
8407       return SDValue();
8408
8409     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8410                       DAG.getConstant(~Mask, MVT::i32));
8411
8412     // Do not add new nodes to DAG combiner worklist.
8413     DCI.CombineTo(N, Res, false);
8414   }
8415
8416   return SDValue();
8417 }
8418
8419 static SDValue PerformXORCombine(SDNode *N,
8420                                  TargetLowering::DAGCombinerInfo &DCI,
8421                                  const ARMSubtarget *Subtarget) {
8422   EVT VT = N->getValueType(0);
8423   SelectionDAG &DAG = DCI.DAG;
8424
8425   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8426     return SDValue();
8427
8428   if (!Subtarget->isThumb1Only()) {
8429     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8430     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8431     if (Result.getNode())
8432       return Result;
8433   }
8434
8435   return SDValue();
8436 }
8437
8438 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8439 /// the bits being cleared by the AND are not demanded by the BFI.
8440 static SDValue PerformBFICombine(SDNode *N,
8441                                  TargetLowering::DAGCombinerInfo &DCI) {
8442   SDValue N1 = N->getOperand(1);
8443   if (N1.getOpcode() == ISD::AND) {
8444     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8445     if (!N11C)
8446       return SDValue();
8447     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8448     unsigned LSB = countTrailingZeros(~InvMask);
8449     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8450     assert(Width <
8451                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8452            "undefined behavior");
8453     unsigned Mask = (1u << Width) - 1;
8454     unsigned Mask2 = N11C->getZExtValue();
8455     if ((Mask & (~Mask2)) == 0)
8456       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8457                              N->getOperand(0), N1.getOperand(0),
8458                              N->getOperand(2));
8459   }
8460   return SDValue();
8461 }
8462
8463 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8464 /// ARMISD::VMOVRRD.
8465 static SDValue PerformVMOVRRDCombine(SDNode *N,
8466                                      TargetLowering::DAGCombinerInfo &DCI,
8467                                      const ARMSubtarget *Subtarget) {
8468   // vmovrrd(vmovdrr x, y) -> x,y
8469   SDValue InDouble = N->getOperand(0);
8470   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8471     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8472
8473   // vmovrrd(load f64) -> (load i32), (load i32)
8474   SDNode *InNode = InDouble.getNode();
8475   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8476       InNode->getValueType(0) == MVT::f64 &&
8477       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8478       !cast<LoadSDNode>(InNode)->isVolatile()) {
8479     // TODO: Should this be done for non-FrameIndex operands?
8480     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8481
8482     SelectionDAG &DAG = DCI.DAG;
8483     SDLoc DL(LD);
8484     SDValue BasePtr = LD->getBasePtr();
8485     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8486                                  LD->getPointerInfo(), LD->isVolatile(),
8487                                  LD->isNonTemporal(), LD->isInvariant(),
8488                                  LD->getAlignment());
8489
8490     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8491                                     DAG.getConstant(4, MVT::i32));
8492     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8493                                  LD->getPointerInfo(), LD->isVolatile(),
8494                                  LD->isNonTemporal(), LD->isInvariant(),
8495                                  std::min(4U, LD->getAlignment() / 2));
8496
8497     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8498     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8499       std::swap (NewLD1, NewLD2);
8500     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8501     return Result;
8502   }
8503
8504   return SDValue();
8505 }
8506
8507 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8508 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8509 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8510   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8511   SDValue Op0 = N->getOperand(0);
8512   SDValue Op1 = N->getOperand(1);
8513   if (Op0.getOpcode() == ISD::BITCAST)
8514     Op0 = Op0.getOperand(0);
8515   if (Op1.getOpcode() == ISD::BITCAST)
8516     Op1 = Op1.getOperand(0);
8517   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8518       Op0.getNode() == Op1.getNode() &&
8519       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8520     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8521                        N->getValueType(0), Op0.getOperand(0));
8522   return SDValue();
8523 }
8524
8525 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8526 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8527 /// i64 vector to have f64 elements, since the value can then be loaded
8528 /// directly into a VFP register.
8529 static bool hasNormalLoadOperand(SDNode *N) {
8530   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8531   for (unsigned i = 0; i < NumElts; ++i) {
8532     SDNode *Elt = N->getOperand(i).getNode();
8533     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8534       return true;
8535   }
8536   return false;
8537 }
8538
8539 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8540 /// ISD::BUILD_VECTOR.
8541 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8542                                           TargetLowering::DAGCombinerInfo &DCI,
8543                                           const ARMSubtarget *Subtarget) {
8544   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8545   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8546   // into a pair of GPRs, which is fine when the value is used as a scalar,
8547   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8548   SelectionDAG &DAG = DCI.DAG;
8549   if (N->getNumOperands() == 2) {
8550     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8551     if (RV.getNode())
8552       return RV;
8553   }
8554
8555   // Load i64 elements as f64 values so that type legalization does not split
8556   // them up into i32 values.
8557   EVT VT = N->getValueType(0);
8558   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8559     return SDValue();
8560   SDLoc dl(N);
8561   SmallVector<SDValue, 8> Ops;
8562   unsigned NumElts = VT.getVectorNumElements();
8563   for (unsigned i = 0; i < NumElts; ++i) {
8564     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8565     Ops.push_back(V);
8566     // Make the DAGCombiner fold the bitcast.
8567     DCI.AddToWorklist(V.getNode());
8568   }
8569   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8570   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8571   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8572 }
8573
8574 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8575 static SDValue
8576 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8577   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8578   // At that time, we may have inserted bitcasts from integer to float.
8579   // If these bitcasts have survived DAGCombine, change the lowering of this
8580   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8581   // force to use floating point types.
8582
8583   // Make sure we can change the type of the vector.
8584   // This is possible iff:
8585   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8586   //    1.1. Vector is used only once.
8587   //    1.2. Use is a bit convert to an integer type.
8588   // 2. The size of its operands are 32-bits (64-bits are not legal).
8589   EVT VT = N->getValueType(0);
8590   EVT EltVT = VT.getVectorElementType();
8591
8592   // Check 1.1. and 2.
8593   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8594     return SDValue();
8595
8596   // By construction, the input type must be float.
8597   assert(EltVT == MVT::f32 && "Unexpected type!");
8598
8599   // Check 1.2.
8600   SDNode *Use = *N->use_begin();
8601   if (Use->getOpcode() != ISD::BITCAST ||
8602       Use->getValueType(0).isFloatingPoint())
8603     return SDValue();
8604
8605   // Check profitability.
8606   // Model is, if more than half of the relevant operands are bitcast from
8607   // i32, turn the build_vector into a sequence of insert_vector_elt.
8608   // Relevant operands are everything that is not statically
8609   // (i.e., at compile time) bitcasted.
8610   unsigned NumOfBitCastedElts = 0;
8611   unsigned NumElts = VT.getVectorNumElements();
8612   unsigned NumOfRelevantElts = NumElts;
8613   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8614     SDValue Elt = N->getOperand(Idx);
8615     if (Elt->getOpcode() == ISD::BITCAST) {
8616       // Assume only bit cast to i32 will go away.
8617       if (Elt->getOperand(0).getValueType() == MVT::i32)
8618         ++NumOfBitCastedElts;
8619     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8620       // Constants are statically casted, thus do not count them as
8621       // relevant operands.
8622       --NumOfRelevantElts;
8623   }
8624
8625   // Check if more than half of the elements require a non-free bitcast.
8626   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8627     return SDValue();
8628
8629   SelectionDAG &DAG = DCI.DAG;
8630   // Create the new vector type.
8631   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8632   // Check if the type is legal.
8633   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8634   if (!TLI.isTypeLegal(VecVT))
8635     return SDValue();
8636
8637   // Combine:
8638   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8639   // => BITCAST INSERT_VECTOR_ELT
8640   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8641   //                      (BITCAST EN), N.
8642   SDValue Vec = DAG.getUNDEF(VecVT);
8643   SDLoc dl(N);
8644   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8645     SDValue V = N->getOperand(Idx);
8646     if (V.getOpcode() == ISD::UNDEF)
8647       continue;
8648     if (V.getOpcode() == ISD::BITCAST &&
8649         V->getOperand(0).getValueType() == MVT::i32)
8650       // Fold obvious case.
8651       V = V.getOperand(0);
8652     else {
8653       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8654       // Make the DAGCombiner fold the bitcasts.
8655       DCI.AddToWorklist(V.getNode());
8656     }
8657     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8658     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8659   }
8660   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8661   // Make the DAGCombiner fold the bitcasts.
8662   DCI.AddToWorklist(Vec.getNode());
8663   return Vec;
8664 }
8665
8666 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8667 /// ISD::INSERT_VECTOR_ELT.
8668 static SDValue PerformInsertEltCombine(SDNode *N,
8669                                        TargetLowering::DAGCombinerInfo &DCI) {
8670   // Bitcast an i64 load inserted into a vector to f64.
8671   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8672   EVT VT = N->getValueType(0);
8673   SDNode *Elt = N->getOperand(1).getNode();
8674   if (VT.getVectorElementType() != MVT::i64 ||
8675       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8676     return SDValue();
8677
8678   SelectionDAG &DAG = DCI.DAG;
8679   SDLoc dl(N);
8680   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8681                                  VT.getVectorNumElements());
8682   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8683   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8684   // Make the DAGCombiner fold the bitcasts.
8685   DCI.AddToWorklist(Vec.getNode());
8686   DCI.AddToWorklist(V.getNode());
8687   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8688                                Vec, V, N->getOperand(2));
8689   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8690 }
8691
8692 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8693 /// ISD::VECTOR_SHUFFLE.
8694 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8695   // The LLVM shufflevector instruction does not require the shuffle mask
8696   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8697   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8698   // operands do not match the mask length, they are extended by concatenating
8699   // them with undef vectors.  That is probably the right thing for other
8700   // targets, but for NEON it is better to concatenate two double-register
8701   // size vector operands into a single quad-register size vector.  Do that
8702   // transformation here:
8703   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8704   //   shuffle(concat(v1, v2), undef)
8705   SDValue Op0 = N->getOperand(0);
8706   SDValue Op1 = N->getOperand(1);
8707   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8708       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8709       Op0.getNumOperands() != 2 ||
8710       Op1.getNumOperands() != 2)
8711     return SDValue();
8712   SDValue Concat0Op1 = Op0.getOperand(1);
8713   SDValue Concat1Op1 = Op1.getOperand(1);
8714   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8715       Concat1Op1.getOpcode() != ISD::UNDEF)
8716     return SDValue();
8717   // Skip the transformation if any of the types are illegal.
8718   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8719   EVT VT = N->getValueType(0);
8720   if (!TLI.isTypeLegal(VT) ||
8721       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8722       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8723     return SDValue();
8724
8725   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8726                                   Op0.getOperand(0), Op1.getOperand(0));
8727   // Translate the shuffle mask.
8728   SmallVector<int, 16> NewMask;
8729   unsigned NumElts = VT.getVectorNumElements();
8730   unsigned HalfElts = NumElts/2;
8731   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8732   for (unsigned n = 0; n < NumElts; ++n) {
8733     int MaskElt = SVN->getMaskElt(n);
8734     int NewElt = -1;
8735     if (MaskElt < (int)HalfElts)
8736       NewElt = MaskElt;
8737     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8738       NewElt = HalfElts + MaskElt - NumElts;
8739     NewMask.push_back(NewElt);
8740   }
8741   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8742                               DAG.getUNDEF(VT), NewMask.data());
8743 }
8744
8745 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8746 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8747 /// base address updates.
8748 /// For generic load/stores, the memory type is assumed to be a vector.
8749 /// The caller is assumed to have checked legality.
8750 static SDValue CombineBaseUpdate(SDNode *N,
8751                                  TargetLowering::DAGCombinerInfo &DCI) {
8752   SelectionDAG &DAG = DCI.DAG;
8753   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8754                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8755   const bool isStore = N->getOpcode() == ISD::STORE;
8756   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8757   SDValue Addr = N->getOperand(AddrOpIdx);
8758   MemSDNode *MemN = cast<MemSDNode>(N);
8759
8760   // Search for a use of the address operand that is an increment.
8761   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8762          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8763     SDNode *User = *UI;
8764     if (User->getOpcode() != ISD::ADD ||
8765         UI.getUse().getResNo() != Addr.getResNo())
8766       continue;
8767
8768     // Check that the add is independent of the load/store.  Otherwise, folding
8769     // it would create a cycle.
8770     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8771       continue;
8772
8773     // Find the new opcode for the updating load/store.
8774     bool isLoadOp = true;
8775     bool isLaneOp = false;
8776     unsigned NewOpc = 0;
8777     unsigned NumVecs = 0;
8778     if (isIntrinsic) {
8779       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8780       switch (IntNo) {
8781       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8782       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8783         NumVecs = 1; break;
8784       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8785         NumVecs = 2; break;
8786       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8787         NumVecs = 3; break;
8788       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8789         NumVecs = 4; break;
8790       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8791         NumVecs = 2; isLaneOp = true; break;
8792       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8793         NumVecs = 3; isLaneOp = true; break;
8794       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8795         NumVecs = 4; isLaneOp = true; break;
8796       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8797         NumVecs = 1; isLoadOp = false; break;
8798       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8799         NumVecs = 2; isLoadOp = false; break;
8800       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8801         NumVecs = 3; isLoadOp = false; break;
8802       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8803         NumVecs = 4; isLoadOp = false; break;
8804       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8805         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8806       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8807         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8808       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8809         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8810       }
8811     } else {
8812       isLaneOp = true;
8813       switch (N->getOpcode()) {
8814       default: llvm_unreachable("unexpected opcode for Neon base update");
8815       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8816       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8817       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8818       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
8819         NumVecs = 1; isLaneOp = false; break;
8820       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
8821         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8822       }
8823     }
8824
8825     // Find the size of memory referenced by the load/store.
8826     EVT VecTy;
8827     if (isLoadOp) {
8828       VecTy = N->getValueType(0);
8829     } else if (isIntrinsic) {
8830       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8831     } else {
8832       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8833       VecTy = N->getOperand(1).getValueType();
8834     }
8835
8836     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8837     if (isLaneOp)
8838       NumBytes /= VecTy.getVectorNumElements();
8839
8840     // If the increment is a constant, it must match the memory ref size.
8841     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8842     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8843       uint64_t IncVal = CInc->getZExtValue();
8844       if (IncVal != NumBytes)
8845         continue;
8846     } else if (NumBytes >= 3 * 16) {
8847       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8848       // separate instructions that make it harder to use a non-constant update.
8849       continue;
8850     }
8851
8852     // OK, we found an ADD we can fold into the base update.
8853     // Now, create a _UPD node, taking care of not breaking alignment.
8854
8855     EVT AlignedVecTy = VecTy;
8856     unsigned Alignment = MemN->getAlignment();
8857
8858     // If this is a less-than-standard-aligned load/store, change the type to
8859     // match the standard alignment.
8860     // The alignment is overlooked when selecting _UPD variants; and it's
8861     // easier to introduce bitcasts here than fix that.
8862     // There are 3 ways to get to this base-update combine:
8863     // - intrinsics: they are assumed to be properly aligned (to the standard
8864     //   alignment of the memory type), so we don't need to do anything.
8865     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
8866     //   intrinsics, so, likewise, there's nothing to do.
8867     // - generic load/store instructions: the alignment is specified as an
8868     //   explicit operand, rather than implicitly as the standard alignment
8869     //   of the memory type (like the intrisics).  We need to change the
8870     //   memory type to match the explicit alignment.  That way, we don't
8871     //   generate non-standard-aligned ARMISD::VLDx nodes.
8872     if (isa<LSBaseSDNode>(N)) {
8873       if (Alignment == 0)
8874         Alignment = 1;
8875       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
8876         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
8877         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
8878         assert(!isLaneOp && "Unexpected generic load/store lane.");
8879         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
8880         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
8881       }
8882       // Don't set an explicit alignment on regular load/stores that we want
8883       // to transform to VLD/VST 1_UPD nodes.
8884       // This matches the behavior of regular load/stores, which only get an
8885       // explicit alignment if the MMO alignment is larger than the standard
8886       // alignment of the memory type.
8887       // Intrinsics, however, always get an explicit alignment, set to the
8888       // alignment of the MMO.
8889       Alignment = 1;
8890     }
8891
8892     // Create the new updating load/store node.
8893     // First, create an SDVTList for the new updating node's results.
8894     EVT Tys[6];
8895     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
8896     unsigned n;
8897     for (n = 0; n < NumResultVecs; ++n)
8898       Tys[n] = AlignedVecTy;
8899     Tys[n++] = MVT::i32;
8900     Tys[n] = MVT::Other;
8901     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
8902
8903     // Then, gather the new node's operands.
8904     SmallVector<SDValue, 8> Ops;
8905     Ops.push_back(N->getOperand(0)); // incoming chain
8906     Ops.push_back(N->getOperand(AddrOpIdx));
8907     Ops.push_back(Inc);
8908
8909     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
8910       // Try to match the intrinsic's signature
8911       Ops.push_back(StN->getValue());
8912     } else {
8913       // Loads (and of course intrinsics) match the intrinsics' signature,
8914       // so just add all but the alignment operand.
8915       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
8916         Ops.push_back(N->getOperand(i));
8917     }
8918
8919     // For all node types, the alignment operand is always the last one.
8920     Ops.push_back(DAG.getConstant(Alignment, MVT::i32));
8921
8922     // If this is a non-standard-aligned STORE, the penultimate operand is the
8923     // stored value.  Bitcast it to the aligned type.
8924     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
8925       SDValue &StVal = Ops[Ops.size()-2];
8926       StVal = DAG.getNode(ISD::BITCAST, SDLoc(N), AlignedVecTy, StVal);
8927     }
8928
8929     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8930                                            Ops, AlignedVecTy,
8931                                            MemN->getMemOperand());
8932
8933     // Update the uses.
8934     SmallVector<SDValue, 5> NewResults;
8935     for (unsigned i = 0; i < NumResultVecs; ++i)
8936       NewResults.push_back(SDValue(UpdN.getNode(), i));
8937
8938     // If this is an non-standard-aligned LOAD, the first result is the loaded
8939     // value.  Bitcast it to the expected result type.
8940     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
8941       SDValue &LdVal = NewResults[0];
8942       LdVal = DAG.getNode(ISD::BITCAST, SDLoc(N), VecTy, LdVal);
8943     }
8944
8945     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8946     DCI.CombineTo(N, NewResults);
8947     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8948
8949     break;
8950   }
8951   return SDValue();
8952 }
8953
8954 static SDValue PerformVLDCombine(SDNode *N,
8955                                  TargetLowering::DAGCombinerInfo &DCI) {
8956   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8957     return SDValue();
8958
8959   return CombineBaseUpdate(N, DCI);
8960 }
8961
8962 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8963 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8964 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8965 /// return true.
8966 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8967   SelectionDAG &DAG = DCI.DAG;
8968   EVT VT = N->getValueType(0);
8969   // vldN-dup instructions only support 64-bit vectors for N > 1.
8970   if (!VT.is64BitVector())
8971     return false;
8972
8973   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8974   SDNode *VLD = N->getOperand(0).getNode();
8975   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8976     return false;
8977   unsigned NumVecs = 0;
8978   unsigned NewOpc = 0;
8979   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8980   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8981     NumVecs = 2;
8982     NewOpc = ARMISD::VLD2DUP;
8983   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8984     NumVecs = 3;
8985     NewOpc = ARMISD::VLD3DUP;
8986   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8987     NumVecs = 4;
8988     NewOpc = ARMISD::VLD4DUP;
8989   } else {
8990     return false;
8991   }
8992
8993   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8994   // numbers match the load.
8995   unsigned VLDLaneNo =
8996     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8997   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8998        UI != UE; ++UI) {
8999     // Ignore uses of the chain result.
9000     if (UI.getUse().getResNo() == NumVecs)
9001       continue;
9002     SDNode *User = *UI;
9003     if (User->getOpcode() != ARMISD::VDUPLANE ||
9004         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9005       return false;
9006   }
9007
9008   // Create the vldN-dup node.
9009   EVT Tys[5];
9010   unsigned n;
9011   for (n = 0; n < NumVecs; ++n)
9012     Tys[n] = VT;
9013   Tys[n] = MVT::Other;
9014   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9015   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9016   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9017   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9018                                            Ops, VLDMemInt->getMemoryVT(),
9019                                            VLDMemInt->getMemOperand());
9020
9021   // Update the uses.
9022   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9023        UI != UE; ++UI) {
9024     unsigned ResNo = UI.getUse().getResNo();
9025     // Ignore uses of the chain result.
9026     if (ResNo == NumVecs)
9027       continue;
9028     SDNode *User = *UI;
9029     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9030   }
9031
9032   // Now the vldN-lane intrinsic is dead except for its chain result.
9033   // Update uses of the chain.
9034   std::vector<SDValue> VLDDupResults;
9035   for (unsigned n = 0; n < NumVecs; ++n)
9036     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9037   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9038   DCI.CombineTo(VLD, VLDDupResults);
9039
9040   return true;
9041 }
9042
9043 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9044 /// ARMISD::VDUPLANE.
9045 static SDValue PerformVDUPLANECombine(SDNode *N,
9046                                       TargetLowering::DAGCombinerInfo &DCI) {
9047   SDValue Op = N->getOperand(0);
9048
9049   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9050   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9051   if (CombineVLDDUP(N, DCI))
9052     return SDValue(N, 0);
9053
9054   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9055   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9056   while (Op.getOpcode() == ISD::BITCAST)
9057     Op = Op.getOperand(0);
9058   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9059     return SDValue();
9060
9061   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9062   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9063   // The canonical VMOV for a zero vector uses a 32-bit element size.
9064   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9065   unsigned EltBits;
9066   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9067     EltSize = 8;
9068   EVT VT = N->getValueType(0);
9069   if (EltSize > VT.getVectorElementType().getSizeInBits())
9070     return SDValue();
9071
9072   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9073 }
9074
9075 static SDValue PerformLOADCombine(SDNode *N,
9076                                   TargetLowering::DAGCombinerInfo &DCI) {
9077   EVT VT = N->getValueType(0);
9078
9079   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9080   if (ISD::isNormalLoad(N) && VT.isVector() &&
9081       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9082     return CombineBaseUpdate(N, DCI);
9083
9084   return SDValue();
9085 }
9086
9087 /// PerformSTORECombine - Target-specific dag combine xforms for
9088 /// ISD::STORE.
9089 static SDValue PerformSTORECombine(SDNode *N,
9090                                    TargetLowering::DAGCombinerInfo &DCI) {
9091   StoreSDNode *St = cast<StoreSDNode>(N);
9092   if (St->isVolatile())
9093     return SDValue();
9094
9095   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9096   // pack all of the elements in one place.  Next, store to memory in fewer
9097   // chunks.
9098   SDValue StVal = St->getValue();
9099   EVT VT = StVal.getValueType();
9100   if (St->isTruncatingStore() && VT.isVector()) {
9101     SelectionDAG &DAG = DCI.DAG;
9102     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9103     EVT StVT = St->getMemoryVT();
9104     unsigned NumElems = VT.getVectorNumElements();
9105     assert(StVT != VT && "Cannot truncate to the same type");
9106     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9107     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9108
9109     // From, To sizes and ElemCount must be pow of two
9110     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9111
9112     // We are going to use the original vector elt for storing.
9113     // Accumulated smaller vector elements must be a multiple of the store size.
9114     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9115
9116     unsigned SizeRatio  = FromEltSz / ToEltSz;
9117     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9118
9119     // Create a type on which we perform the shuffle.
9120     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9121                                      NumElems*SizeRatio);
9122     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9123
9124     SDLoc DL(St);
9125     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9126     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9127     for (unsigned i = 0; i < NumElems; ++i)
9128       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9129
9130     // Can't shuffle using an illegal type.
9131     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9132
9133     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9134                                 DAG.getUNDEF(WideVec.getValueType()),
9135                                 ShuffleVec.data());
9136     // At this point all of the data is stored at the bottom of the
9137     // register. We now need to save it to mem.
9138
9139     // Find the largest store unit
9140     MVT StoreType = MVT::i8;
9141     for (MVT Tp : MVT::integer_valuetypes()) {
9142       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9143         StoreType = Tp;
9144     }
9145     // Didn't find a legal store type.
9146     if (!TLI.isTypeLegal(StoreType))
9147       return SDValue();
9148
9149     // Bitcast the original vector into a vector of store-size units
9150     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9151             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9152     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9153     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9154     SmallVector<SDValue, 8> Chains;
9155     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9156                                         TLI.getPointerTy());
9157     SDValue BasePtr = St->getBasePtr();
9158
9159     // Perform one or more big stores into memory.
9160     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9161     for (unsigned I = 0; I < E; I++) {
9162       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9163                                    StoreType, ShuffWide,
9164                                    DAG.getIntPtrConstant(I));
9165       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9166                                 St->getPointerInfo(), St->isVolatile(),
9167                                 St->isNonTemporal(), St->getAlignment());
9168       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9169                             Increment);
9170       Chains.push_back(Ch);
9171     }
9172     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9173   }
9174
9175   if (!ISD::isNormalStore(St))
9176     return SDValue();
9177
9178   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9179   // ARM stores of arguments in the same cache line.
9180   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9181       StVal.getNode()->hasOneUse()) {
9182     SelectionDAG  &DAG = DCI.DAG;
9183     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9184     SDLoc DL(St);
9185     SDValue BasePtr = St->getBasePtr();
9186     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9187                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9188                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9189                                   St->isNonTemporal(), St->getAlignment());
9190
9191     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9192                                     DAG.getConstant(4, MVT::i32));
9193     return DAG.getStore(NewST1.getValue(0), DL,
9194                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9195                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9196                         St->isNonTemporal(),
9197                         std::min(4U, St->getAlignment() / 2));
9198   }
9199
9200   if (StVal.getValueType() == MVT::i64 &&
9201       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9202
9203     // Bitcast an i64 store extracted from a vector to f64.
9204     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9205     SelectionDAG &DAG = DCI.DAG;
9206     SDLoc dl(StVal);
9207     SDValue IntVec = StVal.getOperand(0);
9208     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9209                                    IntVec.getValueType().getVectorNumElements());
9210     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9211     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9212                                  Vec, StVal.getOperand(1));
9213     dl = SDLoc(N);
9214     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9215     // Make the DAGCombiner fold the bitcasts.
9216     DCI.AddToWorklist(Vec.getNode());
9217     DCI.AddToWorklist(ExtElt.getNode());
9218     DCI.AddToWorklist(V.getNode());
9219     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9220                         St->getPointerInfo(), St->isVolatile(),
9221                         St->isNonTemporal(), St->getAlignment(),
9222                         St->getAAInfo());
9223   }
9224
9225   // If this is a legal vector store, try to combine it into a VST1_UPD.
9226   if (ISD::isNormalStore(N) && VT.isVector() &&
9227       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9228     return CombineBaseUpdate(N, DCI);
9229
9230   return SDValue();
9231 }
9232
9233 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9234 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9235 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9236 {
9237   integerPart cN;
9238   integerPart c0 = 0;
9239   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9240        I != E; I++) {
9241     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9242     if (!C)
9243       return false;
9244
9245     bool isExact;
9246     APFloat APF = C->getValueAPF();
9247     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9248         != APFloat::opOK || !isExact)
9249       return false;
9250
9251     c0 = (I == 0) ? cN : c0;
9252     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9253       return false;
9254   }
9255   C = c0;
9256   return true;
9257 }
9258
9259 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9260 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9261 /// when the VMUL has a constant operand that is a power of 2.
9262 ///
9263 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9264 ///  vmul.f32        d16, d17, d16
9265 ///  vcvt.s32.f32    d16, d16
9266 /// becomes:
9267 ///  vcvt.s32.f32    d16, d16, #3
9268 static SDValue PerformVCVTCombine(SDNode *N,
9269                                   TargetLowering::DAGCombinerInfo &DCI,
9270                                   const ARMSubtarget *Subtarget) {
9271   SelectionDAG &DAG = DCI.DAG;
9272   SDValue Op = N->getOperand(0);
9273
9274   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9275       Op.getOpcode() != ISD::FMUL)
9276     return SDValue();
9277
9278   uint64_t C;
9279   SDValue N0 = Op->getOperand(0);
9280   SDValue ConstVec = Op->getOperand(1);
9281   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9282
9283   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9284       !isConstVecPow2(ConstVec, isSigned, C))
9285     return SDValue();
9286
9287   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9288   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9289   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9290   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9291       NumLanes > 4) {
9292     // These instructions only exist converting from f32 to i32. We can handle
9293     // smaller integers by generating an extra truncate, but larger ones would
9294     // be lossy. We also can't handle more then 4 lanes, since these intructions
9295     // only support v2i32/v4i32 types.
9296     return SDValue();
9297   }
9298
9299   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9300     Intrinsic::arm_neon_vcvtfp2fxu;
9301   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9302                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9303                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9304                                  DAG.getConstant(Log2_64(C), MVT::i32));
9305
9306   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9307     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9308
9309   return FixConv;
9310 }
9311
9312 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9313 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9314 /// when the VDIV has a constant operand that is a power of 2.
9315 ///
9316 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9317 ///  vcvt.f32.s32    d16, d16
9318 ///  vdiv.f32        d16, d17, d16
9319 /// becomes:
9320 ///  vcvt.f32.s32    d16, d16, #3
9321 static SDValue PerformVDIVCombine(SDNode *N,
9322                                   TargetLowering::DAGCombinerInfo &DCI,
9323                                   const ARMSubtarget *Subtarget) {
9324   SelectionDAG &DAG = DCI.DAG;
9325   SDValue Op = N->getOperand(0);
9326   unsigned OpOpcode = Op.getNode()->getOpcode();
9327
9328   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9329       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9330     return SDValue();
9331
9332   uint64_t C;
9333   SDValue ConstVec = N->getOperand(1);
9334   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9335
9336   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9337       !isConstVecPow2(ConstVec, isSigned, C))
9338     return SDValue();
9339
9340   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9341   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9342   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9343     // These instructions only exist converting from i32 to f32. We can handle
9344     // smaller integers by generating an extra extend, but larger ones would
9345     // be lossy.
9346     return SDValue();
9347   }
9348
9349   SDValue ConvInput = Op.getOperand(0);
9350   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9351   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9352     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9353                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9354                             ConvInput);
9355
9356   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9357     Intrinsic::arm_neon_vcvtfxu2fp;
9358   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9359                      Op.getValueType(),
9360                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9361                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9362 }
9363
9364 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9365 /// operand of a vector shift operation, where all the elements of the
9366 /// build_vector must have the same constant integer value.
9367 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9368   // Ignore bit_converts.
9369   while (Op.getOpcode() == ISD::BITCAST)
9370     Op = Op.getOperand(0);
9371   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9372   APInt SplatBits, SplatUndef;
9373   unsigned SplatBitSize;
9374   bool HasAnyUndefs;
9375   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9376                                       HasAnyUndefs, ElementBits) ||
9377       SplatBitSize > ElementBits)
9378     return false;
9379   Cnt = SplatBits.getSExtValue();
9380   return true;
9381 }
9382
9383 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9384 /// operand of a vector shift left operation.  That value must be in the range:
9385 ///   0 <= Value < ElementBits for a left shift; or
9386 ///   0 <= Value <= ElementBits for a long left shift.
9387 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9388   assert(VT.isVector() && "vector shift count is not a vector type");
9389   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9390   if (! getVShiftImm(Op, ElementBits, Cnt))
9391     return false;
9392   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9393 }
9394
9395 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9396 /// operand of a vector shift right operation.  For a shift opcode, the value
9397 /// is positive, but for an intrinsic the value count must be negative. The
9398 /// absolute value must be in the range:
9399 ///   1 <= |Value| <= ElementBits for a right shift; or
9400 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9401 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9402                          int64_t &Cnt) {
9403   assert(VT.isVector() && "vector shift count is not a vector type");
9404   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9405   if (! getVShiftImm(Op, ElementBits, Cnt))
9406     return false;
9407   if (isIntrinsic)
9408     Cnt = -Cnt;
9409   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9410 }
9411
9412 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9413 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9414   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9415   switch (IntNo) {
9416   default:
9417     // Don't do anything for most intrinsics.
9418     break;
9419
9420   // Vector shifts: check for immediate versions and lower them.
9421   // Note: This is done during DAG combining instead of DAG legalizing because
9422   // the build_vectors for 64-bit vector element shift counts are generally
9423   // not legal, and it is hard to see their values after they get legalized to
9424   // loads from a constant pool.
9425   case Intrinsic::arm_neon_vshifts:
9426   case Intrinsic::arm_neon_vshiftu:
9427   case Intrinsic::arm_neon_vrshifts:
9428   case Intrinsic::arm_neon_vrshiftu:
9429   case Intrinsic::arm_neon_vrshiftn:
9430   case Intrinsic::arm_neon_vqshifts:
9431   case Intrinsic::arm_neon_vqshiftu:
9432   case Intrinsic::arm_neon_vqshiftsu:
9433   case Intrinsic::arm_neon_vqshiftns:
9434   case Intrinsic::arm_neon_vqshiftnu:
9435   case Intrinsic::arm_neon_vqshiftnsu:
9436   case Intrinsic::arm_neon_vqrshiftns:
9437   case Intrinsic::arm_neon_vqrshiftnu:
9438   case Intrinsic::arm_neon_vqrshiftnsu: {
9439     EVT VT = N->getOperand(1).getValueType();
9440     int64_t Cnt;
9441     unsigned VShiftOpc = 0;
9442
9443     switch (IntNo) {
9444     case Intrinsic::arm_neon_vshifts:
9445     case Intrinsic::arm_neon_vshiftu:
9446       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9447         VShiftOpc = ARMISD::VSHL;
9448         break;
9449       }
9450       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9451         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9452                      ARMISD::VSHRs : ARMISD::VSHRu);
9453         break;
9454       }
9455       return SDValue();
9456
9457     case Intrinsic::arm_neon_vrshifts:
9458     case Intrinsic::arm_neon_vrshiftu:
9459       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9460         break;
9461       return SDValue();
9462
9463     case Intrinsic::arm_neon_vqshifts:
9464     case Intrinsic::arm_neon_vqshiftu:
9465       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9466         break;
9467       return SDValue();
9468
9469     case Intrinsic::arm_neon_vqshiftsu:
9470       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9471         break;
9472       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9473
9474     case Intrinsic::arm_neon_vrshiftn:
9475     case Intrinsic::arm_neon_vqshiftns:
9476     case Intrinsic::arm_neon_vqshiftnu:
9477     case Intrinsic::arm_neon_vqshiftnsu:
9478     case Intrinsic::arm_neon_vqrshiftns:
9479     case Intrinsic::arm_neon_vqrshiftnu:
9480     case Intrinsic::arm_neon_vqrshiftnsu:
9481       // Narrowing shifts require an immediate right shift.
9482       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9483         break;
9484       llvm_unreachable("invalid shift count for narrowing vector shift "
9485                        "intrinsic");
9486
9487     default:
9488       llvm_unreachable("unhandled vector shift");
9489     }
9490
9491     switch (IntNo) {
9492     case Intrinsic::arm_neon_vshifts:
9493     case Intrinsic::arm_neon_vshiftu:
9494       // Opcode already set above.
9495       break;
9496     case Intrinsic::arm_neon_vrshifts:
9497       VShiftOpc = ARMISD::VRSHRs; break;
9498     case Intrinsic::arm_neon_vrshiftu:
9499       VShiftOpc = ARMISD::VRSHRu; break;
9500     case Intrinsic::arm_neon_vrshiftn:
9501       VShiftOpc = ARMISD::VRSHRN; break;
9502     case Intrinsic::arm_neon_vqshifts:
9503       VShiftOpc = ARMISD::VQSHLs; break;
9504     case Intrinsic::arm_neon_vqshiftu:
9505       VShiftOpc = ARMISD::VQSHLu; break;
9506     case Intrinsic::arm_neon_vqshiftsu:
9507       VShiftOpc = ARMISD::VQSHLsu; break;
9508     case Intrinsic::arm_neon_vqshiftns:
9509       VShiftOpc = ARMISD::VQSHRNs; break;
9510     case Intrinsic::arm_neon_vqshiftnu:
9511       VShiftOpc = ARMISD::VQSHRNu; break;
9512     case Intrinsic::arm_neon_vqshiftnsu:
9513       VShiftOpc = ARMISD::VQSHRNsu; break;
9514     case Intrinsic::arm_neon_vqrshiftns:
9515       VShiftOpc = ARMISD::VQRSHRNs; break;
9516     case Intrinsic::arm_neon_vqrshiftnu:
9517       VShiftOpc = ARMISD::VQRSHRNu; break;
9518     case Intrinsic::arm_neon_vqrshiftnsu:
9519       VShiftOpc = ARMISD::VQRSHRNsu; break;
9520     }
9521
9522     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9523                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9524   }
9525
9526   case Intrinsic::arm_neon_vshiftins: {
9527     EVT VT = N->getOperand(1).getValueType();
9528     int64_t Cnt;
9529     unsigned VShiftOpc = 0;
9530
9531     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9532       VShiftOpc = ARMISD::VSLI;
9533     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9534       VShiftOpc = ARMISD::VSRI;
9535     else {
9536       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9537     }
9538
9539     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9540                        N->getOperand(1), N->getOperand(2),
9541                        DAG.getConstant(Cnt, MVT::i32));
9542   }
9543
9544   case Intrinsic::arm_neon_vqrshifts:
9545   case Intrinsic::arm_neon_vqrshiftu:
9546     // No immediate versions of these to check for.
9547     break;
9548   }
9549
9550   return SDValue();
9551 }
9552
9553 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9554 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9555 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9556 /// vector element shift counts are generally not legal, and it is hard to see
9557 /// their values after they get legalized to loads from a constant pool.
9558 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9559                                    const ARMSubtarget *ST) {
9560   EVT VT = N->getValueType(0);
9561   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9562     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9563     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9564     SDValue N1 = N->getOperand(1);
9565     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9566       SDValue N0 = N->getOperand(0);
9567       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9568           DAG.MaskedValueIsZero(N0.getOperand(0),
9569                                 APInt::getHighBitsSet(32, 16)))
9570         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9571     }
9572   }
9573
9574   // Nothing to be done for scalar shifts.
9575   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9576   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9577     return SDValue();
9578
9579   assert(ST->hasNEON() && "unexpected vector shift");
9580   int64_t Cnt;
9581
9582   switch (N->getOpcode()) {
9583   default: llvm_unreachable("unexpected shift opcode");
9584
9585   case ISD::SHL:
9586     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9587       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9588                          DAG.getConstant(Cnt, MVT::i32));
9589     break;
9590
9591   case ISD::SRA:
9592   case ISD::SRL:
9593     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9594       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9595                             ARMISD::VSHRs : ARMISD::VSHRu);
9596       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9597                          DAG.getConstant(Cnt, MVT::i32));
9598     }
9599   }
9600   return SDValue();
9601 }
9602
9603 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9604 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9605 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9606                                     const ARMSubtarget *ST) {
9607   SDValue N0 = N->getOperand(0);
9608
9609   // Check for sign- and zero-extensions of vector extract operations of 8-
9610   // and 16-bit vector elements.  NEON supports these directly.  They are
9611   // handled during DAG combining because type legalization will promote them
9612   // to 32-bit types and it is messy to recognize the operations after that.
9613   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9614     SDValue Vec = N0.getOperand(0);
9615     SDValue Lane = N0.getOperand(1);
9616     EVT VT = N->getValueType(0);
9617     EVT EltVT = N0.getValueType();
9618     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9619
9620     if (VT == MVT::i32 &&
9621         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9622         TLI.isTypeLegal(Vec.getValueType()) &&
9623         isa<ConstantSDNode>(Lane)) {
9624
9625       unsigned Opc = 0;
9626       switch (N->getOpcode()) {
9627       default: llvm_unreachable("unexpected opcode");
9628       case ISD::SIGN_EXTEND:
9629         Opc = ARMISD::VGETLANEs;
9630         break;
9631       case ISD::ZERO_EXTEND:
9632       case ISD::ANY_EXTEND:
9633         Opc = ARMISD::VGETLANEu;
9634         break;
9635       }
9636       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9637     }
9638   }
9639
9640   return SDValue();
9641 }
9642
9643 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9644 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9645 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9646                                        const ARMSubtarget *ST) {
9647   // If the target supports NEON, try to use vmax/vmin instructions for f32
9648   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9649   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9650   // a NaN; only do the transformation when it matches that behavior.
9651
9652   // For now only do this when using NEON for FP operations; if using VFP, it
9653   // is not obvious that the benefit outweighs the cost of switching to the
9654   // NEON pipeline.
9655   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9656       N->getValueType(0) != MVT::f32)
9657     return SDValue();
9658
9659   SDValue CondLHS = N->getOperand(0);
9660   SDValue CondRHS = N->getOperand(1);
9661   SDValue LHS = N->getOperand(2);
9662   SDValue RHS = N->getOperand(3);
9663   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9664
9665   unsigned Opcode = 0;
9666   bool IsReversed;
9667   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9668     IsReversed = false; // x CC y ? x : y
9669   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9670     IsReversed = true ; // x CC y ? y : x
9671   } else {
9672     return SDValue();
9673   }
9674
9675   bool IsUnordered;
9676   switch (CC) {
9677   default: break;
9678   case ISD::SETOLT:
9679   case ISD::SETOLE:
9680   case ISD::SETLT:
9681   case ISD::SETLE:
9682   case ISD::SETULT:
9683   case ISD::SETULE:
9684     // If LHS is NaN, an ordered comparison will be false and the result will
9685     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9686     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9687     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9688     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9689       break;
9690     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9691     // will return -0, so vmin can only be used for unsafe math or if one of
9692     // the operands is known to be nonzero.
9693     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9694         !DAG.getTarget().Options.UnsafeFPMath &&
9695         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9696       break;
9697     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9698     break;
9699
9700   case ISD::SETOGT:
9701   case ISD::SETOGE:
9702   case ISD::SETGT:
9703   case ISD::SETGE:
9704   case ISD::SETUGT:
9705   case ISD::SETUGE:
9706     // If LHS is NaN, an ordered comparison will be false and the result will
9707     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9708     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9709     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9710     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9711       break;
9712     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9713     // will return +0, so vmax can only be used for unsafe math or if one of
9714     // the operands is known to be nonzero.
9715     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9716         !DAG.getTarget().Options.UnsafeFPMath &&
9717         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9718       break;
9719     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9720     break;
9721   }
9722
9723   if (!Opcode)
9724     return SDValue();
9725   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9726 }
9727
9728 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9729 SDValue
9730 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9731   SDValue Cmp = N->getOperand(4);
9732   if (Cmp.getOpcode() != ARMISD::CMPZ)
9733     // Only looking at EQ and NE cases.
9734     return SDValue();
9735
9736   EVT VT = N->getValueType(0);
9737   SDLoc dl(N);
9738   SDValue LHS = Cmp.getOperand(0);
9739   SDValue RHS = Cmp.getOperand(1);
9740   SDValue FalseVal = N->getOperand(0);
9741   SDValue TrueVal = N->getOperand(1);
9742   SDValue ARMcc = N->getOperand(2);
9743   ARMCC::CondCodes CC =
9744     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9745
9746   // Simplify
9747   //   mov     r1, r0
9748   //   cmp     r1, x
9749   //   mov     r0, y
9750   //   moveq   r0, x
9751   // to
9752   //   cmp     r0, x
9753   //   movne   r0, y
9754   //
9755   //   mov     r1, r0
9756   //   cmp     r1, x
9757   //   mov     r0, x
9758   //   movne   r0, y
9759   // to
9760   //   cmp     r0, x
9761   //   movne   r0, y
9762   /// FIXME: Turn this into a target neutral optimization?
9763   SDValue Res;
9764   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9765     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9766                       N->getOperand(3), Cmp);
9767   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9768     SDValue ARMcc;
9769     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9770     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9771                       N->getOperand(3), NewCmp);
9772   }
9773
9774   if (Res.getNode()) {
9775     APInt KnownZero, KnownOne;
9776     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9777     // Capture demanded bits information that would be otherwise lost.
9778     if (KnownZero == 0xfffffffe)
9779       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9780                         DAG.getValueType(MVT::i1));
9781     else if (KnownZero == 0xffffff00)
9782       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9783                         DAG.getValueType(MVT::i8));
9784     else if (KnownZero == 0xffff0000)
9785       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9786                         DAG.getValueType(MVT::i16));
9787   }
9788
9789   return Res;
9790 }
9791
9792 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9793                                              DAGCombinerInfo &DCI) const {
9794   switch (N->getOpcode()) {
9795   default: break;
9796   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9797   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9798   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9799   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9800   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9801   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9802   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9803   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9804   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9805   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9806   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9807   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9808   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9809   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9810   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9811   case ISD::FP_TO_SINT:
9812   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9813   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9814   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9815   case ISD::SHL:
9816   case ISD::SRA:
9817   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9818   case ISD::SIGN_EXTEND:
9819   case ISD::ZERO_EXTEND:
9820   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9821   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9822   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9823   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
9824   case ARMISD::VLD2DUP:
9825   case ARMISD::VLD3DUP:
9826   case ARMISD::VLD4DUP:
9827     return PerformVLDCombine(N, DCI);
9828   case ARMISD::BUILD_VECTOR:
9829     return PerformARMBUILD_VECTORCombine(N, DCI);
9830   case ISD::INTRINSIC_VOID:
9831   case ISD::INTRINSIC_W_CHAIN:
9832     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9833     case Intrinsic::arm_neon_vld1:
9834     case Intrinsic::arm_neon_vld2:
9835     case Intrinsic::arm_neon_vld3:
9836     case Intrinsic::arm_neon_vld4:
9837     case Intrinsic::arm_neon_vld2lane:
9838     case Intrinsic::arm_neon_vld3lane:
9839     case Intrinsic::arm_neon_vld4lane:
9840     case Intrinsic::arm_neon_vst1:
9841     case Intrinsic::arm_neon_vst2:
9842     case Intrinsic::arm_neon_vst3:
9843     case Intrinsic::arm_neon_vst4:
9844     case Intrinsic::arm_neon_vst2lane:
9845     case Intrinsic::arm_neon_vst3lane:
9846     case Intrinsic::arm_neon_vst4lane:
9847       return PerformVLDCombine(N, DCI);
9848     default: break;
9849     }
9850     break;
9851   }
9852   return SDValue();
9853 }
9854
9855 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9856                                                           EVT VT) const {
9857   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9858 }
9859
9860 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9861                                                        unsigned,
9862                                                        unsigned,
9863                                                        bool *Fast) const {
9864   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9865   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9866
9867   switch (VT.getSimpleVT().SimpleTy) {
9868   default:
9869     return false;
9870   case MVT::i8:
9871   case MVT::i16:
9872   case MVT::i32: {
9873     // Unaligned access can use (for example) LRDB, LRDH, LDR
9874     if (AllowsUnaligned) {
9875       if (Fast)
9876         *Fast = Subtarget->hasV7Ops();
9877       return true;
9878     }
9879     return false;
9880   }
9881   case MVT::f64:
9882   case MVT::v2f64: {
9883     // For any little-endian targets with neon, we can support unaligned ld/st
9884     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9885     // A big-endian target may also explicitly support unaligned accesses
9886     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9887       if (Fast)
9888         *Fast = true;
9889       return true;
9890     }
9891     return false;
9892   }
9893   }
9894 }
9895
9896 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9897                        unsigned AlignCheck) {
9898   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9899           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9900 }
9901
9902 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9903                                            unsigned DstAlign, unsigned SrcAlign,
9904                                            bool IsMemset, bool ZeroMemset,
9905                                            bool MemcpyStrSrc,
9906                                            MachineFunction &MF) const {
9907   const Function *F = MF.getFunction();
9908
9909   // See if we can use NEON instructions for this...
9910   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
9911       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
9912     bool Fast;
9913     if (Size >= 16 &&
9914         (memOpAlign(SrcAlign, DstAlign, 16) ||
9915          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9916       return MVT::v2f64;
9917     } else if (Size >= 8 &&
9918                (memOpAlign(SrcAlign, DstAlign, 8) ||
9919                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9920                  Fast))) {
9921       return MVT::f64;
9922     }
9923   }
9924
9925   // Lowering to i32/i16 if the size permits.
9926   if (Size >= 4)
9927     return MVT::i32;
9928   else if (Size >= 2)
9929     return MVT::i16;
9930
9931   // Let the target-independent logic figure it out.
9932   return MVT::Other;
9933 }
9934
9935 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9936   if (Val.getOpcode() != ISD::LOAD)
9937     return false;
9938
9939   EVT VT1 = Val.getValueType();
9940   if (!VT1.isSimple() || !VT1.isInteger() ||
9941       !VT2.isSimple() || !VT2.isInteger())
9942     return false;
9943
9944   switch (VT1.getSimpleVT().SimpleTy) {
9945   default: break;
9946   case MVT::i1:
9947   case MVT::i8:
9948   case MVT::i16:
9949     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9950     return true;
9951   }
9952
9953   return false;
9954 }
9955
9956 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
9957   EVT VT = ExtVal.getValueType();
9958
9959   if (!isTypeLegal(VT))
9960     return false;
9961
9962   // Don't create a loadext if we can fold the extension into a wide/long
9963   // instruction.
9964   // If there's more than one user instruction, the loadext is desirable no
9965   // matter what.  There can be two uses by the same instruction.
9966   if (ExtVal->use_empty() ||
9967       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
9968     return true;
9969
9970   SDNode *U = *ExtVal->use_begin();
9971   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
9972        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
9973     return false;
9974
9975   return true;
9976 }
9977
9978 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9979   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9980     return false;
9981
9982   if (!isTypeLegal(EVT::getEVT(Ty1)))
9983     return false;
9984
9985   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9986
9987   // Assuming the caller doesn't have a zeroext or signext return parameter,
9988   // truncation all the way down to i1 is valid.
9989   return true;
9990 }
9991
9992
9993 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9994   if (V < 0)
9995     return false;
9996
9997   unsigned Scale = 1;
9998   switch (VT.getSimpleVT().SimpleTy) {
9999   default: return false;
10000   case MVT::i1:
10001   case MVT::i8:
10002     // Scale == 1;
10003     break;
10004   case MVT::i16:
10005     // Scale == 2;
10006     Scale = 2;
10007     break;
10008   case MVT::i32:
10009     // Scale == 4;
10010     Scale = 4;
10011     break;
10012   }
10013
10014   if ((V & (Scale - 1)) != 0)
10015     return false;
10016   V /= Scale;
10017   return V == (V & ((1LL << 5) - 1));
10018 }
10019
10020 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10021                                       const ARMSubtarget *Subtarget) {
10022   bool isNeg = false;
10023   if (V < 0) {
10024     isNeg = true;
10025     V = - V;
10026   }
10027
10028   switch (VT.getSimpleVT().SimpleTy) {
10029   default: return false;
10030   case MVT::i1:
10031   case MVT::i8:
10032   case MVT::i16:
10033   case MVT::i32:
10034     // + imm12 or - imm8
10035     if (isNeg)
10036       return V == (V & ((1LL << 8) - 1));
10037     return V == (V & ((1LL << 12) - 1));
10038   case MVT::f32:
10039   case MVT::f64:
10040     // Same as ARM mode. FIXME: NEON?
10041     if (!Subtarget->hasVFP2())
10042       return false;
10043     if ((V & 3) != 0)
10044       return false;
10045     V >>= 2;
10046     return V == (V & ((1LL << 8) - 1));
10047   }
10048 }
10049
10050 /// isLegalAddressImmediate - Return true if the integer value can be used
10051 /// as the offset of the target addressing mode for load / store of the
10052 /// given type.
10053 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10054                                     const ARMSubtarget *Subtarget) {
10055   if (V == 0)
10056     return true;
10057
10058   if (!VT.isSimple())
10059     return false;
10060
10061   if (Subtarget->isThumb1Only())
10062     return isLegalT1AddressImmediate(V, VT);
10063   else if (Subtarget->isThumb2())
10064     return isLegalT2AddressImmediate(V, VT, Subtarget);
10065
10066   // ARM mode.
10067   if (V < 0)
10068     V = - V;
10069   switch (VT.getSimpleVT().SimpleTy) {
10070   default: return false;
10071   case MVT::i1:
10072   case MVT::i8:
10073   case MVT::i32:
10074     // +- imm12
10075     return V == (V & ((1LL << 12) - 1));
10076   case MVT::i16:
10077     // +- imm8
10078     return V == (V & ((1LL << 8) - 1));
10079   case MVT::f32:
10080   case MVT::f64:
10081     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10082       return false;
10083     if ((V & 3) != 0)
10084       return false;
10085     V >>= 2;
10086     return V == (V & ((1LL << 8) - 1));
10087   }
10088 }
10089
10090 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10091                                                       EVT VT) const {
10092   int Scale = AM.Scale;
10093   if (Scale < 0)
10094     return false;
10095
10096   switch (VT.getSimpleVT().SimpleTy) {
10097   default: return false;
10098   case MVT::i1:
10099   case MVT::i8:
10100   case MVT::i16:
10101   case MVT::i32:
10102     if (Scale == 1)
10103       return true;
10104     // r + r << imm
10105     Scale = Scale & ~1;
10106     return Scale == 2 || Scale == 4 || Scale == 8;
10107   case MVT::i64:
10108     // r + r
10109     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10110       return true;
10111     return false;
10112   case MVT::isVoid:
10113     // Note, we allow "void" uses (basically, uses that aren't loads or
10114     // stores), because arm allows folding a scale into many arithmetic
10115     // operations.  This should be made more precise and revisited later.
10116
10117     // Allow r << imm, but the imm has to be a multiple of two.
10118     if (Scale & 1) return false;
10119     return isPowerOf2_32(Scale);
10120   }
10121 }
10122
10123 /// isLegalAddressingMode - Return true if the addressing mode represented
10124 /// by AM is legal for this target, for a load/store of the specified type.
10125 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10126                                               Type *Ty) const {
10127   EVT VT = getValueType(Ty, true);
10128   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10129     return false;
10130
10131   // Can never fold addr of global into load/store.
10132   if (AM.BaseGV)
10133     return false;
10134
10135   switch (AM.Scale) {
10136   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10137     break;
10138   case 1:
10139     if (Subtarget->isThumb1Only())
10140       return false;
10141     // FALL THROUGH.
10142   default:
10143     // ARM doesn't support any R+R*scale+imm addr modes.
10144     if (AM.BaseOffs)
10145       return false;
10146
10147     if (!VT.isSimple())
10148       return false;
10149
10150     if (Subtarget->isThumb2())
10151       return isLegalT2ScaledAddressingMode(AM, VT);
10152
10153     int Scale = AM.Scale;
10154     switch (VT.getSimpleVT().SimpleTy) {
10155     default: return false;
10156     case MVT::i1:
10157     case MVT::i8:
10158     case MVT::i32:
10159       if (Scale < 0) Scale = -Scale;
10160       if (Scale == 1)
10161         return true;
10162       // r + r << imm
10163       return isPowerOf2_32(Scale & ~1);
10164     case MVT::i16:
10165     case MVT::i64:
10166       // r + r
10167       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10168         return true;
10169       return false;
10170
10171     case MVT::isVoid:
10172       // Note, we allow "void" uses (basically, uses that aren't loads or
10173       // stores), because arm allows folding a scale into many arithmetic
10174       // operations.  This should be made more precise and revisited later.
10175
10176       // Allow r << imm, but the imm has to be a multiple of two.
10177       if (Scale & 1) return false;
10178       return isPowerOf2_32(Scale);
10179     }
10180   }
10181   return true;
10182 }
10183
10184 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10185 /// icmp immediate, that is the target has icmp instructions which can compare
10186 /// a register against the immediate without having to materialize the
10187 /// immediate into a register.
10188 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10189   // Thumb2 and ARM modes can use cmn for negative immediates.
10190   if (!Subtarget->isThumb())
10191     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10192   if (Subtarget->isThumb2())
10193     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10194   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10195   return Imm >= 0 && Imm <= 255;
10196 }
10197
10198 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10199 /// *or sub* immediate, that is the target has add or sub instructions which can
10200 /// add a register with the immediate without having to materialize the
10201 /// immediate into a register.
10202 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10203   // Same encoding for add/sub, just flip the sign.
10204   int64_t AbsImm = std::abs(Imm);
10205   if (!Subtarget->isThumb())
10206     return ARM_AM::getSOImmVal(AbsImm) != -1;
10207   if (Subtarget->isThumb2())
10208     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10209   // Thumb1 only has 8-bit unsigned immediate.
10210   return AbsImm >= 0 && AbsImm <= 255;
10211 }
10212
10213 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10214                                       bool isSEXTLoad, SDValue &Base,
10215                                       SDValue &Offset, bool &isInc,
10216                                       SelectionDAG &DAG) {
10217   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10218     return false;
10219
10220   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10221     // AddressingMode 3
10222     Base = Ptr->getOperand(0);
10223     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10224       int RHSC = (int)RHS->getZExtValue();
10225       if (RHSC < 0 && RHSC > -256) {
10226         assert(Ptr->getOpcode() == ISD::ADD);
10227         isInc = false;
10228         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10229         return true;
10230       }
10231     }
10232     isInc = (Ptr->getOpcode() == ISD::ADD);
10233     Offset = Ptr->getOperand(1);
10234     return true;
10235   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10236     // AddressingMode 2
10237     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10238       int RHSC = (int)RHS->getZExtValue();
10239       if (RHSC < 0 && RHSC > -0x1000) {
10240         assert(Ptr->getOpcode() == ISD::ADD);
10241         isInc = false;
10242         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10243         Base = Ptr->getOperand(0);
10244         return true;
10245       }
10246     }
10247
10248     if (Ptr->getOpcode() == ISD::ADD) {
10249       isInc = true;
10250       ARM_AM::ShiftOpc ShOpcVal=
10251         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10252       if (ShOpcVal != ARM_AM::no_shift) {
10253         Base = Ptr->getOperand(1);
10254         Offset = Ptr->getOperand(0);
10255       } else {
10256         Base = Ptr->getOperand(0);
10257         Offset = Ptr->getOperand(1);
10258       }
10259       return true;
10260     }
10261
10262     isInc = (Ptr->getOpcode() == ISD::ADD);
10263     Base = Ptr->getOperand(0);
10264     Offset = Ptr->getOperand(1);
10265     return true;
10266   }
10267
10268   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10269   return false;
10270 }
10271
10272 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10273                                      bool isSEXTLoad, SDValue &Base,
10274                                      SDValue &Offset, bool &isInc,
10275                                      SelectionDAG &DAG) {
10276   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10277     return false;
10278
10279   Base = Ptr->getOperand(0);
10280   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10281     int RHSC = (int)RHS->getZExtValue();
10282     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10283       assert(Ptr->getOpcode() == ISD::ADD);
10284       isInc = false;
10285       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10286       return true;
10287     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10288       isInc = Ptr->getOpcode() == ISD::ADD;
10289       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10290       return true;
10291     }
10292   }
10293
10294   return false;
10295 }
10296
10297 /// getPreIndexedAddressParts - returns true by value, base pointer and
10298 /// offset pointer and addressing mode by reference if the node's address
10299 /// can be legally represented as pre-indexed load / store address.
10300 bool
10301 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10302                                              SDValue &Offset,
10303                                              ISD::MemIndexedMode &AM,
10304                                              SelectionDAG &DAG) const {
10305   if (Subtarget->isThumb1Only())
10306     return false;
10307
10308   EVT VT;
10309   SDValue Ptr;
10310   bool isSEXTLoad = false;
10311   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10312     Ptr = LD->getBasePtr();
10313     VT  = LD->getMemoryVT();
10314     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10315   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10316     Ptr = ST->getBasePtr();
10317     VT  = ST->getMemoryVT();
10318   } else
10319     return false;
10320
10321   bool isInc;
10322   bool isLegal = false;
10323   if (Subtarget->isThumb2())
10324     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10325                                        Offset, isInc, DAG);
10326   else
10327     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10328                                         Offset, isInc, DAG);
10329   if (!isLegal)
10330     return false;
10331
10332   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10333   return true;
10334 }
10335
10336 /// getPostIndexedAddressParts - returns true by value, base pointer and
10337 /// offset pointer and addressing mode by reference if this node can be
10338 /// combined with a load / store to form a post-indexed load / store.
10339 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10340                                                    SDValue &Base,
10341                                                    SDValue &Offset,
10342                                                    ISD::MemIndexedMode &AM,
10343                                                    SelectionDAG &DAG) const {
10344   if (Subtarget->isThumb1Only())
10345     return false;
10346
10347   EVT VT;
10348   SDValue Ptr;
10349   bool isSEXTLoad = false;
10350   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10351     VT  = LD->getMemoryVT();
10352     Ptr = LD->getBasePtr();
10353     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10354   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10355     VT  = ST->getMemoryVT();
10356     Ptr = ST->getBasePtr();
10357   } else
10358     return false;
10359
10360   bool isInc;
10361   bool isLegal = false;
10362   if (Subtarget->isThumb2())
10363     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10364                                        isInc, DAG);
10365   else
10366     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10367                                         isInc, DAG);
10368   if (!isLegal)
10369     return false;
10370
10371   if (Ptr != Base) {
10372     // Swap base ptr and offset to catch more post-index load / store when
10373     // it's legal. In Thumb2 mode, offset must be an immediate.
10374     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10375         !Subtarget->isThumb2())
10376       std::swap(Base, Offset);
10377
10378     // Post-indexed load / store update the base pointer.
10379     if (Ptr != Base)
10380       return false;
10381   }
10382
10383   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10384   return true;
10385 }
10386
10387 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10388                                                       APInt &KnownZero,
10389                                                       APInt &KnownOne,
10390                                                       const SelectionDAG &DAG,
10391                                                       unsigned Depth) const {
10392   unsigned BitWidth = KnownOne.getBitWidth();
10393   KnownZero = KnownOne = APInt(BitWidth, 0);
10394   switch (Op.getOpcode()) {
10395   default: break;
10396   case ARMISD::ADDC:
10397   case ARMISD::ADDE:
10398   case ARMISD::SUBC:
10399   case ARMISD::SUBE:
10400     // These nodes' second result is a boolean
10401     if (Op.getResNo() == 0)
10402       break;
10403     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10404     break;
10405   case ARMISD::CMOV: {
10406     // Bits are known zero/one if known on the LHS and RHS.
10407     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10408     if (KnownZero == 0 && KnownOne == 0) return;
10409
10410     APInt KnownZeroRHS, KnownOneRHS;
10411     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10412     KnownZero &= KnownZeroRHS;
10413     KnownOne  &= KnownOneRHS;
10414     return;
10415   }
10416   case ISD::INTRINSIC_W_CHAIN: {
10417     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10418     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10419     switch (IntID) {
10420     default: return;
10421     case Intrinsic::arm_ldaex:
10422     case Intrinsic::arm_ldrex: {
10423       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10424       unsigned MemBits = VT.getScalarType().getSizeInBits();
10425       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10426       return;
10427     }
10428     }
10429   }
10430   }
10431 }
10432
10433 //===----------------------------------------------------------------------===//
10434 //                           ARM Inline Assembly Support
10435 //===----------------------------------------------------------------------===//
10436
10437 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10438   // Looking for "rev" which is V6+.
10439   if (!Subtarget->hasV6Ops())
10440     return false;
10441
10442   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10443   std::string AsmStr = IA->getAsmString();
10444   SmallVector<StringRef, 4> AsmPieces;
10445   SplitString(AsmStr, AsmPieces, ";\n");
10446
10447   switch (AsmPieces.size()) {
10448   default: return false;
10449   case 1:
10450     AsmStr = AsmPieces[0];
10451     AsmPieces.clear();
10452     SplitString(AsmStr, AsmPieces, " \t,");
10453
10454     // rev $0, $1
10455     if (AsmPieces.size() == 3 &&
10456         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10457         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10458       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10459       if (Ty && Ty->getBitWidth() == 32)
10460         return IntrinsicLowering::LowerToByteSwap(CI);
10461     }
10462     break;
10463   }
10464
10465   return false;
10466 }
10467
10468 /// getConstraintType - Given a constraint letter, return the type of
10469 /// constraint it is for this target.
10470 ARMTargetLowering::ConstraintType
10471 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10472   if (Constraint.size() == 1) {
10473     switch (Constraint[0]) {
10474     default:  break;
10475     case 'l': return C_RegisterClass;
10476     case 'w': return C_RegisterClass;
10477     case 'h': return C_RegisterClass;
10478     case 'x': return C_RegisterClass;
10479     case 't': return C_RegisterClass;
10480     case 'j': return C_Other; // Constant for movw.
10481       // An address with a single base register. Due to the way we
10482       // currently handle addresses it is the same as an 'r' memory constraint.
10483     case 'Q': return C_Memory;
10484     }
10485   } else if (Constraint.size() == 2) {
10486     switch (Constraint[0]) {
10487     default: break;
10488     // All 'U+' constraints are addresses.
10489     case 'U': return C_Memory;
10490     }
10491   }
10492   return TargetLowering::getConstraintType(Constraint);
10493 }
10494
10495 /// Examine constraint type and operand type and determine a weight value.
10496 /// This object must already have been set up with the operand type
10497 /// and the current alternative constraint selected.
10498 TargetLowering::ConstraintWeight
10499 ARMTargetLowering::getSingleConstraintMatchWeight(
10500     AsmOperandInfo &info, const char *constraint) const {
10501   ConstraintWeight weight = CW_Invalid;
10502   Value *CallOperandVal = info.CallOperandVal;
10503     // If we don't have a value, we can't do a match,
10504     // but allow it at the lowest weight.
10505   if (!CallOperandVal)
10506     return CW_Default;
10507   Type *type = CallOperandVal->getType();
10508   // Look at the constraint type.
10509   switch (*constraint) {
10510   default:
10511     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10512     break;
10513   case 'l':
10514     if (type->isIntegerTy()) {
10515       if (Subtarget->isThumb())
10516         weight = CW_SpecificReg;
10517       else
10518         weight = CW_Register;
10519     }
10520     break;
10521   case 'w':
10522     if (type->isFloatingPointTy())
10523       weight = CW_Register;
10524     break;
10525   }
10526   return weight;
10527 }
10528
10529 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10530 RCPair
10531 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10532                                                 const std::string &Constraint,
10533                                                 MVT VT) const {
10534   if (Constraint.size() == 1) {
10535     // GCC ARM Constraint Letters
10536     switch (Constraint[0]) {
10537     case 'l': // Low regs or general regs.
10538       if (Subtarget->isThumb())
10539         return RCPair(0U, &ARM::tGPRRegClass);
10540       return RCPair(0U, &ARM::GPRRegClass);
10541     case 'h': // High regs or no regs.
10542       if (Subtarget->isThumb())
10543         return RCPair(0U, &ARM::hGPRRegClass);
10544       break;
10545     case 'r':
10546       if (Subtarget->isThumb1Only())
10547         return RCPair(0U, &ARM::tGPRRegClass);
10548       return RCPair(0U, &ARM::GPRRegClass);
10549     case 'w':
10550       if (VT == MVT::Other)
10551         break;
10552       if (VT == MVT::f32)
10553         return RCPair(0U, &ARM::SPRRegClass);
10554       if (VT.getSizeInBits() == 64)
10555         return RCPair(0U, &ARM::DPRRegClass);
10556       if (VT.getSizeInBits() == 128)
10557         return RCPair(0U, &ARM::QPRRegClass);
10558       break;
10559     case 'x':
10560       if (VT == MVT::Other)
10561         break;
10562       if (VT == MVT::f32)
10563         return RCPair(0U, &ARM::SPR_8RegClass);
10564       if (VT.getSizeInBits() == 64)
10565         return RCPair(0U, &ARM::DPR_8RegClass);
10566       if (VT.getSizeInBits() == 128)
10567         return RCPair(0U, &ARM::QPR_8RegClass);
10568       break;
10569     case 't':
10570       if (VT == MVT::f32)
10571         return RCPair(0U, &ARM::SPRRegClass);
10572       break;
10573     }
10574   }
10575   if (StringRef("{cc}").equals_lower(Constraint))
10576     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10577
10578   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10579 }
10580
10581 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10582 /// vector.  If it is invalid, don't add anything to Ops.
10583 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10584                                                      std::string &Constraint,
10585                                                      std::vector<SDValue>&Ops,
10586                                                      SelectionDAG &DAG) const {
10587   SDValue Result;
10588
10589   // Currently only support length 1 constraints.
10590   if (Constraint.length() != 1) return;
10591
10592   char ConstraintLetter = Constraint[0];
10593   switch (ConstraintLetter) {
10594   default: break;
10595   case 'j':
10596   case 'I': case 'J': case 'K': case 'L':
10597   case 'M': case 'N': case 'O':
10598     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10599     if (!C)
10600       return;
10601
10602     int64_t CVal64 = C->getSExtValue();
10603     int CVal = (int) CVal64;
10604     // None of these constraints allow values larger than 32 bits.  Check
10605     // that the value fits in an int.
10606     if (CVal != CVal64)
10607       return;
10608
10609     switch (ConstraintLetter) {
10610       case 'j':
10611         // Constant suitable for movw, must be between 0 and
10612         // 65535.
10613         if (Subtarget->hasV6T2Ops())
10614           if (CVal >= 0 && CVal <= 65535)
10615             break;
10616         return;
10617       case 'I':
10618         if (Subtarget->isThumb1Only()) {
10619           // This must be a constant between 0 and 255, for ADD
10620           // immediates.
10621           if (CVal >= 0 && CVal <= 255)
10622             break;
10623         } else if (Subtarget->isThumb2()) {
10624           // A constant that can be used as an immediate value in a
10625           // data-processing instruction.
10626           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10627             break;
10628         } else {
10629           // A constant that can be used as an immediate value in a
10630           // data-processing instruction.
10631           if (ARM_AM::getSOImmVal(CVal) != -1)
10632             break;
10633         }
10634         return;
10635
10636       case 'J':
10637         if (Subtarget->isThumb()) {  // FIXME thumb2
10638           // This must be a constant between -255 and -1, for negated ADD
10639           // immediates. This can be used in GCC with an "n" modifier that
10640           // prints the negated value, for use with SUB instructions. It is
10641           // not useful otherwise but is implemented for compatibility.
10642           if (CVal >= -255 && CVal <= -1)
10643             break;
10644         } else {
10645           // This must be a constant between -4095 and 4095. It is not clear
10646           // what this constraint is intended for. Implemented for
10647           // compatibility with GCC.
10648           if (CVal >= -4095 && CVal <= 4095)
10649             break;
10650         }
10651         return;
10652
10653       case 'K':
10654         if (Subtarget->isThumb1Only()) {
10655           // A 32-bit value where only one byte has a nonzero value. Exclude
10656           // zero to match GCC. This constraint is used by GCC internally for
10657           // constants that can be loaded with a move/shift combination.
10658           // It is not useful otherwise but is implemented for compatibility.
10659           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10660             break;
10661         } else if (Subtarget->isThumb2()) {
10662           // A constant whose bitwise inverse can be used as an immediate
10663           // value in a data-processing instruction. This can be used in GCC
10664           // with a "B" modifier that prints the inverted value, for use with
10665           // BIC and MVN instructions. It is not useful otherwise but is
10666           // implemented for compatibility.
10667           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10668             break;
10669         } else {
10670           // A constant whose bitwise inverse can be used as an immediate
10671           // value in a data-processing instruction. This can be used in GCC
10672           // with a "B" modifier that prints the inverted value, for use with
10673           // BIC and MVN instructions. It is not useful otherwise but is
10674           // implemented for compatibility.
10675           if (ARM_AM::getSOImmVal(~CVal) != -1)
10676             break;
10677         }
10678         return;
10679
10680       case 'L':
10681         if (Subtarget->isThumb1Only()) {
10682           // This must be a constant between -7 and 7,
10683           // for 3-operand ADD/SUB immediate instructions.
10684           if (CVal >= -7 && CVal < 7)
10685             break;
10686         } else if (Subtarget->isThumb2()) {
10687           // A constant whose negation can be used as an immediate value in a
10688           // data-processing instruction. This can be used in GCC with an "n"
10689           // modifier that prints the negated value, for use with SUB
10690           // instructions. It is not useful otherwise but is implemented for
10691           // compatibility.
10692           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10693             break;
10694         } else {
10695           // A constant whose negation can be used as an immediate value in a
10696           // data-processing instruction. This can be used in GCC with an "n"
10697           // modifier that prints the negated value, for use with SUB
10698           // instructions. It is not useful otherwise but is implemented for
10699           // compatibility.
10700           if (ARM_AM::getSOImmVal(-CVal) != -1)
10701             break;
10702         }
10703         return;
10704
10705       case 'M':
10706         if (Subtarget->isThumb()) { // FIXME thumb2
10707           // This must be a multiple of 4 between 0 and 1020, for
10708           // ADD sp + immediate.
10709           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10710             break;
10711         } else {
10712           // A power of two or a constant between 0 and 32.  This is used in
10713           // GCC for the shift amount on shifted register operands, but it is
10714           // useful in general for any shift amounts.
10715           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10716             break;
10717         }
10718         return;
10719
10720       case 'N':
10721         if (Subtarget->isThumb()) {  // FIXME thumb2
10722           // This must be a constant between 0 and 31, for shift amounts.
10723           if (CVal >= 0 && CVal <= 31)
10724             break;
10725         }
10726         return;
10727
10728       case 'O':
10729         if (Subtarget->isThumb()) {  // FIXME thumb2
10730           // This must be a multiple of 4 between -508 and 508, for
10731           // ADD/SUB sp = sp + immediate.
10732           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10733             break;
10734         }
10735         return;
10736     }
10737     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10738     break;
10739   }
10740
10741   if (Result.getNode()) {
10742     Ops.push_back(Result);
10743     return;
10744   }
10745   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10746 }
10747
10748 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10749   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10750   unsigned Opcode = Op->getOpcode();
10751   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10752          "Invalid opcode for Div/Rem lowering");
10753   bool isSigned = (Opcode == ISD::SDIVREM);
10754   EVT VT = Op->getValueType(0);
10755   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10756
10757   RTLIB::Libcall LC;
10758   switch (VT.getSimpleVT().SimpleTy) {
10759   default: llvm_unreachable("Unexpected request for libcall!");
10760   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10761   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10762   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10763   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10764   }
10765
10766   SDValue InChain = DAG.getEntryNode();
10767
10768   TargetLowering::ArgListTy Args;
10769   TargetLowering::ArgListEntry Entry;
10770   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10771     EVT ArgVT = Op->getOperand(i).getValueType();
10772     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10773     Entry.Node = Op->getOperand(i);
10774     Entry.Ty = ArgTy;
10775     Entry.isSExt = isSigned;
10776     Entry.isZExt = !isSigned;
10777     Args.push_back(Entry);
10778   }
10779
10780   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10781                                          getPointerTy());
10782
10783   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10784
10785   SDLoc dl(Op);
10786   TargetLowering::CallLoweringInfo CLI(DAG);
10787   CLI.setDebugLoc(dl).setChain(InChain)
10788     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10789     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10790
10791   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10792   return CallInfo.first;
10793 }
10794
10795 SDValue
10796 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10797   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10798   SDLoc DL(Op);
10799
10800   // Get the inputs.
10801   SDValue Chain = Op.getOperand(0);
10802   SDValue Size  = Op.getOperand(1);
10803
10804   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10805                               DAG.getConstant(2, MVT::i32));
10806
10807   SDValue Flag;
10808   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10809   Flag = Chain.getValue(1);
10810
10811   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10812   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10813
10814   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10815   Chain = NewSP.getValue(1);
10816
10817   SDValue Ops[2] = { NewSP, Chain };
10818   return DAG.getMergeValues(Ops, DL);
10819 }
10820
10821 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10822   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10823          "Unexpected type for custom-lowering FP_EXTEND");
10824
10825   RTLIB::Libcall LC;
10826   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10827
10828   SDValue SrcVal = Op.getOperand(0);
10829   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10830                      /*isSigned*/ false, SDLoc(Op)).first;
10831 }
10832
10833 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10834   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10835          Subtarget->isFPOnlySP() &&
10836          "Unexpected type for custom-lowering FP_ROUND");
10837
10838   RTLIB::Libcall LC;
10839   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10840
10841   SDValue SrcVal = Op.getOperand(0);
10842   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10843                      /*isSigned*/ false, SDLoc(Op)).first;
10844 }
10845
10846 bool
10847 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10848   // The ARM target isn't yet aware of offsets.
10849   return false;
10850 }
10851
10852 bool ARM::isBitFieldInvertedMask(unsigned v) {
10853   if (v == 0xffffffff)
10854     return false;
10855
10856   // there can be 1's on either or both "outsides", all the "inside"
10857   // bits must be 0's
10858   return isShiftedMask_32(~v);
10859 }
10860
10861 /// isFPImmLegal - Returns true if the target can instruction select the
10862 /// specified FP immediate natively. If false, the legalizer will
10863 /// materialize the FP immediate as a load from a constant pool.
10864 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10865   if (!Subtarget->hasVFP3())
10866     return false;
10867   if (VT == MVT::f32)
10868     return ARM_AM::getFP32Imm(Imm) != -1;
10869   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10870     return ARM_AM::getFP64Imm(Imm) != -1;
10871   return false;
10872 }
10873
10874 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10875 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10876 /// specified in the intrinsic calls.
10877 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10878                                            const CallInst &I,
10879                                            unsigned Intrinsic) const {
10880   switch (Intrinsic) {
10881   case Intrinsic::arm_neon_vld1:
10882   case Intrinsic::arm_neon_vld2:
10883   case Intrinsic::arm_neon_vld3:
10884   case Intrinsic::arm_neon_vld4:
10885   case Intrinsic::arm_neon_vld2lane:
10886   case Intrinsic::arm_neon_vld3lane:
10887   case Intrinsic::arm_neon_vld4lane: {
10888     Info.opc = ISD::INTRINSIC_W_CHAIN;
10889     // Conservatively set memVT to the entire set of vectors loaded.
10890     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10891     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10892     Info.ptrVal = I.getArgOperand(0);
10893     Info.offset = 0;
10894     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10895     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10896     Info.vol = false; // volatile loads with NEON intrinsics not supported
10897     Info.readMem = true;
10898     Info.writeMem = false;
10899     return true;
10900   }
10901   case Intrinsic::arm_neon_vst1:
10902   case Intrinsic::arm_neon_vst2:
10903   case Intrinsic::arm_neon_vst3:
10904   case Intrinsic::arm_neon_vst4:
10905   case Intrinsic::arm_neon_vst2lane:
10906   case Intrinsic::arm_neon_vst3lane:
10907   case Intrinsic::arm_neon_vst4lane: {
10908     Info.opc = ISD::INTRINSIC_VOID;
10909     // Conservatively set memVT to the entire set of vectors stored.
10910     unsigned NumElts = 0;
10911     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10912       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10913       if (!ArgTy->isVectorTy())
10914         break;
10915       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10916     }
10917     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10918     Info.ptrVal = I.getArgOperand(0);
10919     Info.offset = 0;
10920     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10921     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10922     Info.vol = false; // volatile stores with NEON intrinsics not supported
10923     Info.readMem = false;
10924     Info.writeMem = true;
10925     return true;
10926   }
10927   case Intrinsic::arm_ldaex:
10928   case Intrinsic::arm_ldrex: {
10929     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10930     Info.opc = ISD::INTRINSIC_W_CHAIN;
10931     Info.memVT = MVT::getVT(PtrTy->getElementType());
10932     Info.ptrVal = I.getArgOperand(0);
10933     Info.offset = 0;
10934     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10935     Info.vol = true;
10936     Info.readMem = true;
10937     Info.writeMem = false;
10938     return true;
10939   }
10940   case Intrinsic::arm_stlex:
10941   case Intrinsic::arm_strex: {
10942     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10943     Info.opc = ISD::INTRINSIC_W_CHAIN;
10944     Info.memVT = MVT::getVT(PtrTy->getElementType());
10945     Info.ptrVal = I.getArgOperand(1);
10946     Info.offset = 0;
10947     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10948     Info.vol = true;
10949     Info.readMem = false;
10950     Info.writeMem = true;
10951     return true;
10952   }
10953   case Intrinsic::arm_stlexd:
10954   case Intrinsic::arm_strexd: {
10955     Info.opc = ISD::INTRINSIC_W_CHAIN;
10956     Info.memVT = MVT::i64;
10957     Info.ptrVal = I.getArgOperand(2);
10958     Info.offset = 0;
10959     Info.align = 8;
10960     Info.vol = true;
10961     Info.readMem = false;
10962     Info.writeMem = true;
10963     return true;
10964   }
10965   case Intrinsic::arm_ldaexd:
10966   case Intrinsic::arm_ldrexd: {
10967     Info.opc = ISD::INTRINSIC_W_CHAIN;
10968     Info.memVT = MVT::i64;
10969     Info.ptrVal = I.getArgOperand(0);
10970     Info.offset = 0;
10971     Info.align = 8;
10972     Info.vol = true;
10973     Info.readMem = true;
10974     Info.writeMem = false;
10975     return true;
10976   }
10977   default:
10978     break;
10979   }
10980
10981   return false;
10982 }
10983
10984 /// \brief Returns true if it is beneficial to convert a load of a constant
10985 /// to just the constant itself.
10986 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10987                                                           Type *Ty) const {
10988   assert(Ty->isIntegerTy());
10989
10990   unsigned Bits = Ty->getPrimitiveSizeInBits();
10991   if (Bits == 0 || Bits > 32)
10992     return false;
10993   return true;
10994 }
10995
10996 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
10997
10998 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
10999                                         ARM_MB::MemBOpt Domain) const {
11000   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11001
11002   // First, if the target has no DMB, see what fallback we can use.
11003   if (!Subtarget->hasDataBarrier()) {
11004     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11005     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11006     // here.
11007     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11008       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11009       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11010                         Builder.getInt32(0), Builder.getInt32(7),
11011                         Builder.getInt32(10), Builder.getInt32(5)};
11012       return Builder.CreateCall(MCR, args);
11013     } else {
11014       // Instead of using barriers, atomic accesses on these subtargets use
11015       // libcalls.
11016       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11017     }
11018   } else {
11019     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11020     // Only a full system barrier exists in the M-class architectures.
11021     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11022     Constant *CDomain = Builder.getInt32(Domain);
11023     return Builder.CreateCall(DMB, CDomain);
11024   }
11025 }
11026
11027 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11028 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11029                                          AtomicOrdering Ord, bool IsStore,
11030                                          bool IsLoad) const {
11031   if (!getInsertFencesForAtomic())
11032     return nullptr;
11033
11034   switch (Ord) {
11035   case NotAtomic:
11036   case Unordered:
11037     llvm_unreachable("Invalid fence: unordered/non-atomic");
11038   case Monotonic:
11039   case Acquire:
11040     return nullptr; // Nothing to do
11041   case SequentiallyConsistent:
11042     if (!IsStore)
11043       return nullptr; // Nothing to do
11044     /*FALLTHROUGH*/
11045   case Release:
11046   case AcquireRelease:
11047     if (Subtarget->isSwift())
11048       return makeDMB(Builder, ARM_MB::ISHST);
11049     // FIXME: add a comment with a link to documentation justifying this.
11050     else
11051       return makeDMB(Builder, ARM_MB::ISH);
11052   }
11053   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11054 }
11055
11056 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11057                                           AtomicOrdering Ord, bool IsStore,
11058                                           bool IsLoad) const {
11059   if (!getInsertFencesForAtomic())
11060     return nullptr;
11061
11062   switch (Ord) {
11063   case NotAtomic:
11064   case Unordered:
11065     llvm_unreachable("Invalid fence: unordered/not-atomic");
11066   case Monotonic:
11067   case Release:
11068     return nullptr; // Nothing to do
11069   case Acquire:
11070   case AcquireRelease:
11071   case SequentiallyConsistent:
11072     return makeDMB(Builder, ARM_MB::ISH);
11073   }
11074   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11075 }
11076
11077 // Loads and stores less than 64-bits are already atomic; ones above that
11078 // are doomed anyway, so defer to the default libcall and blame the OS when
11079 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11080 // anything for those.
11081 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11082   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11083   return (Size == 64) && !Subtarget->isMClass();
11084 }
11085
11086 // Loads and stores less than 64-bits are already atomic; ones above that
11087 // are doomed anyway, so defer to the default libcall and blame the OS when
11088 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11089 // anything for those.
11090 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11091 // guarantee, see DDI0406C ARM architecture reference manual,
11092 // sections A8.8.72-74 LDRD)
11093 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11094   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11095   return (Size == 64) && !Subtarget->isMClass();
11096 }
11097
11098 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11099 // and up to 64 bits on the non-M profiles
11100 TargetLoweringBase::AtomicRMWExpansionKind
11101 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11102   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11103   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11104              ? AtomicRMWExpansionKind::LLSC
11105              : AtomicRMWExpansionKind::None;
11106 }
11107
11108 // This has so far only been implemented for MachO.
11109 bool ARMTargetLowering::useLoadStackGuardNode() const {
11110   return Subtarget->isTargetMachO();
11111 }
11112
11113 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11114                                                   unsigned &Cost) const {
11115   // If we do not have NEON, vector types are not natively supported.
11116   if (!Subtarget->hasNEON())
11117     return false;
11118
11119   // Floating point values and vector values map to the same register file.
11120   // Therefore, althought we could do a store extract of a vector type, this is
11121   // better to leave at float as we have more freedom in the addressing mode for
11122   // those.
11123   if (VectorTy->isFPOrFPVectorTy())
11124     return false;
11125
11126   // If the index is unknown at compile time, this is very expensive to lower
11127   // and it is not possible to combine the store with the extract.
11128   if (!isa<ConstantInt>(Idx))
11129     return false;
11130
11131   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11132   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11133   // We can do a store + vector extract on any vector that fits perfectly in a D
11134   // or Q register.
11135   if (BitWidth == 64 || BitWidth == 128) {
11136     Cost = 0;
11137     return true;
11138   }
11139   return false;
11140 }
11141
11142 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11143                                          AtomicOrdering Ord) const {
11144   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11145   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11146   bool IsAcquire = isAtLeastAcquire(Ord);
11147
11148   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11149   // intrinsic must return {i32, i32} and we have to recombine them into a
11150   // single i64 here.
11151   if (ValTy->getPrimitiveSizeInBits() == 64) {
11152     Intrinsic::ID Int =
11153         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11154     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11155
11156     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11157     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11158
11159     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11160     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11161     if (!Subtarget->isLittle())
11162       std::swap (Lo, Hi);
11163     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11164     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11165     return Builder.CreateOr(
11166         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11167   }
11168
11169   Type *Tys[] = { Addr->getType() };
11170   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11171   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11172
11173   return Builder.CreateTruncOrBitCast(
11174       Builder.CreateCall(Ldrex, Addr),
11175       cast<PointerType>(Addr->getType())->getElementType());
11176 }
11177
11178 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11179                                                Value *Addr,
11180                                                AtomicOrdering Ord) const {
11181   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11182   bool IsRelease = isAtLeastRelease(Ord);
11183
11184   // Since the intrinsics must have legal type, the i64 intrinsics take two
11185   // parameters: "i32, i32". We must marshal Val into the appropriate form
11186   // before the call.
11187   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11188     Intrinsic::ID Int =
11189         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11190     Function *Strex = Intrinsic::getDeclaration(M, Int);
11191     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11192
11193     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11194     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11195     if (!Subtarget->isLittle())
11196       std::swap (Lo, Hi);
11197     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11198     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11199   }
11200
11201   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11202   Type *Tys[] = { Addr->getType() };
11203   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11204
11205   return Builder.CreateCall2(
11206       Strex, Builder.CreateZExtOrBitCast(
11207                  Val, Strex->getFunctionType()->getParamType(0)),
11208       Addr);
11209 }
11210
11211 enum HABaseType {
11212   HA_UNKNOWN = 0,
11213   HA_FLOAT,
11214   HA_DOUBLE,
11215   HA_VECT64,
11216   HA_VECT128
11217 };
11218
11219 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11220                                    uint64_t &Members) {
11221   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11222     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11223       uint64_t SubMembers = 0;
11224       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11225         return false;
11226       Members += SubMembers;
11227     }
11228   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11229     uint64_t SubMembers = 0;
11230     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11231       return false;
11232     Members += SubMembers * AT->getNumElements();
11233   } else if (Ty->isFloatTy()) {
11234     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11235       return false;
11236     Members = 1;
11237     Base = HA_FLOAT;
11238   } else if (Ty->isDoubleTy()) {
11239     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11240       return false;
11241     Members = 1;
11242     Base = HA_DOUBLE;
11243   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11244     Members = 1;
11245     switch (Base) {
11246     case HA_FLOAT:
11247     case HA_DOUBLE:
11248       return false;
11249     case HA_VECT64:
11250       return VT->getBitWidth() == 64;
11251     case HA_VECT128:
11252       return VT->getBitWidth() == 128;
11253     case HA_UNKNOWN:
11254       switch (VT->getBitWidth()) {
11255       case 64:
11256         Base = HA_VECT64;
11257         return true;
11258       case 128:
11259         Base = HA_VECT128;
11260         return true;
11261       default:
11262         return false;
11263       }
11264     }
11265   }
11266
11267   return (Members > 0 && Members <= 4);
11268 }
11269
11270 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11271 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11272 /// passing according to AAPCS rules.
11273 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11274     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11275   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11276       CallingConv::ARM_AAPCS_VFP)
11277     return false;
11278
11279   HABaseType Base = HA_UNKNOWN;
11280   uint64_t Members = 0;
11281   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11282   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11283
11284   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11285   return IsHA || IsIntArray;
11286 }