[ARM] Align stack objects passed to memory intrinsics
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/IR/IntrinsicInst.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/Target/TargetOptions.h"
53 #include <utility>
54 using namespace llvm;
55
56 #define DEBUG_TYPE "arm-isel"
57
58 STATISTIC(NumTailCalls, "Number of tail calls");
59 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
60 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
61
62 cl::opt<bool>
63 EnableARMLongCalls("arm-long-calls", cl::Hidden,
64   cl::desc("Generate calls via indirect call instructions"),
65   cl::init(false));
66
67 static cl::opt<bool>
68 ARMInterworking("arm-interworking", cl::Hidden,
69   cl::desc("Enable / disable ARM interworking (for debugging only)"),
70   cl::init(true));
71
72 namespace {
73   class ARMCCState : public CCState {
74   public:
75     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
76                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
77                ParmContext PC)
78         : CCState(CC, isVarArg, MF, locs, C) {
79       assert(((PC == Call) || (PC == Prologue)) &&
80              "ARMCCState users must specify whether their context is call"
81              "or prologue generation.");
82       CallOrPrologue = PC;
83     }
84   };
85 }
86
87 // The APCS parameter registers.
88 static const MCPhysReg GPRArgRegs[] = {
89   ARM::R0, ARM::R1, ARM::R2, ARM::R3
90 };
91
92 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
93                                        MVT PromotedBitwiseVT) {
94   if (VT != PromotedLdStVT) {
95     setOperationAction(ISD::LOAD, VT, Promote);
96     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
97
98     setOperationAction(ISD::STORE, VT, Promote);
99     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
100   }
101
102   MVT ElemTy = VT.getVectorElementType();
103   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
104     setOperationAction(ISD::SETCC, VT, Custom);
105   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
106   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
107   if (ElemTy == MVT::i32) {
108     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
109     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
110     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
111     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
112   } else {
113     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
114     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
115     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
116     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
117   }
118   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
119   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
120   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
121   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
122   setOperationAction(ISD::SELECT,            VT, Expand);
123   setOperationAction(ISD::SELECT_CC,         VT, Expand);
124   setOperationAction(ISD::VSELECT,           VT, Expand);
125   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
126   if (VT.isInteger()) {
127     setOperationAction(ISD::SHL, VT, Custom);
128     setOperationAction(ISD::SRA, VT, Custom);
129     setOperationAction(ISD::SRL, VT, Custom);
130   }
131
132   // Promote all bit-wise operations.
133   if (VT.isInteger() && VT != PromotedBitwiseVT) {
134     setOperationAction(ISD::AND, VT, Promote);
135     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
136     setOperationAction(ISD::OR,  VT, Promote);
137     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
138     setOperationAction(ISD::XOR, VT, Promote);
139     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
140   }
141
142   // Neon does not support vector divide/remainder operations.
143   setOperationAction(ISD::SDIV, VT, Expand);
144   setOperationAction(ISD::UDIV, VT, Expand);
145   setOperationAction(ISD::FDIV, VT, Expand);
146   setOperationAction(ISD::SREM, VT, Expand);
147   setOperationAction(ISD::UREM, VT, Expand);
148   setOperationAction(ISD::FREM, VT, Expand);
149 }
150
151 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
152   addRegisterClass(VT, &ARM::DPRRegClass);
153   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
154 }
155
156 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
157   addRegisterClass(VT, &ARM::DPairRegClass);
158   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
159 }
160
161 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
162                                      const ARMSubtarget &STI)
163     : TargetLowering(TM), Subtarget(&STI) {
164   RegInfo = Subtarget->getRegisterInfo();
165   Itins = Subtarget->getInstrItineraryData();
166
167   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
168
169   if (Subtarget->isTargetMachO()) {
170     // Uses VFP for Thumb libfuncs if available.
171     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
172         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
173       // Single-precision floating-point arithmetic.
174       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
175       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
176       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
177       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
178
179       // Double-precision floating-point arithmetic.
180       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
181       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
182       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
183       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
184
185       // Single-precision comparisons.
186       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
187       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
188       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
189       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
190       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
191       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
192       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
193       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
194
195       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
196       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
197       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
198       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
199       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
200       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
202       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
203
204       // Double-precision comparisons.
205       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
206       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
207       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
208       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
209       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
210       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
211       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
212       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
213
214       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
215       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
216       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
217       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
218       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
219       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
221       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
222
223       // Floating-point to integer conversions.
224       // i64 conversions are done via library routines even when generating VFP
225       // instructions, so use the same ones.
226       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
227       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
228       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
229       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
230
231       // Conversions between floating types.
232       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
233       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
234
235       // Integer to floating-point conversions.
236       // i64 conversions are done via library routines even when generating VFP
237       // instructions, so use the same ones.
238       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
239       // e.g., __floatunsidf vs. __floatunssidfvfp.
240       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
241       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
242       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
243       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
244     }
245   }
246
247   // These libcalls are not available in 32-bit.
248   setLibcallName(RTLIB::SHL_I128, nullptr);
249   setLibcallName(RTLIB::SRL_I128, nullptr);
250   setLibcallName(RTLIB::SRA_I128, nullptr);
251
252   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
253       !Subtarget->isTargetWindows()) {
254     static const struct {
255       const RTLIB::Libcall Op;
256       const char * const Name;
257       const CallingConv::ID CC;
258       const ISD::CondCode Cond;
259     } LibraryCalls[] = {
260       // Double-precision floating-point arithmetic helper functions
261       // RTABI chapter 4.1.2, Table 2
262       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
263       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
266
267       // Double-precision floating-point comparison helper functions
268       // RTABI chapter 4.1.2, Table 3
269       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
270       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
271       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
272       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
273       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
274       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
276       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
277
278       // Single-precision floating-point arithmetic helper functions
279       // RTABI chapter 4.1.2, Table 4
280       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
281       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
284
285       // Single-precision floating-point comparison helper functions
286       // RTABI chapter 4.1.2, Table 5
287       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
288       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
289       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
290       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
291       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
292       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
294       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
295
296       // Floating-point to integer conversions.
297       // RTABI chapter 4.1.2, Table 6
298       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306
307       // Conversions between floating types.
308       // RTABI chapter 4.1.2, Table 7
309       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312
313       // Integer to floating-point conversions.
314       // RTABI chapter 4.1.2, Table 8
315       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323
324       // Long long helper functions
325       // RTABI chapter 4.2, Table 9
326       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330
331       // Integer division functions
332       // RTABI chapter 4.3.1
333       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341
342       // Memory operations
343       // RTABI chapter 4.3.4
344       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347     };
348
349     for (const auto &LC : LibraryCalls) {
350       setLibcallName(LC.Op, LC.Name);
351       setLibcallCallingConv(LC.Op, LC.CC);
352       if (LC.Cond != ISD::SETCC_INVALID)
353         setCmpLibcallCC(LC.Op, LC.Cond);
354     }
355   }
356
357   if (Subtarget->isTargetWindows()) {
358     static const struct {
359       const RTLIB::Libcall Op;
360       const char * const Name;
361       const CallingConv::ID CC;
362     } LibraryCalls[] = {
363       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
364       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
366       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
367       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
371     };
372
373     for (const auto &LC : LibraryCalls) {
374       setLibcallName(LC.Op, LC.Name);
375       setLibcallCallingConv(LC.Op, LC.CC);
376     }
377   }
378
379   // Use divmod compiler-rt calls for iOS 5.0 and later.
380   if (Subtarget->getTargetTriple().isiOS() &&
381       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
382     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
383     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
384   }
385
386   // The half <-> float conversion functions are always soft-float, but are
387   // needed for some targets which use a hard-float calling convention by
388   // default.
389   if (Subtarget->isAAPCS_ABI()) {
390     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
393   } else {
394     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
395     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
396     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
397   }
398
399   if (Subtarget->isThumb1Only())
400     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
401   else
402     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
403   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
404       !Subtarget->isThumb1Only()) {
405     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
406     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
407   }
408
409   for (MVT VT : MVT::vector_valuetypes()) {
410     for (MVT InnerVT : MVT::vector_valuetypes()) {
411       setTruncStoreAction(VT, InnerVT, Expand);
412       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
413       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
414       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
415     }
416
417     setOperationAction(ISD::MULHS, VT, Expand);
418     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
419     setOperationAction(ISD::MULHU, VT, Expand);
420     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
421
422     setOperationAction(ISD::BSWAP, VT, Expand);
423   }
424
425   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
426   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
427
428   if (Subtarget->hasNEON()) {
429     addDRTypeForNEON(MVT::v2f32);
430     addDRTypeForNEON(MVT::v8i8);
431     addDRTypeForNEON(MVT::v4i16);
432     addDRTypeForNEON(MVT::v2i32);
433     addDRTypeForNEON(MVT::v1i64);
434
435     addQRTypeForNEON(MVT::v4f32);
436     addQRTypeForNEON(MVT::v2f64);
437     addQRTypeForNEON(MVT::v16i8);
438     addQRTypeForNEON(MVT::v8i16);
439     addQRTypeForNEON(MVT::v4i32);
440     addQRTypeForNEON(MVT::v2i64);
441
442     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
443     // neither Neon nor VFP support any arithmetic operations on it.
444     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
445     // supported for v4f32.
446     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
447     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
448     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
449     // FIXME: Code duplication: FDIV and FREM are expanded always, see
450     // ARMTargetLowering::addTypeForNEON method for details.
451     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
452     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
453     // FIXME: Create unittest.
454     // In another words, find a way when "copysign" appears in DAG with vector
455     // operands.
456     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
457     // FIXME: Code duplication: SETCC has custom operation action, see
458     // ARMTargetLowering::addTypeForNEON method for details.
459     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
460     // FIXME: Create unittest for FNEG and for FABS.
461     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
462     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
463     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
464     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
465     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
466     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
467     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
468     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
469     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
470     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
471     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
472     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
473     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
474     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
475     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
476     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
477     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
478     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
479     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
480
481     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
482     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
483     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
484     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
485     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
486     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
487     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
488     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
489     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
490     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
491     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
492     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
493     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
494     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
495     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
496
497     // Mark v2f32 intrinsics.
498     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
499     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
500     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
501     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
502     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
503     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
504     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
505     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
506     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
507     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
508     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
509     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
510     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
511     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
512     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
513
514     // Neon does not support some operations on v1i64 and v2i64 types.
515     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
516     // Custom handling for some quad-vector types to detect VMULL.
517     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
518     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
519     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
520     // Custom handling for some vector types to avoid expensive expansions
521     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
522     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
523     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
524     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
525     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
526     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
527     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
528     // a destination type that is wider than the source, and nor does
529     // it have a FP_TO_[SU]INT instruction with a narrower destination than
530     // source.
531     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
532     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
533     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
534     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
535
536     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
537     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
538
539     // NEON does not have single instruction CTPOP for vectors with element
540     // types wider than 8-bits.  However, custom lowering can leverage the
541     // v8i8/v16i8 vcnt instruction.
542     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
543     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
544     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
545     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
546
547     // NEON only has FMA instructions as of VFP4.
548     if (!Subtarget->hasVFP4()) {
549       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
550       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
551     }
552
553     setTargetDAGCombine(ISD::INTRINSIC_VOID);
554     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
555     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
556     setTargetDAGCombine(ISD::SHL);
557     setTargetDAGCombine(ISD::SRL);
558     setTargetDAGCombine(ISD::SRA);
559     setTargetDAGCombine(ISD::SIGN_EXTEND);
560     setTargetDAGCombine(ISD::ZERO_EXTEND);
561     setTargetDAGCombine(ISD::ANY_EXTEND);
562     setTargetDAGCombine(ISD::SELECT_CC);
563     setTargetDAGCombine(ISD::BUILD_VECTOR);
564     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
565     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
566     setTargetDAGCombine(ISD::STORE);
567     setTargetDAGCombine(ISD::FP_TO_SINT);
568     setTargetDAGCombine(ISD::FP_TO_UINT);
569     setTargetDAGCombine(ISD::FDIV);
570     setTargetDAGCombine(ISD::LOAD);
571
572     // It is legal to extload from v4i8 to v4i16 or v4i32.
573     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
574                    MVT::v2i32}) {
575       for (MVT VT : MVT::integer_vector_valuetypes()) {
576         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
577         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
578         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
579       }
580     }
581   }
582
583   // ARM and Thumb2 support UMLAL/SMLAL.
584   if (!Subtarget->isThumb1Only())
585     setTargetDAGCombine(ISD::ADDC);
586
587   if (Subtarget->isFPOnlySP()) {
588     // When targetting a floating-point unit with only single-precision
589     // operations, f64 is legal for the few double-precision instructions which
590     // are present However, no double-precision operations other than moves,
591     // loads and stores are provided by the hardware.
592     setOperationAction(ISD::FADD,       MVT::f64, Expand);
593     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
594     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
595     setOperationAction(ISD::FMA,        MVT::f64, Expand);
596     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
597     setOperationAction(ISD::FREM,       MVT::f64, Expand);
598     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
599     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
600     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
601     setOperationAction(ISD::FABS,       MVT::f64, Expand);
602     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
603     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
604     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
605     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
606     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
607     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
608     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
609     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
610     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
611     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
612     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
613     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
614     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
615     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
616     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
617     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
618     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
619   }
620
621   computeRegisterProperties(Subtarget->getRegisterInfo());
622
623   // ARM does not have floating-point extending loads.
624   for (MVT VT : MVT::fp_valuetypes()) {
625     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
626     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
627   }
628
629   // ... or truncating stores
630   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
631   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
632   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
633
634   // ARM does not have i1 sign extending load.
635   for (MVT VT : MVT::integer_valuetypes())
636     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
637
638   // ARM supports all 4 flavors of integer indexed load / store.
639   if (!Subtarget->isThumb1Only()) {
640     for (unsigned im = (unsigned)ISD::PRE_INC;
641          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
642       setIndexedLoadAction(im,  MVT::i1,  Legal);
643       setIndexedLoadAction(im,  MVT::i8,  Legal);
644       setIndexedLoadAction(im,  MVT::i16, Legal);
645       setIndexedLoadAction(im,  MVT::i32, Legal);
646       setIndexedStoreAction(im, MVT::i1,  Legal);
647       setIndexedStoreAction(im, MVT::i8,  Legal);
648       setIndexedStoreAction(im, MVT::i16, Legal);
649       setIndexedStoreAction(im, MVT::i32, Legal);
650     }
651   }
652
653   setOperationAction(ISD::SADDO, MVT::i32, Custom);
654   setOperationAction(ISD::UADDO, MVT::i32, Custom);
655   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
656   setOperationAction(ISD::USUBO, MVT::i32, Custom);
657
658   // i64 operation support.
659   setOperationAction(ISD::MUL,     MVT::i64, Expand);
660   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
661   if (Subtarget->isThumb1Only()) {
662     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
663     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
664   }
665   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
666       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
667     setOperationAction(ISD::MULHS, MVT::i32, Expand);
668
669   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
670   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
671   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
672   setOperationAction(ISD::SRL,       MVT::i64, Custom);
673   setOperationAction(ISD::SRA,       MVT::i64, Custom);
674
675   if (!Subtarget->isThumb1Only()) {
676     // FIXME: We should do this for Thumb1 as well.
677     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
678     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
679     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
680     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
681   }
682
683   // ARM does not have ROTL.
684   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
685   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
686   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
687   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
688     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
689
690   // These just redirect to CTTZ and CTLZ on ARM.
691   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
692   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
693
694   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
695
696   // Only ARMv6 has BSWAP.
697   if (!Subtarget->hasV6Ops())
698     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
699
700   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
701       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
702     // These are expanded into libcalls if the cpu doesn't have HW divider.
703     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
704     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
705   }
706
707   // FIXME: Also set divmod for SREM on EABI
708   setOperationAction(ISD::SREM,  MVT::i32, Expand);
709   setOperationAction(ISD::UREM,  MVT::i32, Expand);
710   // Register based DivRem for AEABI (RTABI 4.2)
711   if (Subtarget->isTargetAEABI()) {
712     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
713     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
714     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
715     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
716     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
717     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
718     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
719     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
720
721     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
722     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
723     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
724     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
725     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
726     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
727     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
728     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
729
730     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
731     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
732   } else {
733     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
734     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
735   }
736
737   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
738   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
739   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
740   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
741   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
742
743   setOperationAction(ISD::TRAP, MVT::Other, Legal);
744
745   // Use the default implementation.
746   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
747   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
748   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
749   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
750   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
751   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
752
753   if (!Subtarget->isTargetMachO()) {
754     // Non-MachO platforms may return values in these registers via the
755     // personality function.
756     setExceptionPointerRegister(ARM::R0);
757     setExceptionSelectorRegister(ARM::R1);
758   }
759
760   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
761     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
762   else
763     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
764
765   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
766   // the default expansion. If we are targeting a single threaded system,
767   // then set them all for expand so we can lower them later into their
768   // non-atomic form.
769   if (TM.Options.ThreadModel == ThreadModel::Single)
770     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
771   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
772     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
773     // to ldrex/strex loops already.
774     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
775
776     // On v8, we have particularly efficient implementations of atomic fences
777     // if they can be combined with nearby atomic loads and stores.
778     if (!Subtarget->hasV8Ops()) {
779       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
780       setInsertFencesForAtomic(true);
781     }
782   } else {
783     // If there's anything we can use as a barrier, go through custom lowering
784     // for ATOMIC_FENCE.
785     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
786                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
787
788     // Set them all for expansion, which will force libcalls.
789     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
790     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
791     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
792     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
793     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
794     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
795     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
796     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
801     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
802     // Unordered/Monotonic case.
803     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
804     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
805   }
806
807   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
808
809   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
810   if (!Subtarget->hasV6Ops()) {
811     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
812     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
813   }
814   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
815
816   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
817       !Subtarget->isThumb1Only()) {
818     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
819     // iff target supports vfp2.
820     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
821     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
822   }
823
824   // We want to custom lower some of our intrinsics.
825   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
826   if (Subtarget->isTargetDarwin()) {
827     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
828     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
829     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
830   }
831
832   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
833   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
834   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
835   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
836   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
837   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
838   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
839   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
840   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
841
842   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
843   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
844   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
845   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
846   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
847
848   // We don't support sin/cos/fmod/copysign/pow
849   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
850   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
851   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
852   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
853   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
854   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
855   setOperationAction(ISD::FREM,      MVT::f64, Expand);
856   setOperationAction(ISD::FREM,      MVT::f32, Expand);
857   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
858       !Subtarget->isThumb1Only()) {
859     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
860     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
861   }
862   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
863   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
864
865   if (!Subtarget->hasVFP4()) {
866     setOperationAction(ISD::FMA, MVT::f64, Expand);
867     setOperationAction(ISD::FMA, MVT::f32, Expand);
868   }
869
870   // Various VFP goodness
871   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
872     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
873     if (Subtarget->hasVFP2()) {
874       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
875       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
876       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
877       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
878     }
879
880     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
881     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
882       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
883       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
884     }
885
886     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
887     if (!Subtarget->hasFP16()) {
888       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
889       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
890     }
891   }
892
893   // Combine sin / cos into one node or libcall if possible.
894   if (Subtarget->hasSinCos()) {
895     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
896     setLibcallName(RTLIB::SINCOS_F64, "sincos");
897     if (Subtarget->getTargetTriple().isiOS()) {
898       // For iOS, we don't want to the normal expansion of a libcall to
899       // sincos. We want to issue a libcall to __sincos_stret.
900       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
901       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
902     }
903   }
904
905   // FP-ARMv8 implements a lot of rounding-like FP operations.
906   if (Subtarget->hasFPARMv8()) {
907     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
908     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
909     setOperationAction(ISD::FROUND, MVT::f32, Legal);
910     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
911     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
912     setOperationAction(ISD::FRINT, MVT::f32, Legal);
913     if (!Subtarget->isFPOnlySP()) {
914       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
915       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
916       setOperationAction(ISD::FROUND, MVT::f64, Legal);
917       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
918       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
919       setOperationAction(ISD::FRINT, MVT::f64, Legal);
920     }
921   }
922   // We have target-specific dag combine patterns for the following nodes:
923   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
924   setTargetDAGCombine(ISD::ADD);
925   setTargetDAGCombine(ISD::SUB);
926   setTargetDAGCombine(ISD::MUL);
927   setTargetDAGCombine(ISD::AND);
928   setTargetDAGCombine(ISD::OR);
929   setTargetDAGCombine(ISD::XOR);
930
931   if (Subtarget->hasV6Ops())
932     setTargetDAGCombine(ISD::SRL);
933
934   setStackPointerRegisterToSaveRestore(ARM::SP);
935
936   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
937       !Subtarget->hasVFP2())
938     setSchedulingPreference(Sched::RegPressure);
939   else
940     setSchedulingPreference(Sched::Hybrid);
941
942   //// temporary - rewrite interface to use type
943   MaxStoresPerMemset = 8;
944   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
945   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
946   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
947   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
948   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
949
950   // On ARM arguments smaller than 4 bytes are extended, so all arguments
951   // are at least 4 bytes aligned.
952   setMinStackArgumentAlignment(4);
953
954   // Prefer likely predicted branches to selects on out-of-order cores.
955   PredictableSelectIsExpensive = Subtarget->isLikeA9();
956
957   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
958 }
959
960 // FIXME: It might make sense to define the representative register class as the
961 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
962 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
963 // SPR's representative would be DPR_VFP2. This should work well if register
964 // pressure tracking were modified such that a register use would increment the
965 // pressure of the register class's representative and all of it's super
966 // classes' representatives transitively. We have not implemented this because
967 // of the difficulty prior to coalescing of modeling operand register classes
968 // due to the common occurrence of cross class copies and subregister insertions
969 // and extractions.
970 std::pair<const TargetRegisterClass *, uint8_t>
971 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
972                                            MVT VT) const {
973   const TargetRegisterClass *RRC = nullptr;
974   uint8_t Cost = 1;
975   switch (VT.SimpleTy) {
976   default:
977     return TargetLowering::findRepresentativeClass(TRI, VT);
978   // Use DPR as representative register class for all floating point
979   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
980   // the cost is 1 for both f32 and f64.
981   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
982   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
983     RRC = &ARM::DPRRegClass;
984     // When NEON is used for SP, only half of the register file is available
985     // because operations that define both SP and DP results will be constrained
986     // to the VFP2 class (D0-D15). We currently model this constraint prior to
987     // coalescing by double-counting the SP regs. See the FIXME above.
988     if (Subtarget->useNEONForSinglePrecisionFP())
989       Cost = 2;
990     break;
991   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
992   case MVT::v4f32: case MVT::v2f64:
993     RRC = &ARM::DPRRegClass;
994     Cost = 2;
995     break;
996   case MVT::v4i64:
997     RRC = &ARM::DPRRegClass;
998     Cost = 4;
999     break;
1000   case MVT::v8i64:
1001     RRC = &ARM::DPRRegClass;
1002     Cost = 8;
1003     break;
1004   }
1005   return std::make_pair(RRC, Cost);
1006 }
1007
1008 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1009   switch (Opcode) {
1010   default: return nullptr;
1011   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1012   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1013   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1014   case ARMISD::CALL:          return "ARMISD::CALL";
1015   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1016   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1017   case ARMISD::tCALL:         return "ARMISD::tCALL";
1018   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1019   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1020   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1021   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1022   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1023   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1024   case ARMISD::CMP:           return "ARMISD::CMP";
1025   case ARMISD::CMN:           return "ARMISD::CMN";
1026   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1027   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1028   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1029   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1030   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1031
1032   case ARMISD::CMOV:          return "ARMISD::CMOV";
1033
1034   case ARMISD::RBIT:          return "ARMISD::RBIT";
1035
1036   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1037   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1038   case ARMISD::SITOF:         return "ARMISD::SITOF";
1039   case ARMISD::UITOF:         return "ARMISD::UITOF";
1040
1041   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1042   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1043   case ARMISD::RRX:           return "ARMISD::RRX";
1044
1045   case ARMISD::ADDC:          return "ARMISD::ADDC";
1046   case ARMISD::ADDE:          return "ARMISD::ADDE";
1047   case ARMISD::SUBC:          return "ARMISD::SUBC";
1048   case ARMISD::SUBE:          return "ARMISD::SUBE";
1049
1050   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1051   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1052
1053   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1054   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1055
1056   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1057
1058   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1059
1060   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1061
1062   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1063
1064   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1065
1066   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1067
1068   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1069   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1070   case ARMISD::VCGE:          return "ARMISD::VCGE";
1071   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1072   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1073   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1074   case ARMISD::VCGT:          return "ARMISD::VCGT";
1075   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1076   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1077   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1078   case ARMISD::VTST:          return "ARMISD::VTST";
1079
1080   case ARMISD::VSHL:          return "ARMISD::VSHL";
1081   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1082   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1083   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1084   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1085   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1086   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1087   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1088   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1089   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1090   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1091   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1092   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1093   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1094   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1095   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1096   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1097   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1098   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1099   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1100   case ARMISD::VDUP:          return "ARMISD::VDUP";
1101   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1102   case ARMISD::VEXT:          return "ARMISD::VEXT";
1103   case ARMISD::VREV64:        return "ARMISD::VREV64";
1104   case ARMISD::VREV32:        return "ARMISD::VREV32";
1105   case ARMISD::VREV16:        return "ARMISD::VREV16";
1106   case ARMISD::VZIP:          return "ARMISD::VZIP";
1107   case ARMISD::VUZP:          return "ARMISD::VUZP";
1108   case ARMISD::VTRN:          return "ARMISD::VTRN";
1109   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1110   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1111   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1112   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1113   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1114   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1115   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1116   case ARMISD::FMAX:          return "ARMISD::FMAX";
1117   case ARMISD::FMIN:          return "ARMISD::FMIN";
1118   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1119   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1120   case ARMISD::BFI:           return "ARMISD::BFI";
1121   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1122   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1123   case ARMISD::VBSL:          return "ARMISD::VBSL";
1124   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1125   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1126   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1127   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1128   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1129   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1130   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1131   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1132   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1133   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1134   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1135   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1136   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1137   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1138   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1139   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1140   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1141   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1142   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1143   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1144   }
1145 }
1146
1147 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1148   if (!VT.isVector()) return getPointerTy();
1149   return VT.changeVectorElementTypeToInteger();
1150 }
1151
1152 /// getRegClassFor - Return the register class that should be used for the
1153 /// specified value type.
1154 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1155   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1156   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1157   // load / store 4 to 8 consecutive D registers.
1158   if (Subtarget->hasNEON()) {
1159     if (VT == MVT::v4i64)
1160       return &ARM::QQPRRegClass;
1161     if (VT == MVT::v8i64)
1162       return &ARM::QQQQPRRegClass;
1163   }
1164   return TargetLowering::getRegClassFor(VT);
1165 }
1166
1167 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1168 // source/dest is aligned and the copy size is large enough. We therefore want
1169 // to align such objects passed to memory intrinsics.
1170 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1171                                                unsigned &PrefAlign) const {
1172   if (!isa<MemIntrinsic>(CI))
1173     return false;
1174   MinSize = 8;
1175   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1176   // cycle faster than 4-byte aligned LDM.
1177   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1178   return true;
1179 }
1180
1181 // Create a fast isel object.
1182 FastISel *
1183 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1184                                   const TargetLibraryInfo *libInfo) const {
1185   return ARM::createFastISel(funcInfo, libInfo);
1186 }
1187
1188 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1189   unsigned NumVals = N->getNumValues();
1190   if (!NumVals)
1191     return Sched::RegPressure;
1192
1193   for (unsigned i = 0; i != NumVals; ++i) {
1194     EVT VT = N->getValueType(i);
1195     if (VT == MVT::Glue || VT == MVT::Other)
1196       continue;
1197     if (VT.isFloatingPoint() || VT.isVector())
1198       return Sched::ILP;
1199   }
1200
1201   if (!N->isMachineOpcode())
1202     return Sched::RegPressure;
1203
1204   // Load are scheduled for latency even if there instruction itinerary
1205   // is not available.
1206   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1207   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1208
1209   if (MCID.getNumDefs() == 0)
1210     return Sched::RegPressure;
1211   if (!Itins->isEmpty() &&
1212       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1213     return Sched::ILP;
1214
1215   return Sched::RegPressure;
1216 }
1217
1218 //===----------------------------------------------------------------------===//
1219 // Lowering Code
1220 //===----------------------------------------------------------------------===//
1221
1222 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1223 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1224   switch (CC) {
1225   default: llvm_unreachable("Unknown condition code!");
1226   case ISD::SETNE:  return ARMCC::NE;
1227   case ISD::SETEQ:  return ARMCC::EQ;
1228   case ISD::SETGT:  return ARMCC::GT;
1229   case ISD::SETGE:  return ARMCC::GE;
1230   case ISD::SETLT:  return ARMCC::LT;
1231   case ISD::SETLE:  return ARMCC::LE;
1232   case ISD::SETUGT: return ARMCC::HI;
1233   case ISD::SETUGE: return ARMCC::HS;
1234   case ISD::SETULT: return ARMCC::LO;
1235   case ISD::SETULE: return ARMCC::LS;
1236   }
1237 }
1238
1239 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1240 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1241                         ARMCC::CondCodes &CondCode2) {
1242   CondCode2 = ARMCC::AL;
1243   switch (CC) {
1244   default: llvm_unreachable("Unknown FP condition!");
1245   case ISD::SETEQ:
1246   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1247   case ISD::SETGT:
1248   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1249   case ISD::SETGE:
1250   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1251   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1252   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1253   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1254   case ISD::SETO:   CondCode = ARMCC::VC; break;
1255   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1256   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1257   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1258   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1259   case ISD::SETLT:
1260   case ISD::SETULT: CondCode = ARMCC::LT; break;
1261   case ISD::SETLE:
1262   case ISD::SETULE: CondCode = ARMCC::LE; break;
1263   case ISD::SETNE:
1264   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1265   }
1266 }
1267
1268 //===----------------------------------------------------------------------===//
1269 //                      Calling Convention Implementation
1270 //===----------------------------------------------------------------------===//
1271
1272 #include "ARMGenCallingConv.inc"
1273
1274 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1275 /// account presence of floating point hardware and calling convention
1276 /// limitations, such as support for variadic functions.
1277 CallingConv::ID
1278 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1279                                            bool isVarArg) const {
1280   switch (CC) {
1281   default:
1282     llvm_unreachable("Unsupported calling convention");
1283   case CallingConv::ARM_AAPCS:
1284   case CallingConv::ARM_APCS:
1285   case CallingConv::GHC:
1286     return CC;
1287   case CallingConv::ARM_AAPCS_VFP:
1288     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1289   case CallingConv::C:
1290     if (!Subtarget->isAAPCS_ABI())
1291       return CallingConv::ARM_APCS;
1292     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1293              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1294              !isVarArg)
1295       return CallingConv::ARM_AAPCS_VFP;
1296     else
1297       return CallingConv::ARM_AAPCS;
1298   case CallingConv::Fast:
1299     if (!Subtarget->isAAPCS_ABI()) {
1300       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1301         return CallingConv::Fast;
1302       return CallingConv::ARM_APCS;
1303     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1304       return CallingConv::ARM_AAPCS_VFP;
1305     else
1306       return CallingConv::ARM_AAPCS;
1307   }
1308 }
1309
1310 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1311 /// CallingConvention.
1312 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1313                                                  bool Return,
1314                                                  bool isVarArg) const {
1315   switch (getEffectiveCallingConv(CC, isVarArg)) {
1316   default:
1317     llvm_unreachable("Unsupported calling convention");
1318   case CallingConv::ARM_APCS:
1319     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1320   case CallingConv::ARM_AAPCS:
1321     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1322   case CallingConv::ARM_AAPCS_VFP:
1323     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1324   case CallingConv::Fast:
1325     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1326   case CallingConv::GHC:
1327     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1328   }
1329 }
1330
1331 /// LowerCallResult - Lower the result values of a call into the
1332 /// appropriate copies out of appropriate physical registers.
1333 SDValue
1334 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1335                                    CallingConv::ID CallConv, bool isVarArg,
1336                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1337                                    SDLoc dl, SelectionDAG &DAG,
1338                                    SmallVectorImpl<SDValue> &InVals,
1339                                    bool isThisReturn, SDValue ThisVal) const {
1340
1341   // Assign locations to each value returned by this call.
1342   SmallVector<CCValAssign, 16> RVLocs;
1343   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1344                     *DAG.getContext(), Call);
1345   CCInfo.AnalyzeCallResult(Ins,
1346                            CCAssignFnForNode(CallConv, /* Return*/ true,
1347                                              isVarArg));
1348
1349   // Copy all of the result registers out of their specified physreg.
1350   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1351     CCValAssign VA = RVLocs[i];
1352
1353     // Pass 'this' value directly from the argument to return value, to avoid
1354     // reg unit interference
1355     if (i == 0 && isThisReturn) {
1356       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1357              "unexpected return calling convention register assignment");
1358       InVals.push_back(ThisVal);
1359       continue;
1360     }
1361
1362     SDValue Val;
1363     if (VA.needsCustom()) {
1364       // Handle f64 or half of a v2f64.
1365       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1366                                       InFlag);
1367       Chain = Lo.getValue(1);
1368       InFlag = Lo.getValue(2);
1369       VA = RVLocs[++i]; // skip ahead to next loc
1370       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1371                                       InFlag);
1372       Chain = Hi.getValue(1);
1373       InFlag = Hi.getValue(2);
1374       if (!Subtarget->isLittle())
1375         std::swap (Lo, Hi);
1376       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1377
1378       if (VA.getLocVT() == MVT::v2f64) {
1379         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1380         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1381                           DAG.getConstant(0, MVT::i32));
1382
1383         VA = RVLocs[++i]; // skip ahead to next loc
1384         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1385         Chain = Lo.getValue(1);
1386         InFlag = Lo.getValue(2);
1387         VA = RVLocs[++i]; // skip ahead to next loc
1388         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1389         Chain = Hi.getValue(1);
1390         InFlag = Hi.getValue(2);
1391         if (!Subtarget->isLittle())
1392           std::swap (Lo, Hi);
1393         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1394         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1395                           DAG.getConstant(1, MVT::i32));
1396       }
1397     } else {
1398       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1399                                InFlag);
1400       Chain = Val.getValue(1);
1401       InFlag = Val.getValue(2);
1402     }
1403
1404     switch (VA.getLocInfo()) {
1405     default: llvm_unreachable("Unknown loc info!");
1406     case CCValAssign::Full: break;
1407     case CCValAssign::BCvt:
1408       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1409       break;
1410     }
1411
1412     InVals.push_back(Val);
1413   }
1414
1415   return Chain;
1416 }
1417
1418 /// LowerMemOpCallTo - Store the argument to the stack.
1419 SDValue
1420 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1421                                     SDValue StackPtr, SDValue Arg,
1422                                     SDLoc dl, SelectionDAG &DAG,
1423                                     const CCValAssign &VA,
1424                                     ISD::ArgFlagsTy Flags) const {
1425   unsigned LocMemOffset = VA.getLocMemOffset();
1426   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1427   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1428   return DAG.getStore(Chain, dl, Arg, PtrOff,
1429                       MachinePointerInfo::getStack(LocMemOffset),
1430                       false, false, 0);
1431 }
1432
1433 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1434                                          SDValue Chain, SDValue &Arg,
1435                                          RegsToPassVector &RegsToPass,
1436                                          CCValAssign &VA, CCValAssign &NextVA,
1437                                          SDValue &StackPtr,
1438                                          SmallVectorImpl<SDValue> &MemOpChains,
1439                                          ISD::ArgFlagsTy Flags) const {
1440
1441   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1442                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1443   unsigned id = Subtarget->isLittle() ? 0 : 1;
1444   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1445
1446   if (NextVA.isRegLoc())
1447     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1448   else {
1449     assert(NextVA.isMemLoc());
1450     if (!StackPtr.getNode())
1451       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1452
1453     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1454                                            dl, DAG, NextVA,
1455                                            Flags));
1456   }
1457 }
1458
1459 /// LowerCall - Lowering a call into a callseq_start <-
1460 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1461 /// nodes.
1462 SDValue
1463 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1464                              SmallVectorImpl<SDValue> &InVals) const {
1465   SelectionDAG &DAG                     = CLI.DAG;
1466   SDLoc &dl                          = CLI.DL;
1467   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1468   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1469   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1470   SDValue Chain                         = CLI.Chain;
1471   SDValue Callee                        = CLI.Callee;
1472   bool &isTailCall                      = CLI.IsTailCall;
1473   CallingConv::ID CallConv              = CLI.CallConv;
1474   bool doesNotRet                       = CLI.DoesNotReturn;
1475   bool isVarArg                         = CLI.IsVarArg;
1476
1477   MachineFunction &MF = DAG.getMachineFunction();
1478   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1479   bool isThisReturn   = false;
1480   bool isSibCall      = false;
1481
1482   // Disable tail calls if they're not supported.
1483   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1484     isTailCall = false;
1485
1486   if (isTailCall) {
1487     // Check if it's really possible to do a tail call.
1488     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1489                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1490                                                    Outs, OutVals, Ins, DAG);
1491     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1492       report_fatal_error("failed to perform tail call elimination on a call "
1493                          "site marked musttail");
1494     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1495     // detected sibcalls.
1496     if (isTailCall) {
1497       ++NumTailCalls;
1498       isSibCall = true;
1499     }
1500   }
1501
1502   // Analyze operands of the call, assigning locations to each operand.
1503   SmallVector<CCValAssign, 16> ArgLocs;
1504   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1505                     *DAG.getContext(), Call);
1506   CCInfo.AnalyzeCallOperands(Outs,
1507                              CCAssignFnForNode(CallConv, /* Return*/ false,
1508                                                isVarArg));
1509
1510   // Get a count of how many bytes are to be pushed on the stack.
1511   unsigned NumBytes = CCInfo.getNextStackOffset();
1512
1513   // For tail calls, memory operands are available in our caller's stack.
1514   if (isSibCall)
1515     NumBytes = 0;
1516
1517   // Adjust the stack pointer for the new arguments...
1518   // These operations are automatically eliminated by the prolog/epilog pass
1519   if (!isSibCall)
1520     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1521                                  dl);
1522
1523   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1524
1525   RegsToPassVector RegsToPass;
1526   SmallVector<SDValue, 8> MemOpChains;
1527
1528   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1529   // of tail call optimization, arguments are handled later.
1530   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1531        i != e;
1532        ++i, ++realArgIdx) {
1533     CCValAssign &VA = ArgLocs[i];
1534     SDValue Arg = OutVals[realArgIdx];
1535     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1536     bool isByVal = Flags.isByVal();
1537
1538     // Promote the value if needed.
1539     switch (VA.getLocInfo()) {
1540     default: llvm_unreachable("Unknown loc info!");
1541     case CCValAssign::Full: break;
1542     case CCValAssign::SExt:
1543       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1544       break;
1545     case CCValAssign::ZExt:
1546       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1547       break;
1548     case CCValAssign::AExt:
1549       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1550       break;
1551     case CCValAssign::BCvt:
1552       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1553       break;
1554     }
1555
1556     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1557     if (VA.needsCustom()) {
1558       if (VA.getLocVT() == MVT::v2f64) {
1559         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1560                                   DAG.getConstant(0, MVT::i32));
1561         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1562                                   DAG.getConstant(1, MVT::i32));
1563
1564         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1565                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1566
1567         VA = ArgLocs[++i]; // skip ahead to next loc
1568         if (VA.isRegLoc()) {
1569           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1570                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1571         } else {
1572           assert(VA.isMemLoc());
1573
1574           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1575                                                  dl, DAG, VA, Flags));
1576         }
1577       } else {
1578         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1579                          StackPtr, MemOpChains, Flags);
1580       }
1581     } else if (VA.isRegLoc()) {
1582       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1583         assert(VA.getLocVT() == MVT::i32 &&
1584                "unexpected calling convention register assignment");
1585         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1586                "unexpected use of 'returned'");
1587         isThisReturn = true;
1588       }
1589       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1590     } else if (isByVal) {
1591       assert(VA.isMemLoc());
1592       unsigned offset = 0;
1593
1594       // True if this byval aggregate will be split between registers
1595       // and memory.
1596       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1597       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1598
1599       if (CurByValIdx < ByValArgsCount) {
1600
1601         unsigned RegBegin, RegEnd;
1602         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1603
1604         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1605         unsigned int i, j;
1606         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1607           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1608           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1609           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1610                                      MachinePointerInfo(),
1611                                      false, false, false,
1612                                      DAG.InferPtrAlignment(AddArg));
1613           MemOpChains.push_back(Load.getValue(1));
1614           RegsToPass.push_back(std::make_pair(j, Load));
1615         }
1616
1617         // If parameter size outsides register area, "offset" value
1618         // helps us to calculate stack slot for remained part properly.
1619         offset = RegEnd - RegBegin;
1620
1621         CCInfo.nextInRegsParam();
1622       }
1623
1624       if (Flags.getByValSize() > 4*offset) {
1625         unsigned LocMemOffset = VA.getLocMemOffset();
1626         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1627         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1628                                   StkPtrOff);
1629         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1630         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1631         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1632                                            MVT::i32);
1633         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1634
1635         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1636         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1637         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1638                                           Ops));
1639       }
1640     } else if (!isSibCall) {
1641       assert(VA.isMemLoc());
1642
1643       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1644                                              dl, DAG, VA, Flags));
1645     }
1646   }
1647
1648   if (!MemOpChains.empty())
1649     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1650
1651   // Build a sequence of copy-to-reg nodes chained together with token chain
1652   // and flag operands which copy the outgoing args into the appropriate regs.
1653   SDValue InFlag;
1654   // Tail call byval lowering might overwrite argument registers so in case of
1655   // tail call optimization the copies to registers are lowered later.
1656   if (!isTailCall)
1657     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1658       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1659                                RegsToPass[i].second, InFlag);
1660       InFlag = Chain.getValue(1);
1661     }
1662
1663   // For tail calls lower the arguments to the 'real' stack slot.
1664   if (isTailCall) {
1665     // Force all the incoming stack arguments to be loaded from the stack
1666     // before any new outgoing arguments are stored to the stack, because the
1667     // outgoing stack slots may alias the incoming argument stack slots, and
1668     // the alias isn't otherwise explicit. This is slightly more conservative
1669     // than necessary, because it means that each store effectively depends
1670     // on every argument instead of just those arguments it would clobber.
1671
1672     // Do not flag preceding copytoreg stuff together with the following stuff.
1673     InFlag = SDValue();
1674     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1675       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1676                                RegsToPass[i].second, InFlag);
1677       InFlag = Chain.getValue(1);
1678     }
1679     InFlag = SDValue();
1680   }
1681
1682   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1683   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1684   // node so that legalize doesn't hack it.
1685   bool isDirect = false;
1686   bool isARMFunc = false;
1687   bool isLocalARMFunc = false;
1688   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1689
1690   if (EnableARMLongCalls) {
1691     assert((Subtarget->isTargetWindows() ||
1692             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1693            "long-calls with non-static relocation model!");
1694     // Handle a global address or an external symbol. If it's not one of
1695     // those, the target's already in a register, so we don't need to do
1696     // anything extra.
1697     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1698       const GlobalValue *GV = G->getGlobal();
1699       // Create a constant pool entry for the callee address
1700       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1701       ARMConstantPoolValue *CPV =
1702         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1703
1704       // Get the address of the callee into a register
1705       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1706       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1707       Callee = DAG.getLoad(getPointerTy(), dl,
1708                            DAG.getEntryNode(), CPAddr,
1709                            MachinePointerInfo::getConstantPool(),
1710                            false, false, false, 0);
1711     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1712       const char *Sym = S->getSymbol();
1713
1714       // Create a constant pool entry for the callee address
1715       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1716       ARMConstantPoolValue *CPV =
1717         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1718                                       ARMPCLabelIndex, 0);
1719       // Get the address of the callee into a register
1720       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1721       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1722       Callee = DAG.getLoad(getPointerTy(), dl,
1723                            DAG.getEntryNode(), CPAddr,
1724                            MachinePointerInfo::getConstantPool(),
1725                            false, false, false, 0);
1726     }
1727   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1728     const GlobalValue *GV = G->getGlobal();
1729     isDirect = true;
1730     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1731     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1732                    getTargetMachine().getRelocationModel() != Reloc::Static;
1733     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1734     // ARM call to a local ARM function is predicable.
1735     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1736     // tBX takes a register source operand.
1737     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1738       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1739       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1740                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1741                                                       0, ARMII::MO_NONLAZY));
1742       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1743                            MachinePointerInfo::getGOT(), false, false, true, 0);
1744     } else if (Subtarget->isTargetCOFF()) {
1745       assert(Subtarget->isTargetWindows() &&
1746              "Windows is the only supported COFF target");
1747       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1748                                  ? ARMII::MO_DLLIMPORT
1749                                  : ARMII::MO_NO_FLAG;
1750       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1751                                           TargetFlags);
1752       if (GV->hasDLLImportStorageClass())
1753         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1754                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1755                                          Callee), MachinePointerInfo::getGOT(),
1756                              false, false, false, 0);
1757     } else {
1758       // On ELF targets for PIC code, direct calls should go through the PLT
1759       unsigned OpFlags = 0;
1760       if (Subtarget->isTargetELF() &&
1761           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1762         OpFlags = ARMII::MO_PLT;
1763       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1764     }
1765   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1766     isDirect = true;
1767     bool isStub = Subtarget->isTargetMachO() &&
1768                   getTargetMachine().getRelocationModel() != Reloc::Static;
1769     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1770     // tBX takes a register source operand.
1771     const char *Sym = S->getSymbol();
1772     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1773       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1774       ARMConstantPoolValue *CPV =
1775         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1776                                       ARMPCLabelIndex, 4);
1777       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1778       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1779       Callee = DAG.getLoad(getPointerTy(), dl,
1780                            DAG.getEntryNode(), CPAddr,
1781                            MachinePointerInfo::getConstantPool(),
1782                            false, false, false, 0);
1783       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1784       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1785                            getPointerTy(), Callee, PICLabel);
1786     } else {
1787       unsigned OpFlags = 0;
1788       // On ELF targets for PIC code, direct calls should go through the PLT
1789       if (Subtarget->isTargetELF() &&
1790                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1791         OpFlags = ARMII::MO_PLT;
1792       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1793     }
1794   }
1795
1796   // FIXME: handle tail calls differently.
1797   unsigned CallOpc;
1798   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1799   if (Subtarget->isThumb()) {
1800     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1801       CallOpc = ARMISD::CALL_NOLINK;
1802     else
1803       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1804   } else {
1805     if (!isDirect && !Subtarget->hasV5TOps())
1806       CallOpc = ARMISD::CALL_NOLINK;
1807     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1808                // Emit regular call when code size is the priority
1809                !HasMinSizeAttr)
1810       // "mov lr, pc; b _foo" to avoid confusing the RSP
1811       CallOpc = ARMISD::CALL_NOLINK;
1812     else
1813       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1814   }
1815
1816   std::vector<SDValue> Ops;
1817   Ops.push_back(Chain);
1818   Ops.push_back(Callee);
1819
1820   // Add argument registers to the end of the list so that they are known live
1821   // into the call.
1822   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1823     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1824                                   RegsToPass[i].second.getValueType()));
1825
1826   // Add a register mask operand representing the call-preserved registers.
1827   if (!isTailCall) {
1828     const uint32_t *Mask;
1829     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1830     if (isThisReturn) {
1831       // For 'this' returns, use the R0-preserving mask if applicable
1832       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1833       if (!Mask) {
1834         // Set isThisReturn to false if the calling convention is not one that
1835         // allows 'returned' to be modeled in this way, so LowerCallResult does
1836         // not try to pass 'this' straight through
1837         isThisReturn = false;
1838         Mask = ARI->getCallPreservedMask(MF, CallConv);
1839       }
1840     } else
1841       Mask = ARI->getCallPreservedMask(MF, CallConv);
1842
1843     assert(Mask && "Missing call preserved mask for calling convention");
1844     Ops.push_back(DAG.getRegisterMask(Mask));
1845   }
1846
1847   if (InFlag.getNode())
1848     Ops.push_back(InFlag);
1849
1850   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1851   if (isTailCall)
1852     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1853
1854   // Returns a chain and a flag for retval copy to use.
1855   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1856   InFlag = Chain.getValue(1);
1857
1858   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1859                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1860   if (!Ins.empty())
1861     InFlag = Chain.getValue(1);
1862
1863   // Handle result values, copying them out of physregs into vregs that we
1864   // return.
1865   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1866                          InVals, isThisReturn,
1867                          isThisReturn ? OutVals[0] : SDValue());
1868 }
1869
1870 /// HandleByVal - Every parameter *after* a byval parameter is passed
1871 /// on the stack.  Remember the next parameter register to allocate,
1872 /// and then confiscate the rest of the parameter registers to insure
1873 /// this.
1874 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1875                                     unsigned Align) const {
1876   assert((State->getCallOrPrologue() == Prologue ||
1877           State->getCallOrPrologue() == Call) &&
1878          "unhandled ParmContext");
1879
1880   // Byval (as with any stack) slots are always at least 4 byte aligned.
1881   Align = std::max(Align, 4U);
1882
1883   unsigned Reg = State->AllocateReg(GPRArgRegs);
1884   if (!Reg)
1885     return;
1886
1887   unsigned AlignInRegs = Align / 4;
1888   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1889   for (unsigned i = 0; i < Waste; ++i)
1890     Reg = State->AllocateReg(GPRArgRegs);
1891
1892   if (!Reg)
1893     return;
1894
1895   unsigned Excess = 4 * (ARM::R4 - Reg);
1896
1897   // Special case when NSAA != SP and parameter size greater than size of
1898   // all remained GPR regs. In that case we can't split parameter, we must
1899   // send it to stack. We also must set NCRN to R4, so waste all
1900   // remained registers.
1901   const unsigned NSAAOffset = State->getNextStackOffset();
1902   if (NSAAOffset != 0 && Size > Excess) {
1903     while (State->AllocateReg(GPRArgRegs))
1904       ;
1905     return;
1906   }
1907
1908   // First register for byval parameter is the first register that wasn't
1909   // allocated before this method call, so it would be "reg".
1910   // If parameter is small enough to be saved in range [reg, r4), then
1911   // the end (first after last) register would be reg + param-size-in-regs,
1912   // else parameter would be splitted between registers and stack,
1913   // end register would be r4 in this case.
1914   unsigned ByValRegBegin = Reg;
1915   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1916   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1917   // Note, first register is allocated in the beginning of function already,
1918   // allocate remained amount of registers we need.
1919   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1920     State->AllocateReg(GPRArgRegs);
1921   // A byval parameter that is split between registers and memory needs its
1922   // size truncated here.
1923   // In the case where the entire structure fits in registers, we set the
1924   // size in memory to zero.
1925   Size = std::max<int>(Size - Excess, 0);
1926 }
1927
1928
1929 /// MatchingStackOffset - Return true if the given stack call argument is
1930 /// already available in the same position (relatively) of the caller's
1931 /// incoming argument stack.
1932 static
1933 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1934                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1935                          const TargetInstrInfo *TII) {
1936   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1937   int FI = INT_MAX;
1938   if (Arg.getOpcode() == ISD::CopyFromReg) {
1939     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1940     if (!TargetRegisterInfo::isVirtualRegister(VR))
1941       return false;
1942     MachineInstr *Def = MRI->getVRegDef(VR);
1943     if (!Def)
1944       return false;
1945     if (!Flags.isByVal()) {
1946       if (!TII->isLoadFromStackSlot(Def, FI))
1947         return false;
1948     } else {
1949       return false;
1950     }
1951   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1952     if (Flags.isByVal())
1953       // ByVal argument is passed in as a pointer but it's now being
1954       // dereferenced. e.g.
1955       // define @foo(%struct.X* %A) {
1956       //   tail call @bar(%struct.X* byval %A)
1957       // }
1958       return false;
1959     SDValue Ptr = Ld->getBasePtr();
1960     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1961     if (!FINode)
1962       return false;
1963     FI = FINode->getIndex();
1964   } else
1965     return false;
1966
1967   assert(FI != INT_MAX);
1968   if (!MFI->isFixedObjectIndex(FI))
1969     return false;
1970   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1971 }
1972
1973 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1974 /// for tail call optimization. Targets which want to do tail call
1975 /// optimization should implement this function.
1976 bool
1977 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1978                                                      CallingConv::ID CalleeCC,
1979                                                      bool isVarArg,
1980                                                      bool isCalleeStructRet,
1981                                                      bool isCallerStructRet,
1982                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1983                                     const SmallVectorImpl<SDValue> &OutVals,
1984                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1985                                                      SelectionDAG& DAG) const {
1986   const Function *CallerF = DAG.getMachineFunction().getFunction();
1987   CallingConv::ID CallerCC = CallerF->getCallingConv();
1988   bool CCMatch = CallerCC == CalleeCC;
1989
1990   // Look for obvious safe cases to perform tail call optimization that do not
1991   // require ABI changes. This is what gcc calls sibcall.
1992
1993   // Do not sibcall optimize vararg calls unless the call site is not passing
1994   // any arguments.
1995   if (isVarArg && !Outs.empty())
1996     return false;
1997
1998   // Exception-handling functions need a special set of instructions to indicate
1999   // a return to the hardware. Tail-calling another function would probably
2000   // break this.
2001   if (CallerF->hasFnAttribute("interrupt"))
2002     return false;
2003
2004   // Also avoid sibcall optimization if either caller or callee uses struct
2005   // return semantics.
2006   if (isCalleeStructRet || isCallerStructRet)
2007     return false;
2008
2009   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2010   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2011   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2012   // support in the assembler and linker to be used. This would need to be
2013   // fixed to fully support tail calls in Thumb1.
2014   //
2015   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2016   // LR.  This means if we need to reload LR, it takes an extra instructions,
2017   // which outweighs the value of the tail call; but here we don't know yet
2018   // whether LR is going to be used.  Probably the right approach is to
2019   // generate the tail call here and turn it back into CALL/RET in
2020   // emitEpilogue if LR is used.
2021
2022   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2023   // but we need to make sure there are enough registers; the only valid
2024   // registers are the 4 used for parameters.  We don't currently do this
2025   // case.
2026   if (Subtarget->isThumb1Only())
2027     return false;
2028
2029   // Externally-defined functions with weak linkage should not be
2030   // tail-called on ARM when the OS does not support dynamic
2031   // pre-emption of symbols, as the AAELF spec requires normal calls
2032   // to undefined weak functions to be replaced with a NOP or jump to the
2033   // next instruction. The behaviour of branch instructions in this
2034   // situation (as used for tail calls) is implementation-defined, so we
2035   // cannot rely on the linker replacing the tail call with a return.
2036   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2037     const GlobalValue *GV = G->getGlobal();
2038     const Triple TT(getTargetMachine().getTargetTriple());
2039     if (GV->hasExternalWeakLinkage() &&
2040         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2041       return false;
2042   }
2043
2044   // If the calling conventions do not match, then we'd better make sure the
2045   // results are returned in the same way as what the caller expects.
2046   if (!CCMatch) {
2047     SmallVector<CCValAssign, 16> RVLocs1;
2048     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2049                        *DAG.getContext(), Call);
2050     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2051
2052     SmallVector<CCValAssign, 16> RVLocs2;
2053     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2054                        *DAG.getContext(), Call);
2055     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2056
2057     if (RVLocs1.size() != RVLocs2.size())
2058       return false;
2059     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2060       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2061         return false;
2062       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2063         return false;
2064       if (RVLocs1[i].isRegLoc()) {
2065         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2066           return false;
2067       } else {
2068         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2069           return false;
2070       }
2071     }
2072   }
2073
2074   // If Caller's vararg or byval argument has been split between registers and
2075   // stack, do not perform tail call, since part of the argument is in caller's
2076   // local frame.
2077   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2078                                       getInfo<ARMFunctionInfo>();
2079   if (AFI_Caller->getArgRegsSaveSize())
2080     return false;
2081
2082   // If the callee takes no arguments then go on to check the results of the
2083   // call.
2084   if (!Outs.empty()) {
2085     // Check if stack adjustment is needed. For now, do not do this if any
2086     // argument is passed on the stack.
2087     SmallVector<CCValAssign, 16> ArgLocs;
2088     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2089                       *DAG.getContext(), Call);
2090     CCInfo.AnalyzeCallOperands(Outs,
2091                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2092     if (CCInfo.getNextStackOffset()) {
2093       MachineFunction &MF = DAG.getMachineFunction();
2094
2095       // Check if the arguments are already laid out in the right way as
2096       // the caller's fixed stack objects.
2097       MachineFrameInfo *MFI = MF.getFrameInfo();
2098       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2099       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2100       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2101            i != e;
2102            ++i, ++realArgIdx) {
2103         CCValAssign &VA = ArgLocs[i];
2104         EVT RegVT = VA.getLocVT();
2105         SDValue Arg = OutVals[realArgIdx];
2106         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2107         if (VA.getLocInfo() == CCValAssign::Indirect)
2108           return false;
2109         if (VA.needsCustom()) {
2110           // f64 and vector types are split into multiple registers or
2111           // register/stack-slot combinations.  The types will not match
2112           // the registers; give up on memory f64 refs until we figure
2113           // out what to do about this.
2114           if (!VA.isRegLoc())
2115             return false;
2116           if (!ArgLocs[++i].isRegLoc())
2117             return false;
2118           if (RegVT == MVT::v2f64) {
2119             if (!ArgLocs[++i].isRegLoc())
2120               return false;
2121             if (!ArgLocs[++i].isRegLoc())
2122               return false;
2123           }
2124         } else if (!VA.isRegLoc()) {
2125           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2126                                    MFI, MRI, TII))
2127             return false;
2128         }
2129       }
2130     }
2131   }
2132
2133   return true;
2134 }
2135
2136 bool
2137 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2138                                   MachineFunction &MF, bool isVarArg,
2139                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2140                                   LLVMContext &Context) const {
2141   SmallVector<CCValAssign, 16> RVLocs;
2142   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2143   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2144                                                     isVarArg));
2145 }
2146
2147 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2148                                     SDLoc DL, SelectionDAG &DAG) {
2149   const MachineFunction &MF = DAG.getMachineFunction();
2150   const Function *F = MF.getFunction();
2151
2152   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2153
2154   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2155   // version of the "preferred return address". These offsets affect the return
2156   // instruction if this is a return from PL1 without hypervisor extensions.
2157   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2158   //    SWI:     0      "subs pc, lr, #0"
2159   //    ABORT:   +4     "subs pc, lr, #4"
2160   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2161   // UNDEF varies depending on where the exception came from ARM or Thumb
2162   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2163
2164   int64_t LROffset;
2165   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2166       IntKind == "ABORT")
2167     LROffset = 4;
2168   else if (IntKind == "SWI" || IntKind == "UNDEF")
2169     LROffset = 0;
2170   else
2171     report_fatal_error("Unsupported interrupt attribute. If present, value "
2172                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2173
2174   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2175
2176   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2177 }
2178
2179 SDValue
2180 ARMTargetLowering::LowerReturn(SDValue Chain,
2181                                CallingConv::ID CallConv, bool isVarArg,
2182                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2183                                const SmallVectorImpl<SDValue> &OutVals,
2184                                SDLoc dl, SelectionDAG &DAG) const {
2185
2186   // CCValAssign - represent the assignment of the return value to a location.
2187   SmallVector<CCValAssign, 16> RVLocs;
2188
2189   // CCState - Info about the registers and stack slots.
2190   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2191                     *DAG.getContext(), Call);
2192
2193   // Analyze outgoing return values.
2194   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2195                                                isVarArg));
2196
2197   SDValue Flag;
2198   SmallVector<SDValue, 4> RetOps;
2199   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2200   bool isLittleEndian = Subtarget->isLittle();
2201
2202   MachineFunction &MF = DAG.getMachineFunction();
2203   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2204   AFI->setReturnRegsCount(RVLocs.size());
2205
2206   // Copy the result values into the output registers.
2207   for (unsigned i = 0, realRVLocIdx = 0;
2208        i != RVLocs.size();
2209        ++i, ++realRVLocIdx) {
2210     CCValAssign &VA = RVLocs[i];
2211     assert(VA.isRegLoc() && "Can only return in registers!");
2212
2213     SDValue Arg = OutVals[realRVLocIdx];
2214
2215     switch (VA.getLocInfo()) {
2216     default: llvm_unreachable("Unknown loc info!");
2217     case CCValAssign::Full: break;
2218     case CCValAssign::BCvt:
2219       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2220       break;
2221     }
2222
2223     if (VA.needsCustom()) {
2224       if (VA.getLocVT() == MVT::v2f64) {
2225         // Extract the first half and return it in two registers.
2226         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2227                                    DAG.getConstant(0, MVT::i32));
2228         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2229                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2230
2231         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2232                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
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         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2238                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2239                                  Flag);
2240         Flag = Chain.getValue(1);
2241         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2242         VA = RVLocs[++i]; // skip ahead to next loc
2243
2244         // Extract the 2nd half and fall through to handle it as an f64 value.
2245         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2246                           DAG.getConstant(1, MVT::i32));
2247       }
2248       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2249       // available.
2250       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2251                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2252       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2253                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2254                                Flag);
2255       Flag = Chain.getValue(1);
2256       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2257       VA = RVLocs[++i]; // skip ahead to next loc
2258       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2259                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2260                                Flag);
2261     } else
2262       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2263
2264     // Guarantee that all emitted copies are
2265     // stuck together, avoiding something bad.
2266     Flag = Chain.getValue(1);
2267     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2268   }
2269
2270   // Update chain and glue.
2271   RetOps[0] = Chain;
2272   if (Flag.getNode())
2273     RetOps.push_back(Flag);
2274
2275   // CPUs which aren't M-class use a special sequence to return from
2276   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2277   // though we use "subs pc, lr, #N").
2278   //
2279   // M-class CPUs actually use a normal return sequence with a special
2280   // (hardware-provided) value in LR, so the normal code path works.
2281   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2282       !Subtarget->isMClass()) {
2283     if (Subtarget->isThumb1Only())
2284       report_fatal_error("interrupt attribute is not supported in Thumb1");
2285     return LowerInterruptReturn(RetOps, dl, DAG);
2286   }
2287
2288   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2289 }
2290
2291 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2292   if (N->getNumValues() != 1)
2293     return false;
2294   if (!N->hasNUsesOfValue(1, 0))
2295     return false;
2296
2297   SDValue TCChain = Chain;
2298   SDNode *Copy = *N->use_begin();
2299   if (Copy->getOpcode() == ISD::CopyToReg) {
2300     // If the copy has a glue operand, we conservatively assume it isn't safe to
2301     // perform a tail call.
2302     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2303       return false;
2304     TCChain = Copy->getOperand(0);
2305   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2306     SDNode *VMov = Copy;
2307     // f64 returned in a pair of GPRs.
2308     SmallPtrSet<SDNode*, 2> Copies;
2309     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2310          UI != UE; ++UI) {
2311       if (UI->getOpcode() != ISD::CopyToReg)
2312         return false;
2313       Copies.insert(*UI);
2314     }
2315     if (Copies.size() > 2)
2316       return false;
2317
2318     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2319          UI != UE; ++UI) {
2320       SDValue UseChain = UI->getOperand(0);
2321       if (Copies.count(UseChain.getNode()))
2322         // Second CopyToReg
2323         Copy = *UI;
2324       else {
2325         // We are at the top of this chain.
2326         // If the copy has a glue operand, we conservatively assume it
2327         // isn't safe to perform a tail call.
2328         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2329           return false;
2330         // First CopyToReg
2331         TCChain = UseChain;
2332       }
2333     }
2334   } else if (Copy->getOpcode() == ISD::BITCAST) {
2335     // f32 returned in a single GPR.
2336     if (!Copy->hasOneUse())
2337       return false;
2338     Copy = *Copy->use_begin();
2339     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2340       return false;
2341     // If the copy has a glue operand, we conservatively assume it isn't safe to
2342     // perform a tail call.
2343     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2344       return false;
2345     TCChain = Copy->getOperand(0);
2346   } else {
2347     return false;
2348   }
2349
2350   bool HasRet = false;
2351   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2352        UI != UE; ++UI) {
2353     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2354         UI->getOpcode() != ARMISD::INTRET_FLAG)
2355       return false;
2356     HasRet = true;
2357   }
2358
2359   if (!HasRet)
2360     return false;
2361
2362   Chain = TCChain;
2363   return true;
2364 }
2365
2366 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2367   if (!Subtarget->supportsTailCall())
2368     return false;
2369
2370   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2371     return false;
2372
2373   return !Subtarget->isThumb1Only();
2374 }
2375
2376 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2377 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2378 // one of the above mentioned nodes. It has to be wrapped because otherwise
2379 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2380 // be used to form addressing mode. These wrapped nodes will be selected
2381 // into MOVi.
2382 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2383   EVT PtrVT = Op.getValueType();
2384   // FIXME there is no actual debug info here
2385   SDLoc dl(Op);
2386   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2387   SDValue Res;
2388   if (CP->isMachineConstantPoolEntry())
2389     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2390                                     CP->getAlignment());
2391   else
2392     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2393                                     CP->getAlignment());
2394   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2395 }
2396
2397 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2398   return MachineJumpTableInfo::EK_Inline;
2399 }
2400
2401 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2402                                              SelectionDAG &DAG) const {
2403   MachineFunction &MF = DAG.getMachineFunction();
2404   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2405   unsigned ARMPCLabelIndex = 0;
2406   SDLoc DL(Op);
2407   EVT PtrVT = getPointerTy();
2408   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2409   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2410   SDValue CPAddr;
2411   if (RelocM == Reloc::Static) {
2412     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2413   } else {
2414     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2415     ARMPCLabelIndex = AFI->createPICLabelUId();
2416     ARMConstantPoolValue *CPV =
2417       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2418                                       ARMCP::CPBlockAddress, PCAdj);
2419     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2420   }
2421   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2422   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2423                                MachinePointerInfo::getConstantPool(),
2424                                false, false, false, 0);
2425   if (RelocM == Reloc::Static)
2426     return Result;
2427   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2428   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2429 }
2430
2431 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2432 SDValue
2433 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2434                                                  SelectionDAG &DAG) const {
2435   SDLoc dl(GA);
2436   EVT PtrVT = getPointerTy();
2437   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2438   MachineFunction &MF = DAG.getMachineFunction();
2439   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2440   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2441   ARMConstantPoolValue *CPV =
2442     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2443                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2444   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2445   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2446   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2447                          MachinePointerInfo::getConstantPool(),
2448                          false, false, false, 0);
2449   SDValue Chain = Argument.getValue(1);
2450
2451   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2452   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2453
2454   // call __tls_get_addr.
2455   ArgListTy Args;
2456   ArgListEntry Entry;
2457   Entry.Node = Argument;
2458   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2459   Args.push_back(Entry);
2460
2461   // FIXME: is there useful debug info available here?
2462   TargetLowering::CallLoweringInfo CLI(DAG);
2463   CLI.setDebugLoc(dl).setChain(Chain)
2464     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2465                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2466                0);
2467
2468   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2469   return CallResult.first;
2470 }
2471
2472 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2473 // "local exec" model.
2474 SDValue
2475 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2476                                         SelectionDAG &DAG,
2477                                         TLSModel::Model model) const {
2478   const GlobalValue *GV = GA->getGlobal();
2479   SDLoc dl(GA);
2480   SDValue Offset;
2481   SDValue Chain = DAG.getEntryNode();
2482   EVT PtrVT = getPointerTy();
2483   // Get the Thread Pointer
2484   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2485
2486   if (model == TLSModel::InitialExec) {
2487     MachineFunction &MF = DAG.getMachineFunction();
2488     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2489     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2490     // Initial exec model.
2491     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2492     ARMConstantPoolValue *CPV =
2493       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2494                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2495                                       true);
2496     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2497     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2498     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2499                          MachinePointerInfo::getConstantPool(),
2500                          false, false, false, 0);
2501     Chain = Offset.getValue(1);
2502
2503     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2504     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2505
2506     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2507                          MachinePointerInfo::getConstantPool(),
2508                          false, false, false, 0);
2509   } else {
2510     // local exec model
2511     assert(model == TLSModel::LocalExec);
2512     ARMConstantPoolValue *CPV =
2513       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2514     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2515     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2516     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2517                          MachinePointerInfo::getConstantPool(),
2518                          false, false, false, 0);
2519   }
2520
2521   // The address of the thread local variable is the add of the thread
2522   // pointer with the offset of the variable.
2523   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2524 }
2525
2526 SDValue
2527 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2528   // TODO: implement the "local dynamic" model
2529   assert(Subtarget->isTargetELF() &&
2530          "TLS not implemented for non-ELF targets");
2531   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2532
2533   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2534
2535   switch (model) {
2536     case TLSModel::GeneralDynamic:
2537     case TLSModel::LocalDynamic:
2538       return LowerToTLSGeneralDynamicModel(GA, DAG);
2539     case TLSModel::InitialExec:
2540     case TLSModel::LocalExec:
2541       return LowerToTLSExecModels(GA, DAG, model);
2542   }
2543   llvm_unreachable("bogus TLS model");
2544 }
2545
2546 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2547                                                  SelectionDAG &DAG) const {
2548   EVT PtrVT = getPointerTy();
2549   SDLoc dl(Op);
2550   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2551   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2552     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2553     ARMConstantPoolValue *CPV =
2554       ARMConstantPoolConstant::Create(GV,
2555                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2556     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2557     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2558     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2559                                  CPAddr,
2560                                  MachinePointerInfo::getConstantPool(),
2561                                  false, false, false, 0);
2562     SDValue Chain = Result.getValue(1);
2563     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2564     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2565     if (!UseGOTOFF)
2566       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2567                            MachinePointerInfo::getGOT(),
2568                            false, false, false, 0);
2569     return Result;
2570   }
2571
2572   // If we have T2 ops, we can materialize the address directly via movt/movw
2573   // pair. This is always cheaper.
2574   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2575     ++NumMovwMovt;
2576     // FIXME: Once remat is capable of dealing with instructions with register
2577     // operands, expand this into two nodes.
2578     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2579                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2580   } else {
2581     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2582     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2583     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2584                        MachinePointerInfo::getConstantPool(),
2585                        false, false, false, 0);
2586   }
2587 }
2588
2589 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2590                                                     SelectionDAG &DAG) const {
2591   EVT PtrVT = getPointerTy();
2592   SDLoc dl(Op);
2593   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2594   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2595
2596   if (Subtarget->useMovt(DAG.getMachineFunction()))
2597     ++NumMovwMovt;
2598
2599   // FIXME: Once remat is capable of dealing with instructions with register
2600   // operands, expand this into multiple nodes
2601   unsigned Wrapper =
2602       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2603
2604   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2605   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2606
2607   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2608     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2609                          MachinePointerInfo::getGOT(), false, false, false, 0);
2610   return Result;
2611 }
2612
2613 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2614                                                      SelectionDAG &DAG) const {
2615   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2616   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2617          "Windows on ARM expects to use movw/movt");
2618
2619   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2620   const ARMII::TOF TargetFlags =
2621     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2622   EVT PtrVT = getPointerTy();
2623   SDValue Result;
2624   SDLoc DL(Op);
2625
2626   ++NumMovwMovt;
2627
2628   // FIXME: Once remat is capable of dealing with instructions with register
2629   // operands, expand this into two nodes.
2630   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2631                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2632                                                   TargetFlags));
2633   if (GV->hasDLLImportStorageClass())
2634     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2635                          MachinePointerInfo::getGOT(), false, false, false, 0);
2636   return Result;
2637 }
2638
2639 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2640                                                     SelectionDAG &DAG) const {
2641   assert(Subtarget->isTargetELF() &&
2642          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2643   MachineFunction &MF = DAG.getMachineFunction();
2644   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2645   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2646   EVT PtrVT = getPointerTy();
2647   SDLoc dl(Op);
2648   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2649   ARMConstantPoolValue *CPV =
2650     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2651                                   ARMPCLabelIndex, PCAdj);
2652   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2653   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2654   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2655                                MachinePointerInfo::getConstantPool(),
2656                                false, false, false, 0);
2657   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2658   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2659 }
2660
2661 SDValue
2662 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2663   SDLoc dl(Op);
2664   SDValue Val = DAG.getConstant(0, MVT::i32);
2665   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2666                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2667                      Op.getOperand(1), Val);
2668 }
2669
2670 SDValue
2671 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2672   SDLoc dl(Op);
2673   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2674                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2675 }
2676
2677 SDValue
2678 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2679                                           const ARMSubtarget *Subtarget) const {
2680   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2681   SDLoc dl(Op);
2682   switch (IntNo) {
2683   default: return SDValue();    // Don't custom lower most intrinsics.
2684   case Intrinsic::arm_rbit: {
2685     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2686            "RBIT intrinsic must have i32 type!");
2687     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2688   }
2689   case Intrinsic::arm_thread_pointer: {
2690     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2691     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2692   }
2693   case Intrinsic::eh_sjlj_lsda: {
2694     MachineFunction &MF = DAG.getMachineFunction();
2695     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2696     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2697     EVT PtrVT = getPointerTy();
2698     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2699     SDValue CPAddr;
2700     unsigned PCAdj = (RelocM != Reloc::PIC_)
2701       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2702     ARMConstantPoolValue *CPV =
2703       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2704                                       ARMCP::CPLSDA, PCAdj);
2705     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2706     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2707     SDValue Result =
2708       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2709                   MachinePointerInfo::getConstantPool(),
2710                   false, false, false, 0);
2711
2712     if (RelocM == Reloc::PIC_) {
2713       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2714       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2715     }
2716     return Result;
2717   }
2718   case Intrinsic::arm_neon_vmulls:
2719   case Intrinsic::arm_neon_vmullu: {
2720     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2721       ? ARMISD::VMULLs : ARMISD::VMULLu;
2722     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2723                        Op.getOperand(1), Op.getOperand(2));
2724   }
2725   }
2726 }
2727
2728 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2729                                  const ARMSubtarget *Subtarget) {
2730   // FIXME: handle "fence singlethread" more efficiently.
2731   SDLoc dl(Op);
2732   if (!Subtarget->hasDataBarrier()) {
2733     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2734     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2735     // here.
2736     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2737            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2738     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2739                        DAG.getConstant(0, MVT::i32));
2740   }
2741
2742   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2743   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2744   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2745   if (Subtarget->isMClass()) {
2746     // Only a full system barrier exists in the M-class architectures.
2747     Domain = ARM_MB::SY;
2748   } else if (Subtarget->isSwift() && Ord == Release) {
2749     // Swift happens to implement ISHST barriers in a way that's compatible with
2750     // Release semantics but weaker than ISH so we'd be fools not to use
2751     // it. Beware: other processors probably don't!
2752     Domain = ARM_MB::ISHST;
2753   }
2754
2755   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2756                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2757                      DAG.getConstant(Domain, MVT::i32));
2758 }
2759
2760 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2761                              const ARMSubtarget *Subtarget) {
2762   // ARM pre v5TE and Thumb1 does not have preload instructions.
2763   if (!(Subtarget->isThumb2() ||
2764         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2765     // Just preserve the chain.
2766     return Op.getOperand(0);
2767
2768   SDLoc dl(Op);
2769   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2770   if (!isRead &&
2771       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2772     // ARMv7 with MP extension has PLDW.
2773     return Op.getOperand(0);
2774
2775   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2776   if (Subtarget->isThumb()) {
2777     // Invert the bits.
2778     isRead = ~isRead & 1;
2779     isData = ~isData & 1;
2780   }
2781
2782   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2783                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2784                      DAG.getConstant(isData, MVT::i32));
2785 }
2786
2787 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2788   MachineFunction &MF = DAG.getMachineFunction();
2789   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2790
2791   // vastart just stores the address of the VarArgsFrameIndex slot into the
2792   // memory location argument.
2793   SDLoc dl(Op);
2794   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2795   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2796   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2797   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2798                       MachinePointerInfo(SV), false, false, 0);
2799 }
2800
2801 SDValue
2802 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2803                                         SDValue &Root, SelectionDAG &DAG,
2804                                         SDLoc dl) const {
2805   MachineFunction &MF = DAG.getMachineFunction();
2806   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2807
2808   const TargetRegisterClass *RC;
2809   if (AFI->isThumb1OnlyFunction())
2810     RC = &ARM::tGPRRegClass;
2811   else
2812     RC = &ARM::GPRRegClass;
2813
2814   // Transform the arguments stored in physical registers into virtual ones.
2815   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2816   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2817
2818   SDValue ArgValue2;
2819   if (NextVA.isMemLoc()) {
2820     MachineFrameInfo *MFI = MF.getFrameInfo();
2821     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2822
2823     // Create load node to retrieve arguments from the stack.
2824     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2825     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2826                             MachinePointerInfo::getFixedStack(FI),
2827                             false, false, false, 0);
2828   } else {
2829     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2830     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2831   }
2832   if (!Subtarget->isLittle())
2833     std::swap (ArgValue, ArgValue2);
2834   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2835 }
2836
2837 // The remaining GPRs hold either the beginning of variable-argument
2838 // data, or the beginning of an aggregate passed by value (usually
2839 // byval).  Either way, we allocate stack slots adjacent to the data
2840 // provided by our caller, and store the unallocated registers there.
2841 // If this is a variadic function, the va_list pointer will begin with
2842 // these values; otherwise, this reassembles a (byval) structure that
2843 // was split between registers and memory.
2844 // Return: The frame index registers were stored into.
2845 int
2846 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2847                                   SDLoc dl, SDValue &Chain,
2848                                   const Value *OrigArg,
2849                                   unsigned InRegsParamRecordIdx,
2850                                   int ArgOffset,
2851                                   unsigned ArgSize) const {
2852   // Currently, two use-cases possible:
2853   // Case #1. Non-var-args function, and we meet first byval parameter.
2854   //          Setup first unallocated register as first byval register;
2855   //          eat all remained registers
2856   //          (these two actions are performed by HandleByVal method).
2857   //          Then, here, we initialize stack frame with
2858   //          "store-reg" instructions.
2859   // Case #2. Var-args function, that doesn't contain byval parameters.
2860   //          The same: eat all remained unallocated registers,
2861   //          initialize stack frame.
2862
2863   MachineFunction &MF = DAG.getMachineFunction();
2864   MachineFrameInfo *MFI = MF.getFrameInfo();
2865   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2866   unsigned RBegin, REnd;
2867   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2868     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2869   } else {
2870     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2871     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2872     REnd = ARM::R4;
2873   }
2874
2875   if (REnd != RBegin)
2876     ArgOffset = -4 * (ARM::R4 - RBegin);
2877
2878   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2879   SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2880
2881   SmallVector<SDValue, 4> MemOps;
2882   const TargetRegisterClass *RC =
2883       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2884
2885   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2886     unsigned VReg = MF.addLiveIn(Reg, RC);
2887     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2888     SDValue Store =
2889         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2890                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2891     MemOps.push_back(Store);
2892     FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2893                       DAG.getConstant(4, getPointerTy()));
2894   }
2895
2896   if (!MemOps.empty())
2897     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2898   return FrameIndex;
2899 }
2900
2901 // Setup stack frame, the va_list pointer will start from.
2902 void
2903 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2904                                         SDLoc dl, SDValue &Chain,
2905                                         unsigned ArgOffset,
2906                                         unsigned TotalArgRegsSaveSize,
2907                                         bool ForceMutable) const {
2908   MachineFunction &MF = DAG.getMachineFunction();
2909   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2910
2911   // Try to store any remaining integer argument regs
2912   // to their spots on the stack so that they may be loaded by deferencing
2913   // the result of va_next.
2914   // If there is no regs to be stored, just point address after last
2915   // argument passed via stack.
2916   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2917                                   CCInfo.getInRegsParamsCount(),
2918                                   CCInfo.getNextStackOffset(), 4);
2919   AFI->setVarArgsFrameIndex(FrameIndex);
2920 }
2921
2922 SDValue
2923 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2924                                         CallingConv::ID CallConv, bool isVarArg,
2925                                         const SmallVectorImpl<ISD::InputArg>
2926                                           &Ins,
2927                                         SDLoc dl, SelectionDAG &DAG,
2928                                         SmallVectorImpl<SDValue> &InVals)
2929                                           const {
2930   MachineFunction &MF = DAG.getMachineFunction();
2931   MachineFrameInfo *MFI = MF.getFrameInfo();
2932
2933   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2934
2935   // Assign locations to all of the incoming arguments.
2936   SmallVector<CCValAssign, 16> ArgLocs;
2937   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2938                     *DAG.getContext(), Prologue);
2939   CCInfo.AnalyzeFormalArguments(Ins,
2940                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2941                                                   isVarArg));
2942
2943   SmallVector<SDValue, 16> ArgValues;
2944   SDValue ArgValue;
2945   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2946   unsigned CurArgIdx = 0;
2947
2948   // Initially ArgRegsSaveSize is zero.
2949   // Then we increase this value each time we meet byval parameter.
2950   // We also increase this value in case of varargs function.
2951   AFI->setArgRegsSaveSize(0);
2952
2953   // Calculate the amount of stack space that we need to allocate to store
2954   // byval and variadic arguments that are passed in registers.
2955   // We need to know this before we allocate the first byval or variadic
2956   // argument, as they will be allocated a stack slot below the CFA (Canonical
2957   // Frame Address, the stack pointer at entry to the function).
2958   unsigned ArgRegBegin = ARM::R4;
2959   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2960     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
2961       break;
2962
2963     CCValAssign &VA = ArgLocs[i];
2964     unsigned Index = VA.getValNo();
2965     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
2966     if (!Flags.isByVal())
2967       continue;
2968
2969     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
2970     unsigned RBegin, REnd;
2971     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
2972     ArgRegBegin = std::min(ArgRegBegin, RBegin);
2973
2974     CCInfo.nextInRegsParam();
2975   }
2976   CCInfo.rewindByValRegsInfo();
2977
2978   int lastInsIndex = -1;
2979   if (isVarArg && MFI->hasVAStart()) {
2980     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2981     if (RegIdx != array_lengthof(GPRArgRegs))
2982       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
2983   }
2984
2985   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
2986   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
2987
2988   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2989     CCValAssign &VA = ArgLocs[i];
2990     if (Ins[VA.getValNo()].isOrigArg()) {
2991       std::advance(CurOrigArg,
2992                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
2993       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
2994     }
2995     // Arguments stored in registers.
2996     if (VA.isRegLoc()) {
2997       EVT RegVT = VA.getLocVT();
2998
2999       if (VA.needsCustom()) {
3000         // f64 and vector types are split up into multiple registers or
3001         // combinations of registers and stack slots.
3002         if (VA.getLocVT() == MVT::v2f64) {
3003           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3004                                                    Chain, DAG, dl);
3005           VA = ArgLocs[++i]; // skip ahead to next loc
3006           SDValue ArgValue2;
3007           if (VA.isMemLoc()) {
3008             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3009             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3010             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3011                                     MachinePointerInfo::getFixedStack(FI),
3012                                     false, false, false, 0);
3013           } else {
3014             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3015                                              Chain, DAG, dl);
3016           }
3017           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3018           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3019                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3020           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3021                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3022         } else
3023           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3024
3025       } else {
3026         const TargetRegisterClass *RC;
3027
3028         if (RegVT == MVT::f32)
3029           RC = &ARM::SPRRegClass;
3030         else if (RegVT == MVT::f64)
3031           RC = &ARM::DPRRegClass;
3032         else if (RegVT == MVT::v2f64)
3033           RC = &ARM::QPRRegClass;
3034         else if (RegVT == MVT::i32)
3035           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3036                                            : &ARM::GPRRegClass;
3037         else
3038           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3039
3040         // Transform the arguments in physical registers into virtual ones.
3041         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3042         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3043       }
3044
3045       // If this is an 8 or 16-bit value, it is really passed promoted
3046       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3047       // truncate to the right size.
3048       switch (VA.getLocInfo()) {
3049       default: llvm_unreachable("Unknown loc info!");
3050       case CCValAssign::Full: break;
3051       case CCValAssign::BCvt:
3052         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3053         break;
3054       case CCValAssign::SExt:
3055         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3056                                DAG.getValueType(VA.getValVT()));
3057         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3058         break;
3059       case CCValAssign::ZExt:
3060         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3061                                DAG.getValueType(VA.getValVT()));
3062         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3063         break;
3064       }
3065
3066       InVals.push_back(ArgValue);
3067
3068     } else { // VA.isRegLoc()
3069
3070       // sanity check
3071       assert(VA.isMemLoc());
3072       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3073
3074       int index = VA.getValNo();
3075
3076       // Some Ins[] entries become multiple ArgLoc[] entries.
3077       // Process them only once.
3078       if (index != lastInsIndex)
3079         {
3080           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3081           // FIXME: For now, all byval parameter objects are marked mutable.
3082           // This can be changed with more analysis.
3083           // In case of tail call optimization mark all arguments mutable.
3084           // Since they could be overwritten by lowering of arguments in case of
3085           // a tail call.
3086           if (Flags.isByVal()) {
3087             assert(Ins[index].isOrigArg() &&
3088                    "Byval arguments cannot be implicit");
3089             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3090
3091             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3092                                             CurByValIndex, VA.getLocMemOffset(),
3093                                             Flags.getByValSize());
3094             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3095             CCInfo.nextInRegsParam();
3096           } else {
3097             unsigned FIOffset = VA.getLocMemOffset();
3098             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3099                                             FIOffset, true);
3100
3101             // Create load nodes to retrieve arguments from the stack.
3102             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3103             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3104                                          MachinePointerInfo::getFixedStack(FI),
3105                                          false, false, false, 0));
3106           }
3107           lastInsIndex = index;
3108         }
3109     }
3110   }
3111
3112   // varargs
3113   if (isVarArg && MFI->hasVAStart())
3114     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3115                          CCInfo.getNextStackOffset(),
3116                          TotalArgRegsSaveSize);
3117
3118   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3119
3120   return Chain;
3121 }
3122
3123 /// isFloatingPointZero - Return true if this is +0.0.
3124 static bool isFloatingPointZero(SDValue Op) {
3125   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3126     return CFP->getValueAPF().isPosZero();
3127   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3128     // Maybe this has already been legalized into the constant pool?
3129     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3130       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3131       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3132         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3133           return CFP->getValueAPF().isPosZero();
3134     }
3135   } else if (Op->getOpcode() == ISD::BITCAST &&
3136              Op->getValueType(0) == MVT::f64) {
3137     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3138     // created by LowerConstantFP().
3139     SDValue BitcastOp = Op->getOperand(0);
3140     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3141       SDValue MoveOp = BitcastOp->getOperand(0);
3142       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3143           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3144         return true;
3145       }
3146     }
3147   }
3148   return false;
3149 }
3150
3151 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3152 /// the given operands.
3153 SDValue
3154 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3155                              SDValue &ARMcc, SelectionDAG &DAG,
3156                              SDLoc dl) const {
3157   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3158     unsigned C = RHSC->getZExtValue();
3159     if (!isLegalICmpImmediate(C)) {
3160       // Constant does not fit, try adjusting it by one?
3161       switch (CC) {
3162       default: break;
3163       case ISD::SETLT:
3164       case ISD::SETGE:
3165         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3166           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3167           RHS = DAG.getConstant(C-1, MVT::i32);
3168         }
3169         break;
3170       case ISD::SETULT:
3171       case ISD::SETUGE:
3172         if (C != 0 && isLegalICmpImmediate(C-1)) {
3173           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3174           RHS = DAG.getConstant(C-1, MVT::i32);
3175         }
3176         break;
3177       case ISD::SETLE:
3178       case ISD::SETGT:
3179         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3180           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3181           RHS = DAG.getConstant(C+1, MVT::i32);
3182         }
3183         break;
3184       case ISD::SETULE:
3185       case ISD::SETUGT:
3186         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3187           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3188           RHS = DAG.getConstant(C+1, MVT::i32);
3189         }
3190         break;
3191       }
3192     }
3193   }
3194
3195   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3196   ARMISD::NodeType CompareType;
3197   switch (CondCode) {
3198   default:
3199     CompareType = ARMISD::CMP;
3200     break;
3201   case ARMCC::EQ:
3202   case ARMCC::NE:
3203     // Uses only Z Flag
3204     CompareType = ARMISD::CMPZ;
3205     break;
3206   }
3207   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3208   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3209 }
3210
3211 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3212 SDValue
3213 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3214                              SDLoc dl) const {
3215   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3216   SDValue Cmp;
3217   if (!isFloatingPointZero(RHS))
3218     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3219   else
3220     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3221   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3222 }
3223
3224 /// duplicateCmp - Glue values can have only one use, so this function
3225 /// duplicates a comparison node.
3226 SDValue
3227 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3228   unsigned Opc = Cmp.getOpcode();
3229   SDLoc DL(Cmp);
3230   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3231     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3232
3233   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3234   Cmp = Cmp.getOperand(0);
3235   Opc = Cmp.getOpcode();
3236   if (Opc == ARMISD::CMPFP)
3237     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3238   else {
3239     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3240     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3241   }
3242   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3243 }
3244
3245 std::pair<SDValue, SDValue>
3246 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3247                                  SDValue &ARMcc) const {
3248   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3249
3250   SDValue Value, OverflowCmp;
3251   SDValue LHS = Op.getOperand(0);
3252   SDValue RHS = Op.getOperand(1);
3253
3254
3255   // FIXME: We are currently always generating CMPs because we don't support
3256   // generating CMN through the backend. This is not as good as the natural
3257   // CMP case because it causes a register dependency and cannot be folded
3258   // later.
3259
3260   switch (Op.getOpcode()) {
3261   default:
3262     llvm_unreachable("Unknown overflow instruction!");
3263   case ISD::SADDO:
3264     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3265     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3266     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3267     break;
3268   case ISD::UADDO:
3269     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3270     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3271     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3272     break;
3273   case ISD::SSUBO:
3274     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3275     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3276     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3277     break;
3278   case ISD::USUBO:
3279     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3280     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3281     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3282     break;
3283   } // switch (...)
3284
3285   return std::make_pair(Value, OverflowCmp);
3286 }
3287
3288
3289 SDValue
3290 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3291   // Let legalize expand this if it isn't a legal type yet.
3292   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3293     return SDValue();
3294
3295   SDValue Value, OverflowCmp;
3296   SDValue ARMcc;
3297   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3298   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3299   // We use 0 and 1 as false and true values.
3300   SDValue TVal = DAG.getConstant(1, MVT::i32);
3301   SDValue FVal = DAG.getConstant(0, MVT::i32);
3302   EVT VT = Op.getValueType();
3303
3304   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3305                                  ARMcc, CCR, OverflowCmp);
3306
3307   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3308   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3309 }
3310
3311
3312 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3313   SDValue Cond = Op.getOperand(0);
3314   SDValue SelectTrue = Op.getOperand(1);
3315   SDValue SelectFalse = Op.getOperand(2);
3316   SDLoc dl(Op);
3317   unsigned Opc = Cond.getOpcode();
3318
3319   if (Cond.getResNo() == 1 &&
3320       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3321        Opc == ISD::USUBO)) {
3322     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3323       return SDValue();
3324
3325     SDValue Value, OverflowCmp;
3326     SDValue ARMcc;
3327     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3328     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3329     EVT VT = Op.getValueType();
3330
3331     return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3332                    OverflowCmp, DAG);
3333   }
3334
3335   // Convert:
3336   //
3337   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3338   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3339   //
3340   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3341     const ConstantSDNode *CMOVTrue =
3342       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3343     const ConstantSDNode *CMOVFalse =
3344       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3345
3346     if (CMOVTrue && CMOVFalse) {
3347       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3348       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3349
3350       SDValue True;
3351       SDValue False;
3352       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3353         True = SelectTrue;
3354         False = SelectFalse;
3355       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3356         True = SelectFalse;
3357         False = SelectTrue;
3358       }
3359
3360       if (True.getNode() && False.getNode()) {
3361         EVT VT = Op.getValueType();
3362         SDValue ARMcc = Cond.getOperand(2);
3363         SDValue CCR = Cond.getOperand(3);
3364         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3365         assert(True.getValueType() == VT);
3366         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3367       }
3368     }
3369   }
3370
3371   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3372   // undefined bits before doing a full-word comparison with zero.
3373   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3374                      DAG.getConstant(1, Cond.getValueType()));
3375
3376   return DAG.getSelectCC(dl, Cond,
3377                          DAG.getConstant(0, Cond.getValueType()),
3378                          SelectTrue, SelectFalse, ISD::SETNE);
3379 }
3380
3381 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3382   if (CC == ISD::SETNE)
3383     return ISD::SETEQ;
3384   return ISD::getSetCCInverse(CC, true);
3385 }
3386
3387 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3388                                  bool &swpCmpOps, bool &swpVselOps) {
3389   // Start by selecting the GE condition code for opcodes that return true for
3390   // 'equality'
3391   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3392       CC == ISD::SETULE)
3393     CondCode = ARMCC::GE;
3394
3395   // and GT for opcodes that return false for 'equality'.
3396   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3397            CC == ISD::SETULT)
3398     CondCode = ARMCC::GT;
3399
3400   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3401   // to swap the compare operands.
3402   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3403       CC == ISD::SETULT)
3404     swpCmpOps = true;
3405
3406   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3407   // If we have an unordered opcode, we need to swap the operands to the VSEL
3408   // instruction (effectively negating the condition).
3409   //
3410   // This also has the effect of swapping which one of 'less' or 'greater'
3411   // returns true, so we also swap the compare operands. It also switches
3412   // whether we return true for 'equality', so we compensate by picking the
3413   // opposite condition code to our original choice.
3414   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3415       CC == ISD::SETUGT) {
3416     swpCmpOps = !swpCmpOps;
3417     swpVselOps = !swpVselOps;
3418     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3419   }
3420
3421   // 'ordered' is 'anything but unordered', so use the VS condition code and
3422   // swap the VSEL operands.
3423   if (CC == ISD::SETO) {
3424     CondCode = ARMCC::VS;
3425     swpVselOps = true;
3426   }
3427
3428   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3429   // code and swap the VSEL operands.
3430   if (CC == ISD::SETUNE) {
3431     CondCode = ARMCC::EQ;
3432     swpVselOps = true;
3433   }
3434 }
3435
3436 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3437                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3438                                    SDValue Cmp, SelectionDAG &DAG) const {
3439   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3440     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3441                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3442     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3443                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3444
3445     SDValue TrueLow = TrueVal.getValue(0);
3446     SDValue TrueHigh = TrueVal.getValue(1);
3447     SDValue FalseLow = FalseVal.getValue(0);
3448     SDValue FalseHigh = FalseVal.getValue(1);
3449
3450     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3451                               ARMcc, CCR, Cmp);
3452     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3453                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3454
3455     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3456   } else {
3457     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3458                        Cmp);
3459   }
3460 }
3461
3462 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3463   EVT VT = Op.getValueType();
3464   SDValue LHS = Op.getOperand(0);
3465   SDValue RHS = Op.getOperand(1);
3466   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3467   SDValue TrueVal = Op.getOperand(2);
3468   SDValue FalseVal = Op.getOperand(3);
3469   SDLoc dl(Op);
3470
3471   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3472     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3473                                                     dl);
3474
3475     // If softenSetCCOperands only returned one value, we should compare it to
3476     // zero.
3477     if (!RHS.getNode()) {
3478       RHS = DAG.getConstant(0, LHS.getValueType());
3479       CC = ISD::SETNE;
3480     }
3481   }
3482
3483   if (LHS.getValueType() == MVT::i32) {
3484     // Try to generate VSEL on ARMv8.
3485     // The VSEL instruction can't use all the usual ARM condition
3486     // codes: it only has two bits to select the condition code, so it's
3487     // constrained to use only GE, GT, VS and EQ.
3488     //
3489     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3490     // swap the operands of the previous compare instruction (effectively
3491     // inverting the compare condition, swapping 'less' and 'greater') and
3492     // sometimes need to swap the operands to the VSEL (which inverts the
3493     // condition in the sense of firing whenever the previous condition didn't)
3494     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3495                                     TrueVal.getValueType() == MVT::f64)) {
3496       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3497       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3498           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3499         CC = getInverseCCForVSEL(CC);
3500         std::swap(TrueVal, FalseVal);
3501       }
3502     }
3503
3504     SDValue ARMcc;
3505     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3506     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3507     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3508   }
3509
3510   ARMCC::CondCodes CondCode, CondCode2;
3511   FPCCToARMCC(CC, CondCode, CondCode2);
3512
3513   // Try to generate VSEL on ARMv8.
3514   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3515                                   TrueVal.getValueType() == MVT::f64)) {
3516     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3517     // same operands, as follows:
3518     //   c = fcmp [ogt, olt, ugt, ult] a, b
3519     //   select c, a, b
3520     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3521     // handled differently than the original code sequence.
3522     if (getTargetMachine().Options.UnsafeFPMath) {
3523       if (LHS == TrueVal && RHS == FalseVal) {
3524         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3525           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3526         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3527           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3528       } else if (LHS == FalseVal && RHS == TrueVal) {
3529         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3530           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3531         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3532           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3533       }
3534     }
3535
3536     bool swpCmpOps = false;
3537     bool swpVselOps = false;
3538     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3539
3540     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3541         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3542       if (swpCmpOps)
3543         std::swap(LHS, RHS);
3544       if (swpVselOps)
3545         std::swap(TrueVal, FalseVal);
3546     }
3547   }
3548
3549   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3550   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3551   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3552   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3553   if (CondCode2 != ARMCC::AL) {
3554     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3555     // FIXME: Needs another CMP because flag can have but one use.
3556     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3557     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3558   }
3559   return Result;
3560 }
3561
3562 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3563 /// to morph to an integer compare sequence.
3564 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3565                            const ARMSubtarget *Subtarget) {
3566   SDNode *N = Op.getNode();
3567   if (!N->hasOneUse())
3568     // Otherwise it requires moving the value from fp to integer registers.
3569     return false;
3570   if (!N->getNumValues())
3571     return false;
3572   EVT VT = Op.getValueType();
3573   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3574     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3575     // vmrs are very slow, e.g. cortex-a8.
3576     return false;
3577
3578   if (isFloatingPointZero(Op)) {
3579     SeenZero = true;
3580     return true;
3581   }
3582   return ISD::isNormalLoad(N);
3583 }
3584
3585 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3586   if (isFloatingPointZero(Op))
3587     return DAG.getConstant(0, MVT::i32);
3588
3589   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3590     return DAG.getLoad(MVT::i32, SDLoc(Op),
3591                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3592                        Ld->isVolatile(), Ld->isNonTemporal(),
3593                        Ld->isInvariant(), Ld->getAlignment());
3594
3595   llvm_unreachable("Unknown VFP cmp argument!");
3596 }
3597
3598 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3599                            SDValue &RetVal1, SDValue &RetVal2) {
3600   if (isFloatingPointZero(Op)) {
3601     RetVal1 = DAG.getConstant(0, MVT::i32);
3602     RetVal2 = DAG.getConstant(0, MVT::i32);
3603     return;
3604   }
3605
3606   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3607     SDValue Ptr = Ld->getBasePtr();
3608     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3609                           Ld->getChain(), Ptr,
3610                           Ld->getPointerInfo(),
3611                           Ld->isVolatile(), Ld->isNonTemporal(),
3612                           Ld->isInvariant(), Ld->getAlignment());
3613
3614     EVT PtrType = Ptr.getValueType();
3615     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3616     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3617                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3618     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3619                           Ld->getChain(), NewPtr,
3620                           Ld->getPointerInfo().getWithOffset(4),
3621                           Ld->isVolatile(), Ld->isNonTemporal(),
3622                           Ld->isInvariant(), NewAlign);
3623     return;
3624   }
3625
3626   llvm_unreachable("Unknown VFP cmp argument!");
3627 }
3628
3629 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3630 /// f32 and even f64 comparisons to integer ones.
3631 SDValue
3632 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3633   SDValue Chain = Op.getOperand(0);
3634   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3635   SDValue LHS = Op.getOperand(2);
3636   SDValue RHS = Op.getOperand(3);
3637   SDValue Dest = Op.getOperand(4);
3638   SDLoc dl(Op);
3639
3640   bool LHSSeenZero = false;
3641   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3642   bool RHSSeenZero = false;
3643   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3644   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3645     // If unsafe fp math optimization is enabled and there are no other uses of
3646     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3647     // to an integer comparison.
3648     if (CC == ISD::SETOEQ)
3649       CC = ISD::SETEQ;
3650     else if (CC == ISD::SETUNE)
3651       CC = ISD::SETNE;
3652
3653     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3654     SDValue ARMcc;
3655     if (LHS.getValueType() == MVT::f32) {
3656       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3657                         bitcastf32Toi32(LHS, DAG), Mask);
3658       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3659                         bitcastf32Toi32(RHS, DAG), Mask);
3660       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3661       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3662       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3663                          Chain, Dest, ARMcc, CCR, Cmp);
3664     }
3665
3666     SDValue LHS1, LHS2;
3667     SDValue RHS1, RHS2;
3668     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3669     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3670     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3671     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3672     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3673     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3674     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3675     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3676     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3677   }
3678
3679   return SDValue();
3680 }
3681
3682 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3683   SDValue Chain = Op.getOperand(0);
3684   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3685   SDValue LHS = Op.getOperand(2);
3686   SDValue RHS = Op.getOperand(3);
3687   SDValue Dest = Op.getOperand(4);
3688   SDLoc dl(Op);
3689
3690   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3691     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3692                                                     dl);
3693
3694     // If softenSetCCOperands only returned one value, we should compare it to
3695     // zero.
3696     if (!RHS.getNode()) {
3697       RHS = DAG.getConstant(0, LHS.getValueType());
3698       CC = ISD::SETNE;
3699     }
3700   }
3701
3702   if (LHS.getValueType() == MVT::i32) {
3703     SDValue ARMcc;
3704     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3705     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3706     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3707                        Chain, Dest, ARMcc, CCR, Cmp);
3708   }
3709
3710   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3711
3712   if (getTargetMachine().Options.UnsafeFPMath &&
3713       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3714        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3715     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3716     if (Result.getNode())
3717       return Result;
3718   }
3719
3720   ARMCC::CondCodes CondCode, CondCode2;
3721   FPCCToARMCC(CC, CondCode, CondCode2);
3722
3723   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3724   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3725   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3726   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3727   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3728   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3729   if (CondCode2 != ARMCC::AL) {
3730     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3731     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3732     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3733   }
3734   return Res;
3735 }
3736
3737 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3738   SDValue Chain = Op.getOperand(0);
3739   SDValue Table = Op.getOperand(1);
3740   SDValue Index = Op.getOperand(2);
3741   SDLoc dl(Op);
3742
3743   EVT PTy = getPointerTy();
3744   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3745   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3746   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3747   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3748   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3749   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3750   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3751   if (Subtarget->isThumb2()) {
3752     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3753     // which does another jump to the destination. This also makes it easier
3754     // to translate it to TBB / TBH later.
3755     // FIXME: This might not work if the function is extremely large.
3756     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3757                        Addr, Op.getOperand(2), JTI, UId);
3758   }
3759   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3760     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3761                        MachinePointerInfo::getJumpTable(),
3762                        false, false, false, 0);
3763     Chain = Addr.getValue(1);
3764     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3765     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3766   } else {
3767     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3768                        MachinePointerInfo::getJumpTable(),
3769                        false, false, false, 0);
3770     Chain = Addr.getValue(1);
3771     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3772   }
3773 }
3774
3775 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3776   EVT VT = Op.getValueType();
3777   SDLoc dl(Op);
3778
3779   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3780     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3781       return Op;
3782     return DAG.UnrollVectorOp(Op.getNode());
3783   }
3784
3785   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3786          "Invalid type for custom lowering!");
3787   if (VT != MVT::v4i16)
3788     return DAG.UnrollVectorOp(Op.getNode());
3789
3790   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3791   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3792 }
3793
3794 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3795   EVT VT = Op.getValueType();
3796   if (VT.isVector())
3797     return LowerVectorFP_TO_INT(Op, DAG);
3798
3799   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3800     RTLIB::Libcall LC;
3801     if (Op.getOpcode() == ISD::FP_TO_SINT)
3802       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3803                               Op.getValueType());
3804     else
3805       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3806                               Op.getValueType());
3807     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3808                        /*isSigned*/ false, SDLoc(Op)).first;
3809   }
3810
3811   SDLoc dl(Op);
3812   unsigned Opc;
3813
3814   switch (Op.getOpcode()) {
3815   default: llvm_unreachable("Invalid opcode!");
3816   case ISD::FP_TO_SINT:
3817     Opc = ARMISD::FTOSI;
3818     break;
3819   case ISD::FP_TO_UINT:
3820     Opc = ARMISD::FTOUI;
3821     break;
3822   }
3823   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3824   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3825 }
3826
3827 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3828   EVT VT = Op.getValueType();
3829   SDLoc dl(Op);
3830
3831   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3832     if (VT.getVectorElementType() == MVT::f32)
3833       return Op;
3834     return DAG.UnrollVectorOp(Op.getNode());
3835   }
3836
3837   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3838          "Invalid type for custom lowering!");
3839   if (VT != MVT::v4f32)
3840     return DAG.UnrollVectorOp(Op.getNode());
3841
3842   unsigned CastOpc;
3843   unsigned Opc;
3844   switch (Op.getOpcode()) {
3845   default: llvm_unreachable("Invalid opcode!");
3846   case ISD::SINT_TO_FP:
3847     CastOpc = ISD::SIGN_EXTEND;
3848     Opc = ISD::SINT_TO_FP;
3849     break;
3850   case ISD::UINT_TO_FP:
3851     CastOpc = ISD::ZERO_EXTEND;
3852     Opc = ISD::UINT_TO_FP;
3853     break;
3854   }
3855
3856   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3857   return DAG.getNode(Opc, dl, VT, Op);
3858 }
3859
3860 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3861   EVT VT = Op.getValueType();
3862   if (VT.isVector())
3863     return LowerVectorINT_TO_FP(Op, DAG);
3864
3865   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3866     RTLIB::Libcall LC;
3867     if (Op.getOpcode() == ISD::SINT_TO_FP)
3868       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3869                               Op.getValueType());
3870     else
3871       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3872                               Op.getValueType());
3873     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3874                        /*isSigned*/ false, SDLoc(Op)).first;
3875   }
3876
3877   SDLoc dl(Op);
3878   unsigned Opc;
3879
3880   switch (Op.getOpcode()) {
3881   default: llvm_unreachable("Invalid opcode!");
3882   case ISD::SINT_TO_FP:
3883     Opc = ARMISD::SITOF;
3884     break;
3885   case ISD::UINT_TO_FP:
3886     Opc = ARMISD::UITOF;
3887     break;
3888   }
3889
3890   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3891   return DAG.getNode(Opc, dl, VT, Op);
3892 }
3893
3894 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3895   // Implement fcopysign with a fabs and a conditional fneg.
3896   SDValue Tmp0 = Op.getOperand(0);
3897   SDValue Tmp1 = Op.getOperand(1);
3898   SDLoc dl(Op);
3899   EVT VT = Op.getValueType();
3900   EVT SrcVT = Tmp1.getValueType();
3901   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3902     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3903   bool UseNEON = !InGPR && Subtarget->hasNEON();
3904
3905   if (UseNEON) {
3906     // Use VBSL to copy the sign bit.
3907     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3908     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3909                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3910     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3911     if (VT == MVT::f64)
3912       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3913                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3914                          DAG.getConstant(32, MVT::i32));
3915     else /*if (VT == MVT::f32)*/
3916       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3917     if (SrcVT == MVT::f32) {
3918       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3919       if (VT == MVT::f64)
3920         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3921                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3922                            DAG.getConstant(32, MVT::i32));
3923     } else if (VT == MVT::f32)
3924       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3925                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3926                          DAG.getConstant(32, MVT::i32));
3927     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3928     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3929
3930     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3931                                             MVT::i32);
3932     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3933     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3934                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3935
3936     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3937                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3938                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3939     if (VT == MVT::f32) {
3940       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3941       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3942                         DAG.getConstant(0, MVT::i32));
3943     } else {
3944       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3945     }
3946
3947     return Res;
3948   }
3949
3950   // Bitcast operand 1 to i32.
3951   if (SrcVT == MVT::f64)
3952     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3953                        Tmp1).getValue(1);
3954   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3955
3956   // Or in the signbit with integer operations.
3957   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3958   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3959   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3960   if (VT == MVT::f32) {
3961     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3962                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3963     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3964                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3965   }
3966
3967   // f64: Or the high part with signbit and then combine two parts.
3968   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3969                      Tmp0);
3970   SDValue Lo = Tmp0.getValue(0);
3971   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3972   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3973   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3974 }
3975
3976 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3977   MachineFunction &MF = DAG.getMachineFunction();
3978   MachineFrameInfo *MFI = MF.getFrameInfo();
3979   MFI->setReturnAddressIsTaken(true);
3980
3981   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3982     return SDValue();
3983
3984   EVT VT = Op.getValueType();
3985   SDLoc dl(Op);
3986   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3987   if (Depth) {
3988     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3989     SDValue Offset = DAG.getConstant(4, MVT::i32);
3990     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3991                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3992                        MachinePointerInfo(), false, false, false, 0);
3993   }
3994
3995   // Return LR, which contains the return address. Mark it an implicit live-in.
3996   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3997   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3998 }
3999
4000 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4001   const ARMBaseRegisterInfo &ARI =
4002     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4003   MachineFunction &MF = DAG.getMachineFunction();
4004   MachineFrameInfo *MFI = MF.getFrameInfo();
4005   MFI->setFrameAddressIsTaken(true);
4006
4007   EVT VT = Op.getValueType();
4008   SDLoc dl(Op);  // FIXME probably not meaningful
4009   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4010   unsigned FrameReg = ARI.getFrameRegister(MF);
4011   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4012   while (Depth--)
4013     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4014                             MachinePointerInfo(),
4015                             false, false, false, 0);
4016   return FrameAddr;
4017 }
4018
4019 // FIXME? Maybe this could be a TableGen attribute on some registers and
4020 // this table could be generated automatically from RegInfo.
4021 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4022                                               EVT VT) const {
4023   unsigned Reg = StringSwitch<unsigned>(RegName)
4024                        .Case("sp", ARM::SP)
4025                        .Default(0);
4026   if (Reg)
4027     return Reg;
4028   report_fatal_error("Invalid register name global variable");
4029 }
4030
4031 /// ExpandBITCAST - If the target supports VFP, this function is called to
4032 /// expand a bit convert where either the source or destination type is i64 to
4033 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4034 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4035 /// vectors), since the legalizer won't know what to do with that.
4036 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4037   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4038   SDLoc dl(N);
4039   SDValue Op = N->getOperand(0);
4040
4041   // This function is only supposed to be called for i64 types, either as the
4042   // source or destination of the bit convert.
4043   EVT SrcVT = Op.getValueType();
4044   EVT DstVT = N->getValueType(0);
4045   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4046          "ExpandBITCAST called for non-i64 type");
4047
4048   // Turn i64->f64 into VMOVDRR.
4049   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4050     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4051                              DAG.getConstant(0, MVT::i32));
4052     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4053                              DAG.getConstant(1, MVT::i32));
4054     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4055                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4056   }
4057
4058   // Turn f64->i64 into VMOVRRD.
4059   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4060     SDValue Cvt;
4061     if (TLI.isBigEndian() && SrcVT.isVector() &&
4062         SrcVT.getVectorNumElements() > 1)
4063       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4064                         DAG.getVTList(MVT::i32, MVT::i32),
4065                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4066     else
4067       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4068                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4069     // Merge the pieces into a single i64 value.
4070     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4071   }
4072
4073   return SDValue();
4074 }
4075
4076 /// getZeroVector - Returns a vector of specified type with all zero elements.
4077 /// Zero vectors are used to represent vector negation and in those cases
4078 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4079 /// not support i64 elements, so sometimes the zero vectors will need to be
4080 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4081 /// zero vector.
4082 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4083   assert(VT.isVector() && "Expected a vector type");
4084   // The canonical modified immediate encoding of a zero vector is....0!
4085   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4086   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4087   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4088   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4089 }
4090
4091 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4092 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4093 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4094                                                 SelectionDAG &DAG) const {
4095   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4096   EVT VT = Op.getValueType();
4097   unsigned VTBits = VT.getSizeInBits();
4098   SDLoc dl(Op);
4099   SDValue ShOpLo = Op.getOperand(0);
4100   SDValue ShOpHi = Op.getOperand(1);
4101   SDValue ShAmt  = Op.getOperand(2);
4102   SDValue ARMcc;
4103   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4104
4105   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4106
4107   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4108                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4109   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4110   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4111                                    DAG.getConstant(VTBits, MVT::i32));
4112   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4113   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4114   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4115
4116   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4117   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4118                           ARMcc, DAG, dl);
4119   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4120   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4121                            CCR, Cmp);
4122
4123   SDValue Ops[2] = { Lo, Hi };
4124   return DAG.getMergeValues(Ops, dl);
4125 }
4126
4127 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4128 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4129 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4130                                                SelectionDAG &DAG) const {
4131   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4132   EVT VT = Op.getValueType();
4133   unsigned VTBits = VT.getSizeInBits();
4134   SDLoc dl(Op);
4135   SDValue ShOpLo = Op.getOperand(0);
4136   SDValue ShOpHi = Op.getOperand(1);
4137   SDValue ShAmt  = Op.getOperand(2);
4138   SDValue ARMcc;
4139
4140   assert(Op.getOpcode() == ISD::SHL_PARTS);
4141   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4142                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4143   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4144   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4145                                    DAG.getConstant(VTBits, MVT::i32));
4146   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4147   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4148
4149   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4150   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4151   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4152                           ARMcc, DAG, dl);
4153   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4154   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4155                            CCR, Cmp);
4156
4157   SDValue Ops[2] = { Lo, Hi };
4158   return DAG.getMergeValues(Ops, dl);
4159 }
4160
4161 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4162                                             SelectionDAG &DAG) const {
4163   // The rounding mode is in bits 23:22 of the FPSCR.
4164   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4165   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4166   // so that the shift + and get folded into a bitfield extract.
4167   SDLoc dl(Op);
4168   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4169                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4170                                               MVT::i32));
4171   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4172                                   DAG.getConstant(1U << 22, MVT::i32));
4173   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4174                               DAG.getConstant(22, MVT::i32));
4175   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4176                      DAG.getConstant(3, MVT::i32));
4177 }
4178
4179 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4180                          const ARMSubtarget *ST) {
4181   EVT VT = N->getValueType(0);
4182   SDLoc dl(N);
4183
4184   if (!ST->hasV6T2Ops())
4185     return SDValue();
4186
4187   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4188   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4189 }
4190
4191 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4192 /// for each 16-bit element from operand, repeated.  The basic idea is to
4193 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4194 ///
4195 /// Trace for v4i16:
4196 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4197 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4198 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4199 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4200 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4201 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4202 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4203 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4204 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4205   EVT VT = N->getValueType(0);
4206   SDLoc DL(N);
4207
4208   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4209   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4210   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4211   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4212   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4213   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4214 }
4215
4216 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4217 /// bit-count for each 16-bit element from the operand.  We need slightly
4218 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4219 /// 64/128-bit registers.
4220 ///
4221 /// Trace for v4i16:
4222 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4223 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4224 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4225 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4226 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4227   EVT VT = N->getValueType(0);
4228   SDLoc DL(N);
4229
4230   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4231   if (VT.is64BitVector()) {
4232     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4233     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4234                        DAG.getIntPtrConstant(0));
4235   } else {
4236     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4237                                     BitCounts, DAG.getIntPtrConstant(0));
4238     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4239   }
4240 }
4241
4242 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4243 /// bit-count for each 32-bit element from the operand.  The idea here is
4244 /// to split the vector into 16-bit elements, leverage the 16-bit count
4245 /// routine, and then combine the results.
4246 ///
4247 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4248 /// input    = [v0    v1    ] (vi: 32-bit elements)
4249 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4250 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4251 /// vrev: N0 = [k1 k0 k3 k2 ]
4252 ///            [k0 k1 k2 k3 ]
4253 ///       N1 =+[k1 k0 k3 k2 ]
4254 ///            [k0 k2 k1 k3 ]
4255 ///       N2 =+[k1 k3 k0 k2 ]
4256 ///            [k0    k2    k1    k3    ]
4257 /// Extended =+[k1    k3    k0    k2    ]
4258 ///            [k0    k2    ]
4259 /// Extracted=+[k1    k3    ]
4260 ///
4261 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4262   EVT VT = N->getValueType(0);
4263   SDLoc DL(N);
4264
4265   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4266
4267   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4268   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4269   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4270   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4271   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4272
4273   if (VT.is64BitVector()) {
4274     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4275     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4276                        DAG.getIntPtrConstant(0));
4277   } else {
4278     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4279                                     DAG.getIntPtrConstant(0));
4280     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4281   }
4282 }
4283
4284 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4285                           const ARMSubtarget *ST) {
4286   EVT VT = N->getValueType(0);
4287
4288   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4289   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4290           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4291          "Unexpected type for custom ctpop lowering");
4292
4293   if (VT.getVectorElementType() == MVT::i32)
4294     return lowerCTPOP32BitElements(N, DAG);
4295   else
4296     return lowerCTPOP16BitElements(N, DAG);
4297 }
4298
4299 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4300                           const ARMSubtarget *ST) {
4301   EVT VT = N->getValueType(0);
4302   SDLoc dl(N);
4303
4304   if (!VT.isVector())
4305     return SDValue();
4306
4307   // Lower vector shifts on NEON to use VSHL.
4308   assert(ST->hasNEON() && "unexpected vector shift");
4309
4310   // Left shifts translate directly to the vshiftu intrinsic.
4311   if (N->getOpcode() == ISD::SHL)
4312     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4313                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4314                        N->getOperand(0), N->getOperand(1));
4315
4316   assert((N->getOpcode() == ISD::SRA ||
4317           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4318
4319   // NEON uses the same intrinsics for both left and right shifts.  For
4320   // right shifts, the shift amounts are negative, so negate the vector of
4321   // shift amounts.
4322   EVT ShiftVT = N->getOperand(1).getValueType();
4323   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4324                                      getZeroVector(ShiftVT, DAG, dl),
4325                                      N->getOperand(1));
4326   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4327                              Intrinsic::arm_neon_vshifts :
4328                              Intrinsic::arm_neon_vshiftu);
4329   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4330                      DAG.getConstant(vshiftInt, MVT::i32),
4331                      N->getOperand(0), NegatedCount);
4332 }
4333
4334 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4335                                 const ARMSubtarget *ST) {
4336   EVT VT = N->getValueType(0);
4337   SDLoc dl(N);
4338
4339   // We can get here for a node like i32 = ISD::SHL i32, i64
4340   if (VT != MVT::i64)
4341     return SDValue();
4342
4343   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4344          "Unknown shift to lower!");
4345
4346   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4347   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4348       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4349     return SDValue();
4350
4351   // If we are in thumb mode, we don't have RRX.
4352   if (ST->isThumb1Only()) return SDValue();
4353
4354   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4355   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4356                            DAG.getConstant(0, MVT::i32));
4357   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4358                            DAG.getConstant(1, MVT::i32));
4359
4360   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4361   // captures the result into a carry flag.
4362   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4363   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4364
4365   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4366   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4367
4368   // Merge the pieces into a single i64 value.
4369  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4370 }
4371
4372 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4373   SDValue TmpOp0, TmpOp1;
4374   bool Invert = false;
4375   bool Swap = false;
4376   unsigned Opc = 0;
4377
4378   SDValue Op0 = Op.getOperand(0);
4379   SDValue Op1 = Op.getOperand(1);
4380   SDValue CC = Op.getOperand(2);
4381   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4382   EVT VT = Op.getValueType();
4383   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4384   SDLoc dl(Op);
4385
4386   if (Op1.getValueType().isFloatingPoint()) {
4387     switch (SetCCOpcode) {
4388     default: llvm_unreachable("Illegal FP comparison");
4389     case ISD::SETUNE:
4390     case ISD::SETNE:  Invert = true; // Fallthrough
4391     case ISD::SETOEQ:
4392     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4393     case ISD::SETOLT:
4394     case ISD::SETLT: Swap = true; // Fallthrough
4395     case ISD::SETOGT:
4396     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4397     case ISD::SETOLE:
4398     case ISD::SETLE:  Swap = true; // Fallthrough
4399     case ISD::SETOGE:
4400     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4401     case ISD::SETUGE: Swap = true; // Fallthrough
4402     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4403     case ISD::SETUGT: Swap = true; // Fallthrough
4404     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4405     case ISD::SETUEQ: Invert = true; // Fallthrough
4406     case ISD::SETONE:
4407       // Expand this to (OLT | OGT).
4408       TmpOp0 = Op0;
4409       TmpOp1 = Op1;
4410       Opc = ISD::OR;
4411       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4412       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4413       break;
4414     case ISD::SETUO: Invert = true; // Fallthrough
4415     case ISD::SETO:
4416       // Expand this to (OLT | OGE).
4417       TmpOp0 = Op0;
4418       TmpOp1 = Op1;
4419       Opc = ISD::OR;
4420       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4421       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4422       break;
4423     }
4424   } else {
4425     // Integer comparisons.
4426     switch (SetCCOpcode) {
4427     default: llvm_unreachable("Illegal integer comparison");
4428     case ISD::SETNE:  Invert = true;
4429     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4430     case ISD::SETLT:  Swap = true;
4431     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4432     case ISD::SETLE:  Swap = true;
4433     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4434     case ISD::SETULT: Swap = true;
4435     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4436     case ISD::SETULE: Swap = true;
4437     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4438     }
4439
4440     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4441     if (Opc == ARMISD::VCEQ) {
4442
4443       SDValue AndOp;
4444       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4445         AndOp = Op0;
4446       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4447         AndOp = Op1;
4448
4449       // Ignore bitconvert.
4450       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4451         AndOp = AndOp.getOperand(0);
4452
4453       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4454         Opc = ARMISD::VTST;
4455         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4456         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4457         Invert = !Invert;
4458       }
4459     }
4460   }
4461
4462   if (Swap)
4463     std::swap(Op0, Op1);
4464
4465   // If one of the operands is a constant vector zero, attempt to fold the
4466   // comparison to a specialized compare-against-zero form.
4467   SDValue SingleOp;
4468   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4469     SingleOp = Op0;
4470   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4471     if (Opc == ARMISD::VCGE)
4472       Opc = ARMISD::VCLEZ;
4473     else if (Opc == ARMISD::VCGT)
4474       Opc = ARMISD::VCLTZ;
4475     SingleOp = Op1;
4476   }
4477
4478   SDValue Result;
4479   if (SingleOp.getNode()) {
4480     switch (Opc) {
4481     case ARMISD::VCEQ:
4482       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4483     case ARMISD::VCGE:
4484       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4485     case ARMISD::VCLEZ:
4486       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4487     case ARMISD::VCGT:
4488       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4489     case ARMISD::VCLTZ:
4490       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4491     default:
4492       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4493     }
4494   } else {
4495      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4496   }
4497
4498   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4499
4500   if (Invert)
4501     Result = DAG.getNOT(dl, Result, VT);
4502
4503   return Result;
4504 }
4505
4506 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4507 /// valid vector constant for a NEON instruction with a "modified immediate"
4508 /// operand (e.g., VMOV).  If so, return the encoded value.
4509 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4510                                  unsigned SplatBitSize, SelectionDAG &DAG,
4511                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4512   unsigned OpCmode, Imm;
4513
4514   // SplatBitSize is set to the smallest size that splats the vector, so a
4515   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4516   // immediate instructions others than VMOV do not support the 8-bit encoding
4517   // of a zero vector, and the default encoding of zero is supposed to be the
4518   // 32-bit version.
4519   if (SplatBits == 0)
4520     SplatBitSize = 32;
4521
4522   switch (SplatBitSize) {
4523   case 8:
4524     if (type != VMOVModImm)
4525       return SDValue();
4526     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4527     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4528     OpCmode = 0xe;
4529     Imm = SplatBits;
4530     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4531     break;
4532
4533   case 16:
4534     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4535     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4536     if ((SplatBits & ~0xff) == 0) {
4537       // Value = 0x00nn: Op=x, Cmode=100x.
4538       OpCmode = 0x8;
4539       Imm = SplatBits;
4540       break;
4541     }
4542     if ((SplatBits & ~0xff00) == 0) {
4543       // Value = 0xnn00: Op=x, Cmode=101x.
4544       OpCmode = 0xa;
4545       Imm = SplatBits >> 8;
4546       break;
4547     }
4548     return SDValue();
4549
4550   case 32:
4551     // NEON's 32-bit VMOV supports splat values where:
4552     // * only one byte is nonzero, or
4553     // * the least significant byte is 0xff and the second byte is nonzero, or
4554     // * the least significant 2 bytes are 0xff and the third is nonzero.
4555     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4556     if ((SplatBits & ~0xff) == 0) {
4557       // Value = 0x000000nn: Op=x, Cmode=000x.
4558       OpCmode = 0;
4559       Imm = SplatBits;
4560       break;
4561     }
4562     if ((SplatBits & ~0xff00) == 0) {
4563       // Value = 0x0000nn00: Op=x, Cmode=001x.
4564       OpCmode = 0x2;
4565       Imm = SplatBits >> 8;
4566       break;
4567     }
4568     if ((SplatBits & ~0xff0000) == 0) {
4569       // Value = 0x00nn0000: Op=x, Cmode=010x.
4570       OpCmode = 0x4;
4571       Imm = SplatBits >> 16;
4572       break;
4573     }
4574     if ((SplatBits & ~0xff000000) == 0) {
4575       // Value = 0xnn000000: Op=x, Cmode=011x.
4576       OpCmode = 0x6;
4577       Imm = SplatBits >> 24;
4578       break;
4579     }
4580
4581     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4582     if (type == OtherModImm) return SDValue();
4583
4584     if ((SplatBits & ~0xffff) == 0 &&
4585         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4586       // Value = 0x0000nnff: Op=x, Cmode=1100.
4587       OpCmode = 0xc;
4588       Imm = SplatBits >> 8;
4589       break;
4590     }
4591
4592     if ((SplatBits & ~0xffffff) == 0 &&
4593         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4594       // Value = 0x00nnffff: Op=x, Cmode=1101.
4595       OpCmode = 0xd;
4596       Imm = SplatBits >> 16;
4597       break;
4598     }
4599
4600     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4601     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4602     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4603     // and fall through here to test for a valid 64-bit splat.  But, then the
4604     // caller would also need to check and handle the change in size.
4605     return SDValue();
4606
4607   case 64: {
4608     if (type != VMOVModImm)
4609       return SDValue();
4610     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4611     uint64_t BitMask = 0xff;
4612     uint64_t Val = 0;
4613     unsigned ImmMask = 1;
4614     Imm = 0;
4615     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4616       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4617         Val |= BitMask;
4618         Imm |= ImmMask;
4619       } else if ((SplatBits & BitMask) != 0) {
4620         return SDValue();
4621       }
4622       BitMask <<= 8;
4623       ImmMask <<= 1;
4624     }
4625
4626     if (DAG.getTargetLoweringInfo().isBigEndian())
4627       // swap higher and lower 32 bit word
4628       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4629
4630     // Op=1, Cmode=1110.
4631     OpCmode = 0x1e;
4632     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4633     break;
4634   }
4635
4636   default:
4637     llvm_unreachable("unexpected size for isNEONModifiedImm");
4638   }
4639
4640   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4641   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4642 }
4643
4644 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4645                                            const ARMSubtarget *ST) const {
4646   if (!ST->hasVFP3())
4647     return SDValue();
4648
4649   bool IsDouble = Op.getValueType() == MVT::f64;
4650   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4651
4652   // Use the default (constant pool) lowering for double constants when we have
4653   // an SP-only FPU
4654   if (IsDouble && Subtarget->isFPOnlySP())
4655     return SDValue();
4656
4657   // Try splatting with a VMOV.f32...
4658   APFloat FPVal = CFP->getValueAPF();
4659   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4660
4661   if (ImmVal != -1) {
4662     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4663       // We have code in place to select a valid ConstantFP already, no need to
4664       // do any mangling.
4665       return Op;
4666     }
4667
4668     // It's a float and we are trying to use NEON operations where
4669     // possible. Lower it to a splat followed by an extract.
4670     SDLoc DL(Op);
4671     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4672     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4673                                       NewVal);
4674     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4675                        DAG.getConstant(0, MVT::i32));
4676   }
4677
4678   // The rest of our options are NEON only, make sure that's allowed before
4679   // proceeding..
4680   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4681     return SDValue();
4682
4683   EVT VMovVT;
4684   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4685
4686   // It wouldn't really be worth bothering for doubles except for one very
4687   // important value, which does happen to match: 0.0. So make sure we don't do
4688   // anything stupid.
4689   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4690     return SDValue();
4691
4692   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4693   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4694                                      false, VMOVModImm);
4695   if (NewVal != SDValue()) {
4696     SDLoc DL(Op);
4697     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4698                                       NewVal);
4699     if (IsDouble)
4700       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4701
4702     // It's a float: cast and extract a vector element.
4703     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4704                                        VecConstant);
4705     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4706                        DAG.getConstant(0, MVT::i32));
4707   }
4708
4709   // Finally, try a VMVN.i32
4710   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4711                              false, VMVNModImm);
4712   if (NewVal != SDValue()) {
4713     SDLoc DL(Op);
4714     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4715
4716     if (IsDouble)
4717       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4718
4719     // It's a float: cast and extract a vector element.
4720     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4721                                        VecConstant);
4722     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4723                        DAG.getConstant(0, MVT::i32));
4724   }
4725
4726   return SDValue();
4727 }
4728
4729 // check if an VEXT instruction can handle the shuffle mask when the
4730 // vector sources of the shuffle are the same.
4731 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4732   unsigned NumElts = VT.getVectorNumElements();
4733
4734   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4735   if (M[0] < 0)
4736     return false;
4737
4738   Imm = M[0];
4739
4740   // If this is a VEXT shuffle, the immediate value is the index of the first
4741   // element.  The other shuffle indices must be the successive elements after
4742   // the first one.
4743   unsigned ExpectedElt = Imm;
4744   for (unsigned i = 1; i < NumElts; ++i) {
4745     // Increment the expected index.  If it wraps around, just follow it
4746     // back to index zero and keep going.
4747     ++ExpectedElt;
4748     if (ExpectedElt == NumElts)
4749       ExpectedElt = 0;
4750
4751     if (M[i] < 0) continue; // ignore UNDEF indices
4752     if (ExpectedElt != static_cast<unsigned>(M[i]))
4753       return false;
4754   }
4755
4756   return true;
4757 }
4758
4759
4760 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4761                        bool &ReverseVEXT, unsigned &Imm) {
4762   unsigned NumElts = VT.getVectorNumElements();
4763   ReverseVEXT = false;
4764
4765   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4766   if (M[0] < 0)
4767     return false;
4768
4769   Imm = M[0];
4770
4771   // If this is a VEXT shuffle, the immediate value is the index of the first
4772   // element.  The other shuffle indices must be the successive elements after
4773   // the first one.
4774   unsigned ExpectedElt = Imm;
4775   for (unsigned i = 1; i < NumElts; ++i) {
4776     // Increment the expected index.  If it wraps around, it may still be
4777     // a VEXT but the source vectors must be swapped.
4778     ExpectedElt += 1;
4779     if (ExpectedElt == NumElts * 2) {
4780       ExpectedElt = 0;
4781       ReverseVEXT = true;
4782     }
4783
4784     if (M[i] < 0) continue; // ignore UNDEF indices
4785     if (ExpectedElt != static_cast<unsigned>(M[i]))
4786       return false;
4787   }
4788
4789   // Adjust the index value if the source operands will be swapped.
4790   if (ReverseVEXT)
4791     Imm -= NumElts;
4792
4793   return true;
4794 }
4795
4796 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4797 /// instruction with the specified blocksize.  (The order of the elements
4798 /// within each block of the vector is reversed.)
4799 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4800   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4801          "Only possible block sizes for VREV are: 16, 32, 64");
4802
4803   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4804   if (EltSz == 64)
4805     return false;
4806
4807   unsigned NumElts = VT.getVectorNumElements();
4808   unsigned BlockElts = M[0] + 1;
4809   // If the first shuffle index is UNDEF, be optimistic.
4810   if (M[0] < 0)
4811     BlockElts = BlockSize / EltSz;
4812
4813   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4814     return false;
4815
4816   for (unsigned i = 0; i < NumElts; ++i) {
4817     if (M[i] < 0) continue; // ignore UNDEF indices
4818     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4819       return false;
4820   }
4821
4822   return true;
4823 }
4824
4825 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4826   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4827   // range, then 0 is placed into the resulting vector. So pretty much any mask
4828   // of 8 elements can work here.
4829   return VT == MVT::v8i8 && M.size() == 8;
4830 }
4831
4832 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4833   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4834   if (EltSz == 64)
4835     return false;
4836
4837   unsigned NumElts = VT.getVectorNumElements();
4838   WhichResult = (M[0] == 0 ? 0 : 1);
4839   for (unsigned i = 0; i < NumElts; i += 2) {
4840     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4841         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4842       return false;
4843   }
4844   return true;
4845 }
4846
4847 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4848 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4849 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4850 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4851   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4852   if (EltSz == 64)
4853     return false;
4854
4855   unsigned NumElts = VT.getVectorNumElements();
4856   WhichResult = (M[0] == 0 ? 0 : 1);
4857   for (unsigned i = 0; i < NumElts; i += 2) {
4858     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4859         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4860       return false;
4861   }
4862   return true;
4863 }
4864
4865 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4866   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4867   if (EltSz == 64)
4868     return false;
4869
4870   unsigned NumElts = VT.getVectorNumElements();
4871   WhichResult = (M[0] == 0 ? 0 : 1);
4872   for (unsigned i = 0; i != NumElts; ++i) {
4873     if (M[i] < 0) continue; // ignore UNDEF indices
4874     if ((unsigned) M[i] != 2 * i + WhichResult)
4875       return false;
4876   }
4877
4878   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4879   if (VT.is64BitVector() && EltSz == 32)
4880     return false;
4881
4882   return true;
4883 }
4884
4885 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4886 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4887 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4888 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4889   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4890   if (EltSz == 64)
4891     return false;
4892
4893   unsigned Half = VT.getVectorNumElements() / 2;
4894   WhichResult = (M[0] == 0 ? 0 : 1);
4895   for (unsigned j = 0; j != 2; ++j) {
4896     unsigned Idx = WhichResult;
4897     for (unsigned i = 0; i != Half; ++i) {
4898       int MIdx = M[i + j * Half];
4899       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4900         return false;
4901       Idx += 2;
4902     }
4903   }
4904
4905   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4906   if (VT.is64BitVector() && EltSz == 32)
4907     return false;
4908
4909   return true;
4910 }
4911
4912 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4913   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4914   if (EltSz == 64)
4915     return false;
4916
4917   unsigned NumElts = VT.getVectorNumElements();
4918   WhichResult = (M[0] == 0 ? 0 : 1);
4919   unsigned Idx = WhichResult * NumElts / 2;
4920   for (unsigned i = 0; i != NumElts; i += 2) {
4921     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4922         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4923       return false;
4924     Idx += 1;
4925   }
4926
4927   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4928   if (VT.is64BitVector() && EltSz == 32)
4929     return false;
4930
4931   return true;
4932 }
4933
4934 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4935 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4936 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4937 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4938   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4939   if (EltSz == 64)
4940     return false;
4941
4942   unsigned NumElts = VT.getVectorNumElements();
4943   WhichResult = (M[0] == 0 ? 0 : 1);
4944   unsigned Idx = WhichResult * NumElts / 2;
4945   for (unsigned i = 0; i != NumElts; i += 2) {
4946     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4947         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4948       return false;
4949     Idx += 1;
4950   }
4951
4952   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4953   if (VT.is64BitVector() && EltSz == 32)
4954     return false;
4955
4956   return true;
4957 }
4958
4959 /// \return true if this is a reverse operation on an vector.
4960 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4961   unsigned NumElts = VT.getVectorNumElements();
4962   // Make sure the mask has the right size.
4963   if (NumElts != M.size())
4964       return false;
4965
4966   // Look for <15, ..., 3, -1, 1, 0>.
4967   for (unsigned i = 0; i != NumElts; ++i)
4968     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4969       return false;
4970
4971   return true;
4972 }
4973
4974 // If N is an integer constant that can be moved into a register in one
4975 // instruction, return an SDValue of such a constant (will become a MOV
4976 // instruction).  Otherwise return null.
4977 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4978                                      const ARMSubtarget *ST, SDLoc dl) {
4979   uint64_t Val;
4980   if (!isa<ConstantSDNode>(N))
4981     return SDValue();
4982   Val = cast<ConstantSDNode>(N)->getZExtValue();
4983
4984   if (ST->isThumb1Only()) {
4985     if (Val <= 255 || ~Val <= 255)
4986       return DAG.getConstant(Val, MVT::i32);
4987   } else {
4988     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4989       return DAG.getConstant(Val, MVT::i32);
4990   }
4991   return SDValue();
4992 }
4993
4994 // If this is a case we can't handle, return null and let the default
4995 // expansion code take care of it.
4996 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4997                                              const ARMSubtarget *ST) const {
4998   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4999   SDLoc dl(Op);
5000   EVT VT = Op.getValueType();
5001
5002   APInt SplatBits, SplatUndef;
5003   unsigned SplatBitSize;
5004   bool HasAnyUndefs;
5005   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5006     if (SplatBitSize <= 64) {
5007       // Check if an immediate VMOV works.
5008       EVT VmovVT;
5009       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5010                                       SplatUndef.getZExtValue(), SplatBitSize,
5011                                       DAG, VmovVT, VT.is128BitVector(),
5012                                       VMOVModImm);
5013       if (Val.getNode()) {
5014         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5015         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5016       }
5017
5018       // Try an immediate VMVN.
5019       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5020       Val = isNEONModifiedImm(NegatedImm,
5021                                       SplatUndef.getZExtValue(), SplatBitSize,
5022                                       DAG, VmovVT, VT.is128BitVector(),
5023                                       VMVNModImm);
5024       if (Val.getNode()) {
5025         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5026         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5027       }
5028
5029       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5030       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5031         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5032         if (ImmVal != -1) {
5033           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5034           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5035         }
5036       }
5037     }
5038   }
5039
5040   // Scan through the operands to see if only one value is used.
5041   //
5042   // As an optimisation, even if more than one value is used it may be more
5043   // profitable to splat with one value then change some lanes.
5044   //
5045   // Heuristically we decide to do this if the vector has a "dominant" value,
5046   // defined as splatted to more than half of the lanes.
5047   unsigned NumElts = VT.getVectorNumElements();
5048   bool isOnlyLowElement = true;
5049   bool usesOnlyOneValue = true;
5050   bool hasDominantValue = false;
5051   bool isConstant = true;
5052
5053   // Map of the number of times a particular SDValue appears in the
5054   // element list.
5055   DenseMap<SDValue, unsigned> ValueCounts;
5056   SDValue Value;
5057   for (unsigned i = 0; i < NumElts; ++i) {
5058     SDValue V = Op.getOperand(i);
5059     if (V.getOpcode() == ISD::UNDEF)
5060       continue;
5061     if (i > 0)
5062       isOnlyLowElement = false;
5063     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5064       isConstant = false;
5065
5066     ValueCounts.insert(std::make_pair(V, 0));
5067     unsigned &Count = ValueCounts[V];
5068
5069     // Is this value dominant? (takes up more than half of the lanes)
5070     if (++Count > (NumElts / 2)) {
5071       hasDominantValue = true;
5072       Value = V;
5073     }
5074   }
5075   if (ValueCounts.size() != 1)
5076     usesOnlyOneValue = false;
5077   if (!Value.getNode() && ValueCounts.size() > 0)
5078     Value = ValueCounts.begin()->first;
5079
5080   if (ValueCounts.size() == 0)
5081     return DAG.getUNDEF(VT);
5082
5083   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5084   // Keep going if we are hitting this case.
5085   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5086     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5087
5088   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5089
5090   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5091   // i32 and try again.
5092   if (hasDominantValue && EltSize <= 32) {
5093     if (!isConstant) {
5094       SDValue N;
5095
5096       // If we are VDUPing a value that comes directly from a vector, that will
5097       // cause an unnecessary move to and from a GPR, where instead we could
5098       // just use VDUPLANE. We can only do this if the lane being extracted
5099       // is at a constant index, as the VDUP from lane instructions only have
5100       // constant-index forms.
5101       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5102           isa<ConstantSDNode>(Value->getOperand(1))) {
5103         // We need to create a new undef vector to use for the VDUPLANE if the
5104         // size of the vector from which we get the value is different than the
5105         // size of the vector that we need to create. We will insert the element
5106         // such that the register coalescer will remove unnecessary copies.
5107         if (VT != Value->getOperand(0).getValueType()) {
5108           ConstantSDNode *constIndex;
5109           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5110           assert(constIndex && "The index is not a constant!");
5111           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5112                              VT.getVectorNumElements();
5113           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5114                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5115                         Value, DAG.getConstant(index, MVT::i32)),
5116                            DAG.getConstant(index, MVT::i32));
5117         } else
5118           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5119                         Value->getOperand(0), Value->getOperand(1));
5120       } else
5121         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5122
5123       if (!usesOnlyOneValue) {
5124         // The dominant value was splatted as 'N', but we now have to insert
5125         // all differing elements.
5126         for (unsigned I = 0; I < NumElts; ++I) {
5127           if (Op.getOperand(I) == Value)
5128             continue;
5129           SmallVector<SDValue, 3> Ops;
5130           Ops.push_back(N);
5131           Ops.push_back(Op.getOperand(I));
5132           Ops.push_back(DAG.getConstant(I, MVT::i32));
5133           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5134         }
5135       }
5136       return N;
5137     }
5138     if (VT.getVectorElementType().isFloatingPoint()) {
5139       SmallVector<SDValue, 8> Ops;
5140       for (unsigned i = 0; i < NumElts; ++i)
5141         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5142                                   Op.getOperand(i)));
5143       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5144       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5145       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5146       if (Val.getNode())
5147         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5148     }
5149     if (usesOnlyOneValue) {
5150       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5151       if (isConstant && Val.getNode())
5152         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5153     }
5154   }
5155
5156   // If all elements are constants and the case above didn't get hit, fall back
5157   // to the default expansion, which will generate a load from the constant
5158   // pool.
5159   if (isConstant)
5160     return SDValue();
5161
5162   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5163   if (NumElts >= 4) {
5164     SDValue shuffle = ReconstructShuffle(Op, DAG);
5165     if (shuffle != SDValue())
5166       return shuffle;
5167   }
5168
5169   // Vectors with 32- or 64-bit elements can be built by directly assigning
5170   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5171   // will be legalized.
5172   if (EltSize >= 32) {
5173     // Do the expansion with floating-point types, since that is what the VFP
5174     // registers are defined to use, and since i64 is not legal.
5175     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5176     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5177     SmallVector<SDValue, 8> Ops;
5178     for (unsigned i = 0; i < NumElts; ++i)
5179       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5180     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5181     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5182   }
5183
5184   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5185   // know the default expansion would otherwise fall back on something even
5186   // worse. For a vector with one or two non-undef values, that's
5187   // scalar_to_vector for the elements followed by a shuffle (provided the
5188   // shuffle is valid for the target) and materialization element by element
5189   // on the stack followed by a load for everything else.
5190   if (!isConstant && !usesOnlyOneValue) {
5191     SDValue Vec = DAG.getUNDEF(VT);
5192     for (unsigned i = 0 ; i < NumElts; ++i) {
5193       SDValue V = Op.getOperand(i);
5194       if (V.getOpcode() == ISD::UNDEF)
5195         continue;
5196       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5197       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5198     }
5199     return Vec;
5200   }
5201
5202   return SDValue();
5203 }
5204
5205 // Gather data to see if the operation can be modelled as a
5206 // shuffle in combination with VEXTs.
5207 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5208                                               SelectionDAG &DAG) const {
5209   SDLoc dl(Op);
5210   EVT VT = Op.getValueType();
5211   unsigned NumElts = VT.getVectorNumElements();
5212
5213   SmallVector<SDValue, 2> SourceVecs;
5214   SmallVector<unsigned, 2> MinElts;
5215   SmallVector<unsigned, 2> MaxElts;
5216
5217   for (unsigned i = 0; i < NumElts; ++i) {
5218     SDValue V = Op.getOperand(i);
5219     if (V.getOpcode() == ISD::UNDEF)
5220       continue;
5221     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5222       // A shuffle can only come from building a vector from various
5223       // elements of other vectors.
5224       return SDValue();
5225     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5226                VT.getVectorElementType()) {
5227       // This code doesn't know how to handle shuffles where the vector
5228       // element types do not match (this happens because type legalization
5229       // promotes the return type of EXTRACT_VECTOR_ELT).
5230       // FIXME: It might be appropriate to extend this code to handle
5231       // mismatched types.
5232       return SDValue();
5233     }
5234
5235     // Record this extraction against the appropriate vector if possible...
5236     SDValue SourceVec = V.getOperand(0);
5237     // If the element number isn't a constant, we can't effectively
5238     // analyze what's going on.
5239     if (!isa<ConstantSDNode>(V.getOperand(1)))
5240       return SDValue();
5241     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5242     bool FoundSource = false;
5243     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5244       if (SourceVecs[j] == SourceVec) {
5245         if (MinElts[j] > EltNo)
5246           MinElts[j] = EltNo;
5247         if (MaxElts[j] < EltNo)
5248           MaxElts[j] = EltNo;
5249         FoundSource = true;
5250         break;
5251       }
5252     }
5253
5254     // Or record a new source if not...
5255     if (!FoundSource) {
5256       SourceVecs.push_back(SourceVec);
5257       MinElts.push_back(EltNo);
5258       MaxElts.push_back(EltNo);
5259     }
5260   }
5261
5262   // Currently only do something sane when at most two source vectors
5263   // involved.
5264   if (SourceVecs.size() > 2)
5265     return SDValue();
5266
5267   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5268   int VEXTOffsets[2] = {0, 0};
5269
5270   // This loop extracts the usage patterns of the source vectors
5271   // and prepares appropriate SDValues for a shuffle if possible.
5272   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5273     if (SourceVecs[i].getValueType() == VT) {
5274       // No VEXT necessary
5275       ShuffleSrcs[i] = SourceVecs[i];
5276       VEXTOffsets[i] = 0;
5277       continue;
5278     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5279       // It probably isn't worth padding out a smaller vector just to
5280       // break it down again in a shuffle.
5281       return SDValue();
5282     }
5283
5284     // Since only 64-bit and 128-bit vectors are legal on ARM and
5285     // we've eliminated the other cases...
5286     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5287            "unexpected vector sizes in ReconstructShuffle");
5288
5289     if (MaxElts[i] - MinElts[i] >= NumElts) {
5290       // Span too large for a VEXT to cope
5291       return SDValue();
5292     }
5293
5294     if (MinElts[i] >= NumElts) {
5295       // The extraction can just take the second half
5296       VEXTOffsets[i] = NumElts;
5297       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5298                                    SourceVecs[i],
5299                                    DAG.getIntPtrConstant(NumElts));
5300     } else if (MaxElts[i] < NumElts) {
5301       // The extraction can just take the first half
5302       VEXTOffsets[i] = 0;
5303       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5304                                    SourceVecs[i],
5305                                    DAG.getIntPtrConstant(0));
5306     } else {
5307       // An actual VEXT is needed
5308       VEXTOffsets[i] = MinElts[i];
5309       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5310                                      SourceVecs[i],
5311                                      DAG.getIntPtrConstant(0));
5312       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5313                                      SourceVecs[i],
5314                                      DAG.getIntPtrConstant(NumElts));
5315       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5316                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5317     }
5318   }
5319
5320   SmallVector<int, 8> Mask;
5321
5322   for (unsigned i = 0; i < NumElts; ++i) {
5323     SDValue Entry = Op.getOperand(i);
5324     if (Entry.getOpcode() == ISD::UNDEF) {
5325       Mask.push_back(-1);
5326       continue;
5327     }
5328
5329     SDValue ExtractVec = Entry.getOperand(0);
5330     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5331                                           .getOperand(1))->getSExtValue();
5332     if (ExtractVec == SourceVecs[0]) {
5333       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5334     } else {
5335       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5336     }
5337   }
5338
5339   // Final check before we try to produce nonsense...
5340   if (isShuffleMaskLegal(Mask, VT))
5341     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5342                                 &Mask[0]);
5343
5344   return SDValue();
5345 }
5346
5347 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5348 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5349 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5350 /// are assumed to be legal.
5351 bool
5352 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5353                                       EVT VT) const {
5354   if (VT.getVectorNumElements() == 4 &&
5355       (VT.is128BitVector() || VT.is64BitVector())) {
5356     unsigned PFIndexes[4];
5357     for (unsigned i = 0; i != 4; ++i) {
5358       if (M[i] < 0)
5359         PFIndexes[i] = 8;
5360       else
5361         PFIndexes[i] = M[i];
5362     }
5363
5364     // Compute the index in the perfect shuffle table.
5365     unsigned PFTableIndex =
5366       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5367     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5368     unsigned Cost = (PFEntry >> 30);
5369
5370     if (Cost <= 4)
5371       return true;
5372   }
5373
5374   bool ReverseVEXT;
5375   unsigned Imm, WhichResult;
5376
5377   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5378   return (EltSize >= 32 ||
5379           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5380           isVREVMask(M, VT, 64) ||
5381           isVREVMask(M, VT, 32) ||
5382           isVREVMask(M, VT, 16) ||
5383           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5384           isVTBLMask(M, VT) ||
5385           isVTRNMask(M, VT, WhichResult) ||
5386           isVUZPMask(M, VT, WhichResult) ||
5387           isVZIPMask(M, VT, WhichResult) ||
5388           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5389           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5390           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5391           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5392 }
5393
5394 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5395 /// the specified operations to build the shuffle.
5396 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5397                                       SDValue RHS, SelectionDAG &DAG,
5398                                       SDLoc dl) {
5399   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5400   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5401   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5402
5403   enum {
5404     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5405     OP_VREV,
5406     OP_VDUP0,
5407     OP_VDUP1,
5408     OP_VDUP2,
5409     OP_VDUP3,
5410     OP_VEXT1,
5411     OP_VEXT2,
5412     OP_VEXT3,
5413     OP_VUZPL, // VUZP, left result
5414     OP_VUZPR, // VUZP, right result
5415     OP_VZIPL, // VZIP, left result
5416     OP_VZIPR, // VZIP, right result
5417     OP_VTRNL, // VTRN, left result
5418     OP_VTRNR  // VTRN, right result
5419   };
5420
5421   if (OpNum == OP_COPY) {
5422     if (LHSID == (1*9+2)*9+3) return LHS;
5423     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5424     return RHS;
5425   }
5426
5427   SDValue OpLHS, OpRHS;
5428   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5429   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5430   EVT VT = OpLHS.getValueType();
5431
5432   switch (OpNum) {
5433   default: llvm_unreachable("Unknown shuffle opcode!");
5434   case OP_VREV:
5435     // VREV divides the vector in half and swaps within the half.
5436     if (VT.getVectorElementType() == MVT::i32 ||
5437         VT.getVectorElementType() == MVT::f32)
5438       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5439     // vrev <4 x i16> -> VREV32
5440     if (VT.getVectorElementType() == MVT::i16)
5441       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5442     // vrev <4 x i8> -> VREV16
5443     assert(VT.getVectorElementType() == MVT::i8);
5444     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5445   case OP_VDUP0:
5446   case OP_VDUP1:
5447   case OP_VDUP2:
5448   case OP_VDUP3:
5449     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5450                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5451   case OP_VEXT1:
5452   case OP_VEXT2:
5453   case OP_VEXT3:
5454     return DAG.getNode(ARMISD::VEXT, dl, VT,
5455                        OpLHS, OpRHS,
5456                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5457   case OP_VUZPL:
5458   case OP_VUZPR:
5459     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5460                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5461   case OP_VZIPL:
5462   case OP_VZIPR:
5463     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5464                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5465   case OP_VTRNL:
5466   case OP_VTRNR:
5467     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5468                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5469   }
5470 }
5471
5472 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5473                                        ArrayRef<int> ShuffleMask,
5474                                        SelectionDAG &DAG) {
5475   // Check to see if we can use the VTBL instruction.
5476   SDValue V1 = Op.getOperand(0);
5477   SDValue V2 = Op.getOperand(1);
5478   SDLoc DL(Op);
5479
5480   SmallVector<SDValue, 8> VTBLMask;
5481   for (ArrayRef<int>::iterator
5482          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5483     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5484
5485   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5486     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5487                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5488
5489   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5490                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5491 }
5492
5493 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5494                                                       SelectionDAG &DAG) {
5495   SDLoc DL(Op);
5496   SDValue OpLHS = Op.getOperand(0);
5497   EVT VT = OpLHS.getValueType();
5498
5499   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5500          "Expect an v8i16/v16i8 type");
5501   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5502   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5503   // extract the first 8 bytes into the top double word and the last 8 bytes
5504   // into the bottom double word. The v8i16 case is similar.
5505   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5506   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5507                      DAG.getConstant(ExtractNum, MVT::i32));
5508 }
5509
5510 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5511   SDValue V1 = Op.getOperand(0);
5512   SDValue V2 = Op.getOperand(1);
5513   SDLoc dl(Op);
5514   EVT VT = Op.getValueType();
5515   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5516
5517   // Convert shuffles that are directly supported on NEON to target-specific
5518   // DAG nodes, instead of keeping them as shuffles and matching them again
5519   // during code selection.  This is more efficient and avoids the possibility
5520   // of inconsistencies between legalization and selection.
5521   // FIXME: floating-point vectors should be canonicalized to integer vectors
5522   // of the same time so that they get CSEd properly.
5523   ArrayRef<int> ShuffleMask = SVN->getMask();
5524
5525   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5526   if (EltSize <= 32) {
5527     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5528       int Lane = SVN->getSplatIndex();
5529       // If this is undef splat, generate it via "just" vdup, if possible.
5530       if (Lane == -1) Lane = 0;
5531
5532       // Test if V1 is a SCALAR_TO_VECTOR.
5533       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5534         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5535       }
5536       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5537       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5538       // reaches it).
5539       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5540           !isa<ConstantSDNode>(V1.getOperand(0))) {
5541         bool IsScalarToVector = true;
5542         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5543           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5544             IsScalarToVector = false;
5545             break;
5546           }
5547         if (IsScalarToVector)
5548           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5549       }
5550       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5551                          DAG.getConstant(Lane, MVT::i32));
5552     }
5553
5554     bool ReverseVEXT;
5555     unsigned Imm;
5556     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5557       if (ReverseVEXT)
5558         std::swap(V1, V2);
5559       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5560                          DAG.getConstant(Imm, MVT::i32));
5561     }
5562
5563     if (isVREVMask(ShuffleMask, VT, 64))
5564       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5565     if (isVREVMask(ShuffleMask, VT, 32))
5566       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5567     if (isVREVMask(ShuffleMask, VT, 16))
5568       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5569
5570     if (V2->getOpcode() == ISD::UNDEF &&
5571         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5572       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5573                          DAG.getConstant(Imm, MVT::i32));
5574     }
5575
5576     // Check for Neon shuffles that modify both input vectors in place.
5577     // If both results are used, i.e., if there are two shuffles with the same
5578     // source operands and with masks corresponding to both results of one of
5579     // these operations, DAG memoization will ensure that a single node is
5580     // used for both shuffles.
5581     unsigned WhichResult;
5582     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5583       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5584                          V1, V2).getValue(WhichResult);
5585     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5586       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5587                          V1, V2).getValue(WhichResult);
5588     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5589       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5590                          V1, V2).getValue(WhichResult);
5591
5592     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5593       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5594                          V1, V1).getValue(WhichResult);
5595     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5596       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5597                          V1, V1).getValue(WhichResult);
5598     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5599       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5600                          V1, V1).getValue(WhichResult);
5601   }
5602
5603   // If the shuffle is not directly supported and it has 4 elements, use
5604   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5605   unsigned NumElts = VT.getVectorNumElements();
5606   if (NumElts == 4) {
5607     unsigned PFIndexes[4];
5608     for (unsigned i = 0; i != 4; ++i) {
5609       if (ShuffleMask[i] < 0)
5610         PFIndexes[i] = 8;
5611       else
5612         PFIndexes[i] = ShuffleMask[i];
5613     }
5614
5615     // Compute the index in the perfect shuffle table.
5616     unsigned PFTableIndex =
5617       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5618     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5619     unsigned Cost = (PFEntry >> 30);
5620
5621     if (Cost <= 4)
5622       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5623   }
5624
5625   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5626   if (EltSize >= 32) {
5627     // Do the expansion with floating-point types, since that is what the VFP
5628     // registers are defined to use, and since i64 is not legal.
5629     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5630     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5631     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5632     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5633     SmallVector<SDValue, 8> Ops;
5634     for (unsigned i = 0; i < NumElts; ++i) {
5635       if (ShuffleMask[i] < 0)
5636         Ops.push_back(DAG.getUNDEF(EltVT));
5637       else
5638         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5639                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5640                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5641                                                   MVT::i32)));
5642     }
5643     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5644     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5645   }
5646
5647   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5648     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5649
5650   if (VT == MVT::v8i8) {
5651     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5652     if (NewOp.getNode())
5653       return NewOp;
5654   }
5655
5656   return SDValue();
5657 }
5658
5659 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5660   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5661   SDValue Lane = Op.getOperand(2);
5662   if (!isa<ConstantSDNode>(Lane))
5663     return SDValue();
5664
5665   return Op;
5666 }
5667
5668 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5669   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5670   SDValue Lane = Op.getOperand(1);
5671   if (!isa<ConstantSDNode>(Lane))
5672     return SDValue();
5673
5674   SDValue Vec = Op.getOperand(0);
5675   if (Op.getValueType() == MVT::i32 &&
5676       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5677     SDLoc dl(Op);
5678     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5679   }
5680
5681   return Op;
5682 }
5683
5684 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5685   // The only time a CONCAT_VECTORS operation can have legal types is when
5686   // two 64-bit vectors are concatenated to a 128-bit vector.
5687   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5688          "unexpected CONCAT_VECTORS");
5689   SDLoc dl(Op);
5690   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5691   SDValue Op0 = Op.getOperand(0);
5692   SDValue Op1 = Op.getOperand(1);
5693   if (Op0.getOpcode() != ISD::UNDEF)
5694     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5695                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5696                       DAG.getIntPtrConstant(0));
5697   if (Op1.getOpcode() != ISD::UNDEF)
5698     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5699                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5700                       DAG.getIntPtrConstant(1));
5701   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5702 }
5703
5704 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5705 /// element has been zero/sign-extended, depending on the isSigned parameter,
5706 /// from an integer type half its size.
5707 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5708                                    bool isSigned) {
5709   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5710   EVT VT = N->getValueType(0);
5711   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5712     SDNode *BVN = N->getOperand(0).getNode();
5713     if (BVN->getValueType(0) != MVT::v4i32 ||
5714         BVN->getOpcode() != ISD::BUILD_VECTOR)
5715       return false;
5716     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5717     unsigned HiElt = 1 - LoElt;
5718     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5719     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5720     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5721     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5722     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5723       return false;
5724     if (isSigned) {
5725       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5726           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5727         return true;
5728     } else {
5729       if (Hi0->isNullValue() && Hi1->isNullValue())
5730         return true;
5731     }
5732     return false;
5733   }
5734
5735   if (N->getOpcode() != ISD::BUILD_VECTOR)
5736     return false;
5737
5738   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5739     SDNode *Elt = N->getOperand(i).getNode();
5740     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5741       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5742       unsigned HalfSize = EltSize / 2;
5743       if (isSigned) {
5744         if (!isIntN(HalfSize, C->getSExtValue()))
5745           return false;
5746       } else {
5747         if (!isUIntN(HalfSize, C->getZExtValue()))
5748           return false;
5749       }
5750       continue;
5751     }
5752     return false;
5753   }
5754
5755   return true;
5756 }
5757
5758 /// isSignExtended - Check if a node is a vector value that is sign-extended
5759 /// or a constant BUILD_VECTOR with sign-extended elements.
5760 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5761   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5762     return true;
5763   if (isExtendedBUILD_VECTOR(N, DAG, true))
5764     return true;
5765   return false;
5766 }
5767
5768 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5769 /// or a constant BUILD_VECTOR with zero-extended elements.
5770 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5771   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5772     return true;
5773   if (isExtendedBUILD_VECTOR(N, DAG, false))
5774     return true;
5775   return false;
5776 }
5777
5778 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5779   if (OrigVT.getSizeInBits() >= 64)
5780     return OrigVT;
5781
5782   assert(OrigVT.isSimple() && "Expecting a simple value type");
5783
5784   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5785   switch (OrigSimpleTy) {
5786   default: llvm_unreachable("Unexpected Vector Type");
5787   case MVT::v2i8:
5788   case MVT::v2i16:
5789      return MVT::v2i32;
5790   case MVT::v4i8:
5791     return  MVT::v4i16;
5792   }
5793 }
5794
5795 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5796 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5797 /// We insert the required extension here to get the vector to fill a D register.
5798 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5799                                             const EVT &OrigTy,
5800                                             const EVT &ExtTy,
5801                                             unsigned ExtOpcode) {
5802   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5803   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5804   // 64-bits we need to insert a new extension so that it will be 64-bits.
5805   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5806   if (OrigTy.getSizeInBits() >= 64)
5807     return N;
5808
5809   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5810   EVT NewVT = getExtensionTo64Bits(OrigTy);
5811
5812   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5813 }
5814
5815 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5816 /// does not do any sign/zero extension. If the original vector is less
5817 /// than 64 bits, an appropriate extension will be added after the load to
5818 /// reach a total size of 64 bits. We have to add the extension separately
5819 /// because ARM does not have a sign/zero extending load for vectors.
5820 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5821   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5822
5823   // The load already has the right type.
5824   if (ExtendedTy == LD->getMemoryVT())
5825     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5826                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5827                 LD->isNonTemporal(), LD->isInvariant(),
5828                 LD->getAlignment());
5829
5830   // We need to create a zextload/sextload. We cannot just create a load
5831   // followed by a zext/zext node because LowerMUL is also run during normal
5832   // operation legalization where we can't create illegal types.
5833   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5834                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5835                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5836                         LD->isNonTemporal(), LD->getAlignment());
5837 }
5838
5839 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5840 /// extending load, or BUILD_VECTOR with extended elements, return the
5841 /// unextended value. The unextended vector should be 64 bits so that it can
5842 /// be used as an operand to a VMULL instruction. If the original vector size
5843 /// before extension is less than 64 bits we add a an extension to resize
5844 /// the vector to 64 bits.
5845 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5846   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5847     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5848                                         N->getOperand(0)->getValueType(0),
5849                                         N->getValueType(0),
5850                                         N->getOpcode());
5851
5852   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5853     return SkipLoadExtensionForVMULL(LD, DAG);
5854
5855   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5856   // have been legalized as a BITCAST from v4i32.
5857   if (N->getOpcode() == ISD::BITCAST) {
5858     SDNode *BVN = N->getOperand(0).getNode();
5859     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5860            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5861     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5862     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5863                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5864   }
5865   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5866   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5867   EVT VT = N->getValueType(0);
5868   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5869   unsigned NumElts = VT.getVectorNumElements();
5870   MVT TruncVT = MVT::getIntegerVT(EltSize);
5871   SmallVector<SDValue, 8> Ops;
5872   for (unsigned i = 0; i != NumElts; ++i) {
5873     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5874     const APInt &CInt = C->getAPIntValue();
5875     // Element types smaller than 32 bits are not legal, so use i32 elements.
5876     // The values are implicitly truncated so sext vs. zext doesn't matter.
5877     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5878   }
5879   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5880                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5881 }
5882
5883 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5884   unsigned Opcode = N->getOpcode();
5885   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5886     SDNode *N0 = N->getOperand(0).getNode();
5887     SDNode *N1 = N->getOperand(1).getNode();
5888     return N0->hasOneUse() && N1->hasOneUse() &&
5889       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5890   }
5891   return false;
5892 }
5893
5894 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5895   unsigned Opcode = N->getOpcode();
5896   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5897     SDNode *N0 = N->getOperand(0).getNode();
5898     SDNode *N1 = N->getOperand(1).getNode();
5899     return N0->hasOneUse() && N1->hasOneUse() &&
5900       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5901   }
5902   return false;
5903 }
5904
5905 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5906   // Multiplications are only custom-lowered for 128-bit vectors so that
5907   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5908   EVT VT = Op.getValueType();
5909   assert(VT.is128BitVector() && VT.isInteger() &&
5910          "unexpected type for custom-lowering ISD::MUL");
5911   SDNode *N0 = Op.getOperand(0).getNode();
5912   SDNode *N1 = Op.getOperand(1).getNode();
5913   unsigned NewOpc = 0;
5914   bool isMLA = false;
5915   bool isN0SExt = isSignExtended(N0, DAG);
5916   bool isN1SExt = isSignExtended(N1, DAG);
5917   if (isN0SExt && isN1SExt)
5918     NewOpc = ARMISD::VMULLs;
5919   else {
5920     bool isN0ZExt = isZeroExtended(N0, DAG);
5921     bool isN1ZExt = isZeroExtended(N1, DAG);
5922     if (isN0ZExt && isN1ZExt)
5923       NewOpc = ARMISD::VMULLu;
5924     else if (isN1SExt || isN1ZExt) {
5925       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5926       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5927       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5928         NewOpc = ARMISD::VMULLs;
5929         isMLA = true;
5930       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5931         NewOpc = ARMISD::VMULLu;
5932         isMLA = true;
5933       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5934         std::swap(N0, N1);
5935         NewOpc = ARMISD::VMULLu;
5936         isMLA = true;
5937       }
5938     }
5939
5940     if (!NewOpc) {
5941       if (VT == MVT::v2i64)
5942         // Fall through to expand this.  It is not legal.
5943         return SDValue();
5944       else
5945         // Other vector multiplications are legal.
5946         return Op;
5947     }
5948   }
5949
5950   // Legalize to a VMULL instruction.
5951   SDLoc DL(Op);
5952   SDValue Op0;
5953   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5954   if (!isMLA) {
5955     Op0 = SkipExtensionForVMULL(N0, DAG);
5956     assert(Op0.getValueType().is64BitVector() &&
5957            Op1.getValueType().is64BitVector() &&
5958            "unexpected types for extended operands to VMULL");
5959     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5960   }
5961
5962   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5963   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5964   //   vmull q0, d4, d6
5965   //   vmlal q0, d5, d6
5966   // is faster than
5967   //   vaddl q0, d4, d5
5968   //   vmovl q1, d6
5969   //   vmul  q0, q0, q1
5970   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5971   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5972   EVT Op1VT = Op1.getValueType();
5973   return DAG.getNode(N0->getOpcode(), DL, VT,
5974                      DAG.getNode(NewOpc, DL, VT,
5975                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5976                      DAG.getNode(NewOpc, DL, VT,
5977                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5978 }
5979
5980 static SDValue
5981 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5982   // Convert to float
5983   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5984   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5985   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5986   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5987   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5988   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5989   // Get reciprocal estimate.
5990   // float4 recip = vrecpeq_f32(yf);
5991   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5992                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5993   // Because char has a smaller range than uchar, we can actually get away
5994   // without any newton steps.  This requires that we use a weird bias
5995   // of 0xb000, however (again, this has been exhaustively tested).
5996   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5997   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5998   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5999   Y = DAG.getConstant(0xb000, MVT::i32);
6000   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6001   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6002   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6003   // Convert back to short.
6004   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6005   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6006   return X;
6007 }
6008
6009 static SDValue
6010 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6011   SDValue N2;
6012   // Convert to float.
6013   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6014   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6015   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6016   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6017   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6018   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6019
6020   // Use reciprocal estimate and one refinement step.
6021   // float4 recip = vrecpeq_f32(yf);
6022   // recip *= vrecpsq_f32(yf, recip);
6023   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6024                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6025   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6026                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6027                    N1, N2);
6028   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6029   // Because short has a smaller range than ushort, we can actually get away
6030   // with only a single newton step.  This requires that we use a weird bias
6031   // of 89, however (again, this has been exhaustively tested).
6032   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6033   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6034   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6035   N1 = DAG.getConstant(0x89, MVT::i32);
6036   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6037   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6038   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6039   // Convert back to integer and return.
6040   // return vmovn_s32(vcvt_s32_f32(result));
6041   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6042   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6043   return N0;
6044 }
6045
6046 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6047   EVT VT = Op.getValueType();
6048   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6049          "unexpected type for custom-lowering ISD::SDIV");
6050
6051   SDLoc dl(Op);
6052   SDValue N0 = Op.getOperand(0);
6053   SDValue N1 = Op.getOperand(1);
6054   SDValue N2, N3;
6055
6056   if (VT == MVT::v8i8) {
6057     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6058     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6059
6060     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6061                      DAG.getIntPtrConstant(4));
6062     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6063                      DAG.getIntPtrConstant(4));
6064     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6065                      DAG.getIntPtrConstant(0));
6066     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6067                      DAG.getIntPtrConstant(0));
6068
6069     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6070     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6071
6072     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6073     N0 = LowerCONCAT_VECTORS(N0, DAG);
6074
6075     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6076     return N0;
6077   }
6078   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6079 }
6080
6081 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6082   EVT VT = Op.getValueType();
6083   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6084          "unexpected type for custom-lowering ISD::UDIV");
6085
6086   SDLoc dl(Op);
6087   SDValue N0 = Op.getOperand(0);
6088   SDValue N1 = Op.getOperand(1);
6089   SDValue N2, N3;
6090
6091   if (VT == MVT::v8i8) {
6092     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6093     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6094
6095     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6096                      DAG.getIntPtrConstant(4));
6097     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6098                      DAG.getIntPtrConstant(4));
6099     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6100                      DAG.getIntPtrConstant(0));
6101     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6102                      DAG.getIntPtrConstant(0));
6103
6104     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6105     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6106
6107     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6108     N0 = LowerCONCAT_VECTORS(N0, DAG);
6109
6110     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6111                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6112                      N0);
6113     return N0;
6114   }
6115
6116   // v4i16 sdiv ... Convert to float.
6117   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6118   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6119   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6120   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6121   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6122   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6123
6124   // Use reciprocal estimate and two refinement steps.
6125   // float4 recip = vrecpeq_f32(yf);
6126   // recip *= vrecpsq_f32(yf, recip);
6127   // recip *= vrecpsq_f32(yf, recip);
6128   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6129                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6130   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6131                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6132                    BN1, N2);
6133   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6134   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6135                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6136                    BN1, N2);
6137   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6138   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6139   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6140   // and that it will never cause us to return an answer too large).
6141   // float4 result = as_float4(as_int4(xf*recip) + 2);
6142   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6143   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6144   N1 = DAG.getConstant(2, MVT::i32);
6145   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6146   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6147   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6148   // Convert back to integer and return.
6149   // return vmovn_u32(vcvt_s32_f32(result));
6150   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6151   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6152   return N0;
6153 }
6154
6155 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6156   EVT VT = Op.getNode()->getValueType(0);
6157   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6158
6159   unsigned Opc;
6160   bool ExtraOp = false;
6161   switch (Op.getOpcode()) {
6162   default: llvm_unreachable("Invalid code");
6163   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6164   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6165   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6166   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6167   }
6168
6169   if (!ExtraOp)
6170     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6171                        Op.getOperand(1));
6172   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6173                      Op.getOperand(1), Op.getOperand(2));
6174 }
6175
6176 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6177   assert(Subtarget->isTargetDarwin());
6178
6179   // For iOS, we want to call an alternative entry point: __sincos_stret,
6180   // return values are passed via sret.
6181   SDLoc dl(Op);
6182   SDValue Arg = Op.getOperand(0);
6183   EVT ArgVT = Arg.getValueType();
6184   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6185
6186   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6187   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6188
6189   // Pair of floats / doubles used to pass the result.
6190   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6191
6192   // Create stack object for sret.
6193   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6194   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6195   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6196   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6197
6198   ArgListTy Args;
6199   ArgListEntry Entry;
6200
6201   Entry.Node = SRet;
6202   Entry.Ty = RetTy->getPointerTo();
6203   Entry.isSExt = false;
6204   Entry.isZExt = false;
6205   Entry.isSRet = true;
6206   Args.push_back(Entry);
6207
6208   Entry.Node = Arg;
6209   Entry.Ty = ArgTy;
6210   Entry.isSExt = false;
6211   Entry.isZExt = false;
6212   Args.push_back(Entry);
6213
6214   const char *LibcallName  = (ArgVT == MVT::f64)
6215   ? "__sincos_stret" : "__sincosf_stret";
6216   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6217
6218   TargetLowering::CallLoweringInfo CLI(DAG);
6219   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6220     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6221                std::move(Args), 0)
6222     .setDiscardResult();
6223
6224   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6225
6226   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6227                                 MachinePointerInfo(), false, false, false, 0);
6228
6229   // Address of cos field.
6230   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6231                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6232   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6233                                 MachinePointerInfo(), false, false, false, 0);
6234
6235   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6236   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6237                      LoadSin.getValue(0), LoadCos.getValue(0));
6238 }
6239
6240 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6241   // Monotonic load/store is legal for all targets
6242   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6243     return Op;
6244
6245   // Acquire/Release load/store is not legal for targets without a
6246   // dmb or equivalent available.
6247   return SDValue();
6248 }
6249
6250 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6251                                     SmallVectorImpl<SDValue> &Results,
6252                                     SelectionDAG &DAG,
6253                                     const ARMSubtarget *Subtarget) {
6254   SDLoc DL(N);
6255   SDValue Cycles32, OutChain;
6256
6257   if (Subtarget->hasPerfMon()) {
6258     // Under Power Management extensions, the cycle-count is:
6259     //    mrc p15, #0, <Rt>, c9, c13, #0
6260     SDValue Ops[] = { N->getOperand(0), // Chain
6261                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6262                       DAG.getConstant(15, MVT::i32),
6263                       DAG.getConstant(0, MVT::i32),
6264                       DAG.getConstant(9, MVT::i32),
6265                       DAG.getConstant(13, MVT::i32),
6266                       DAG.getConstant(0, MVT::i32)
6267     };
6268
6269     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6270                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6271     OutChain = Cycles32.getValue(1);
6272   } else {
6273     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6274     // there are older ARM CPUs that have implementation-specific ways of
6275     // obtaining this information (FIXME!).
6276     Cycles32 = DAG.getConstant(0, MVT::i32);
6277     OutChain = DAG.getEntryNode();
6278   }
6279
6280
6281   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6282                                  Cycles32, DAG.getConstant(0, MVT::i32));
6283   Results.push_back(Cycles64);
6284   Results.push_back(OutChain);
6285 }
6286
6287 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6288   switch (Op.getOpcode()) {
6289   default: llvm_unreachable("Don't know how to custom lower this!");
6290   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6291   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6292   case ISD::GlobalAddress:
6293     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6294     default: llvm_unreachable("unknown object format");
6295     case Triple::COFF:
6296       return LowerGlobalAddressWindows(Op, DAG);
6297     case Triple::ELF:
6298       return LowerGlobalAddressELF(Op, DAG);
6299     case Triple::MachO:
6300       return LowerGlobalAddressDarwin(Op, DAG);
6301     }
6302   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6303   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6304   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6305   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6306   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6307   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6308   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6309   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6310   case ISD::SINT_TO_FP:
6311   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6312   case ISD::FP_TO_SINT:
6313   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6314   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6315   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6316   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6317   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6318   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6319   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6320   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6321                                                                Subtarget);
6322   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6323   case ISD::SHL:
6324   case ISD::SRL:
6325   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6326   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6327   case ISD::SRL_PARTS:
6328   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6329   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6330   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6331   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6332   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6333   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6334   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6335   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6336   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6337   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6338   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6339   case ISD::MUL:           return LowerMUL(Op, DAG);
6340   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6341   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6342   case ISD::ADDC:
6343   case ISD::ADDE:
6344   case ISD::SUBC:
6345   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6346   case ISD::SADDO:
6347   case ISD::UADDO:
6348   case ISD::SSUBO:
6349   case ISD::USUBO:
6350     return LowerXALUO(Op, DAG);
6351   case ISD::ATOMIC_LOAD:
6352   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6353   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6354   case ISD::SDIVREM:
6355   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6356   case ISD::DYNAMIC_STACKALLOC:
6357     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6358       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6359     llvm_unreachable("Don't know how to custom lower this!");
6360   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6361   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6362   }
6363 }
6364
6365 /// ReplaceNodeResults - Replace the results of node with an illegal result
6366 /// type with new values built out of custom code.
6367 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6368                                            SmallVectorImpl<SDValue>&Results,
6369                                            SelectionDAG &DAG) const {
6370   SDValue Res;
6371   switch (N->getOpcode()) {
6372   default:
6373     llvm_unreachable("Don't know how to custom expand this!");
6374   case ISD::BITCAST:
6375     Res = ExpandBITCAST(N, DAG);
6376     break;
6377   case ISD::SRL:
6378   case ISD::SRA:
6379     Res = Expand64BitShift(N, DAG, Subtarget);
6380     break;
6381   case ISD::READCYCLECOUNTER:
6382     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6383     return;
6384   }
6385   if (Res.getNode())
6386     Results.push_back(Res);
6387 }
6388
6389 //===----------------------------------------------------------------------===//
6390 //                           ARM Scheduler Hooks
6391 //===----------------------------------------------------------------------===//
6392
6393 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6394 /// registers the function context.
6395 void ARMTargetLowering::
6396 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6397                        MachineBasicBlock *DispatchBB, int FI) const {
6398   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6399   DebugLoc dl = MI->getDebugLoc();
6400   MachineFunction *MF = MBB->getParent();
6401   MachineRegisterInfo *MRI = &MF->getRegInfo();
6402   MachineConstantPool *MCP = MF->getConstantPool();
6403   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6404   const Function *F = MF->getFunction();
6405
6406   bool isThumb = Subtarget->isThumb();
6407   bool isThumb2 = Subtarget->isThumb2();
6408
6409   unsigned PCLabelId = AFI->createPICLabelUId();
6410   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6411   ARMConstantPoolValue *CPV =
6412     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6413   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6414
6415   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6416                                            : &ARM::GPRRegClass;
6417
6418   // Grab constant pool and fixed stack memory operands.
6419   MachineMemOperand *CPMMO =
6420     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6421                              MachineMemOperand::MOLoad, 4, 4);
6422
6423   MachineMemOperand *FIMMOSt =
6424     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6425                              MachineMemOperand::MOStore, 4, 4);
6426
6427   // Load the address of the dispatch MBB into the jump buffer.
6428   if (isThumb2) {
6429     // Incoming value: jbuf
6430     //   ldr.n  r5, LCPI1_1
6431     //   orr    r5, r5, #1
6432     //   add    r5, pc
6433     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6434     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6435     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6436                    .addConstantPoolIndex(CPI)
6437                    .addMemOperand(CPMMO));
6438     // Set the low bit because of thumb mode.
6439     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6440     AddDefaultCC(
6441       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6442                      .addReg(NewVReg1, RegState::Kill)
6443                      .addImm(0x01)));
6444     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6445     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6446       .addReg(NewVReg2, RegState::Kill)
6447       .addImm(PCLabelId);
6448     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6449                    .addReg(NewVReg3, RegState::Kill)
6450                    .addFrameIndex(FI)
6451                    .addImm(36)  // &jbuf[1] :: pc
6452                    .addMemOperand(FIMMOSt));
6453   } else if (isThumb) {
6454     // Incoming value: jbuf
6455     //   ldr.n  r1, LCPI1_4
6456     //   add    r1, pc
6457     //   mov    r2, #1
6458     //   orrs   r1, r2
6459     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6460     //   str    r1, [r2]
6461     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6462     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6463                    .addConstantPoolIndex(CPI)
6464                    .addMemOperand(CPMMO));
6465     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6466     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6467       .addReg(NewVReg1, RegState::Kill)
6468       .addImm(PCLabelId);
6469     // Set the low bit because of thumb mode.
6470     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6471     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6472                    .addReg(ARM::CPSR, RegState::Define)
6473                    .addImm(1));
6474     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6475     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6476                    .addReg(ARM::CPSR, RegState::Define)
6477                    .addReg(NewVReg2, RegState::Kill)
6478                    .addReg(NewVReg3, RegState::Kill));
6479     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6480     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6481             .addFrameIndex(FI)
6482             .addImm(36); // &jbuf[1] :: pc
6483     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6484                    .addReg(NewVReg4, RegState::Kill)
6485                    .addReg(NewVReg5, RegState::Kill)
6486                    .addImm(0)
6487                    .addMemOperand(FIMMOSt));
6488   } else {
6489     // Incoming value: jbuf
6490     //   ldr  r1, LCPI1_1
6491     //   add  r1, pc, r1
6492     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6493     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6494     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6495                    .addConstantPoolIndex(CPI)
6496                    .addImm(0)
6497                    .addMemOperand(CPMMO));
6498     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6499     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6500                    .addReg(NewVReg1, RegState::Kill)
6501                    .addImm(PCLabelId));
6502     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6503                    .addReg(NewVReg2, RegState::Kill)
6504                    .addFrameIndex(FI)
6505                    .addImm(36)  // &jbuf[1] :: pc
6506                    .addMemOperand(FIMMOSt));
6507   }
6508 }
6509
6510 MachineBasicBlock *ARMTargetLowering::
6511 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6512   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6513   DebugLoc dl = MI->getDebugLoc();
6514   MachineFunction *MF = MBB->getParent();
6515   MachineRegisterInfo *MRI = &MF->getRegInfo();
6516   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6517   MachineFrameInfo *MFI = MF->getFrameInfo();
6518   int FI = MFI->getFunctionContextIndex();
6519
6520   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6521                                                         : &ARM::GPRnopcRegClass;
6522
6523   // Get a mapping of the call site numbers to all of the landing pads they're
6524   // associated with.
6525   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6526   unsigned MaxCSNum = 0;
6527   MachineModuleInfo &MMI = MF->getMMI();
6528   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6529        ++BB) {
6530     if (!BB->isLandingPad()) continue;
6531
6532     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6533     // pad.
6534     for (MachineBasicBlock::iterator
6535            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6536       if (!II->isEHLabel()) continue;
6537
6538       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6539       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6540
6541       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6542       for (SmallVectorImpl<unsigned>::iterator
6543              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6544            CSI != CSE; ++CSI) {
6545         CallSiteNumToLPad[*CSI].push_back(BB);
6546         MaxCSNum = std::max(MaxCSNum, *CSI);
6547       }
6548       break;
6549     }
6550   }
6551
6552   // Get an ordered list of the machine basic blocks for the jump table.
6553   std::vector<MachineBasicBlock*> LPadList;
6554   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6555   LPadList.reserve(CallSiteNumToLPad.size());
6556   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6557     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6558     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6559            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6560       LPadList.push_back(*II);
6561       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6562     }
6563   }
6564
6565   assert(!LPadList.empty() &&
6566          "No landing pad destinations for the dispatch jump table!");
6567
6568   // Create the jump table and associated information.
6569   MachineJumpTableInfo *JTI =
6570     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6571   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6572   unsigned UId = AFI->createJumpTableUId();
6573   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6574
6575   // Create the MBBs for the dispatch code.
6576
6577   // Shove the dispatch's address into the return slot in the function context.
6578   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6579   DispatchBB->setIsLandingPad();
6580
6581   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6582   unsigned trap_opcode;
6583   if (Subtarget->isThumb())
6584     trap_opcode = ARM::tTRAP;
6585   else
6586     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6587
6588   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6589   DispatchBB->addSuccessor(TrapBB);
6590
6591   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6592   DispatchBB->addSuccessor(DispContBB);
6593
6594   // Insert and MBBs.
6595   MF->insert(MF->end(), DispatchBB);
6596   MF->insert(MF->end(), DispContBB);
6597   MF->insert(MF->end(), TrapBB);
6598
6599   // Insert code into the entry block that creates and registers the function
6600   // context.
6601   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6602
6603   MachineMemOperand *FIMMOLd =
6604     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6605                              MachineMemOperand::MOLoad |
6606                              MachineMemOperand::MOVolatile, 4, 4);
6607
6608   MachineInstrBuilder MIB;
6609   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6610
6611   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6612   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6613
6614   // Add a register mask with no preserved registers.  This results in all
6615   // registers being marked as clobbered.
6616   MIB.addRegMask(RI.getNoPreservedMask());
6617
6618   unsigned NumLPads = LPadList.size();
6619   if (Subtarget->isThumb2()) {
6620     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6621     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6622                    .addFrameIndex(FI)
6623                    .addImm(4)
6624                    .addMemOperand(FIMMOLd));
6625
6626     if (NumLPads < 256) {
6627       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6628                      .addReg(NewVReg1)
6629                      .addImm(LPadList.size()));
6630     } else {
6631       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6632       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6633                      .addImm(NumLPads & 0xFFFF));
6634
6635       unsigned VReg2 = VReg1;
6636       if ((NumLPads & 0xFFFF0000) != 0) {
6637         VReg2 = MRI->createVirtualRegister(TRC);
6638         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6639                        .addReg(VReg1)
6640                        .addImm(NumLPads >> 16));
6641       }
6642
6643       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6644                      .addReg(NewVReg1)
6645                      .addReg(VReg2));
6646     }
6647
6648     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6649       .addMBB(TrapBB)
6650       .addImm(ARMCC::HI)
6651       .addReg(ARM::CPSR);
6652
6653     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6654     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6655                    .addJumpTableIndex(MJTI)
6656                    .addImm(UId));
6657
6658     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6659     AddDefaultCC(
6660       AddDefaultPred(
6661         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6662         .addReg(NewVReg3, RegState::Kill)
6663         .addReg(NewVReg1)
6664         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6665
6666     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6667       .addReg(NewVReg4, RegState::Kill)
6668       .addReg(NewVReg1)
6669       .addJumpTableIndex(MJTI)
6670       .addImm(UId);
6671   } else if (Subtarget->isThumb()) {
6672     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6673     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6674                    .addFrameIndex(FI)
6675                    .addImm(1)
6676                    .addMemOperand(FIMMOLd));
6677
6678     if (NumLPads < 256) {
6679       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6680                      .addReg(NewVReg1)
6681                      .addImm(NumLPads));
6682     } else {
6683       MachineConstantPool *ConstantPool = MF->getConstantPool();
6684       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6685       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6686
6687       // MachineConstantPool wants an explicit alignment.
6688       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6689       if (Align == 0)
6690         Align = getDataLayout()->getTypeAllocSize(C->getType());
6691       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6692
6693       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6694       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6695                      .addReg(VReg1, RegState::Define)
6696                      .addConstantPoolIndex(Idx));
6697       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6698                      .addReg(NewVReg1)
6699                      .addReg(VReg1));
6700     }
6701
6702     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6703       .addMBB(TrapBB)
6704       .addImm(ARMCC::HI)
6705       .addReg(ARM::CPSR);
6706
6707     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6708     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6709                    .addReg(ARM::CPSR, RegState::Define)
6710                    .addReg(NewVReg1)
6711                    .addImm(2));
6712
6713     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6714     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6715                    .addJumpTableIndex(MJTI)
6716                    .addImm(UId));
6717
6718     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6719     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6720                    .addReg(ARM::CPSR, RegState::Define)
6721                    .addReg(NewVReg2, RegState::Kill)
6722                    .addReg(NewVReg3));
6723
6724     MachineMemOperand *JTMMOLd =
6725       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6726                                MachineMemOperand::MOLoad, 4, 4);
6727
6728     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6729     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6730                    .addReg(NewVReg4, RegState::Kill)
6731                    .addImm(0)
6732                    .addMemOperand(JTMMOLd));
6733
6734     unsigned NewVReg6 = NewVReg5;
6735     if (RelocM == Reloc::PIC_) {
6736       NewVReg6 = MRI->createVirtualRegister(TRC);
6737       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6738                      .addReg(ARM::CPSR, RegState::Define)
6739                      .addReg(NewVReg5, RegState::Kill)
6740                      .addReg(NewVReg3));
6741     }
6742
6743     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6744       .addReg(NewVReg6, RegState::Kill)
6745       .addJumpTableIndex(MJTI)
6746       .addImm(UId);
6747   } else {
6748     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6749     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6750                    .addFrameIndex(FI)
6751                    .addImm(4)
6752                    .addMemOperand(FIMMOLd));
6753
6754     if (NumLPads < 256) {
6755       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6756                      .addReg(NewVReg1)
6757                      .addImm(NumLPads));
6758     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6759       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6760       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6761                      .addImm(NumLPads & 0xFFFF));
6762
6763       unsigned VReg2 = VReg1;
6764       if ((NumLPads & 0xFFFF0000) != 0) {
6765         VReg2 = MRI->createVirtualRegister(TRC);
6766         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6767                        .addReg(VReg1)
6768                        .addImm(NumLPads >> 16));
6769       }
6770
6771       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6772                      .addReg(NewVReg1)
6773                      .addReg(VReg2));
6774     } else {
6775       MachineConstantPool *ConstantPool = MF->getConstantPool();
6776       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6777       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6778
6779       // MachineConstantPool wants an explicit alignment.
6780       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6781       if (Align == 0)
6782         Align = getDataLayout()->getTypeAllocSize(C->getType());
6783       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6784
6785       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6786       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6787                      .addReg(VReg1, RegState::Define)
6788                      .addConstantPoolIndex(Idx)
6789                      .addImm(0));
6790       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6791                      .addReg(NewVReg1)
6792                      .addReg(VReg1, RegState::Kill));
6793     }
6794
6795     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6796       .addMBB(TrapBB)
6797       .addImm(ARMCC::HI)
6798       .addReg(ARM::CPSR);
6799
6800     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6801     AddDefaultCC(
6802       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6803                      .addReg(NewVReg1)
6804                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6805     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6806     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6807                    .addJumpTableIndex(MJTI)
6808                    .addImm(UId));
6809
6810     MachineMemOperand *JTMMOLd =
6811       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6812                                MachineMemOperand::MOLoad, 4, 4);
6813     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6814     AddDefaultPred(
6815       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6816       .addReg(NewVReg3, RegState::Kill)
6817       .addReg(NewVReg4)
6818       .addImm(0)
6819       .addMemOperand(JTMMOLd));
6820
6821     if (RelocM == Reloc::PIC_) {
6822       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6823         .addReg(NewVReg5, RegState::Kill)
6824         .addReg(NewVReg4)
6825         .addJumpTableIndex(MJTI)
6826         .addImm(UId);
6827     } else {
6828       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6829         .addReg(NewVReg5, RegState::Kill)
6830         .addJumpTableIndex(MJTI)
6831         .addImm(UId);
6832     }
6833   }
6834
6835   // Add the jump table entries as successors to the MBB.
6836   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6837   for (std::vector<MachineBasicBlock*>::iterator
6838          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6839     MachineBasicBlock *CurMBB = *I;
6840     if (SeenMBBs.insert(CurMBB).second)
6841       DispContBB->addSuccessor(CurMBB);
6842   }
6843
6844   // N.B. the order the invoke BBs are processed in doesn't matter here.
6845   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6846   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6847   for (MachineBasicBlock *BB : InvokeBBs) {
6848
6849     // Remove the landing pad successor from the invoke block and replace it
6850     // with the new dispatch block.
6851     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6852                                                   BB->succ_end());
6853     while (!Successors.empty()) {
6854       MachineBasicBlock *SMBB = Successors.pop_back_val();
6855       if (SMBB->isLandingPad()) {
6856         BB->removeSuccessor(SMBB);
6857         MBBLPads.push_back(SMBB);
6858       }
6859     }
6860
6861     BB->addSuccessor(DispatchBB);
6862
6863     // Find the invoke call and mark all of the callee-saved registers as
6864     // 'implicit defined' so that they're spilled. This prevents code from
6865     // moving instructions to before the EH block, where they will never be
6866     // executed.
6867     for (MachineBasicBlock::reverse_iterator
6868            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6869       if (!II->isCall()) continue;
6870
6871       DenseMap<unsigned, bool> DefRegs;
6872       for (MachineInstr::mop_iterator
6873              OI = II->operands_begin(), OE = II->operands_end();
6874            OI != OE; ++OI) {
6875         if (!OI->isReg()) continue;
6876         DefRegs[OI->getReg()] = true;
6877       }
6878
6879       MachineInstrBuilder MIB(*MF, &*II);
6880
6881       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6882         unsigned Reg = SavedRegs[i];
6883         if (Subtarget->isThumb2() &&
6884             !ARM::tGPRRegClass.contains(Reg) &&
6885             !ARM::hGPRRegClass.contains(Reg))
6886           continue;
6887         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6888           continue;
6889         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6890           continue;
6891         if (!DefRegs[Reg])
6892           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6893       }
6894
6895       break;
6896     }
6897   }
6898
6899   // Mark all former landing pads as non-landing pads. The dispatch is the only
6900   // landing pad now.
6901   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6902          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6903     (*I)->setIsLandingPad(false);
6904
6905   // The instruction is gone now.
6906   MI->eraseFromParent();
6907
6908   return MBB;
6909 }
6910
6911 static
6912 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6913   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6914        E = MBB->succ_end(); I != E; ++I)
6915     if (*I != Succ)
6916       return *I;
6917   llvm_unreachable("Expecting a BB with two successors!");
6918 }
6919
6920 /// Return the load opcode for a given load size. If load size >= 8,
6921 /// neon opcode will be returned.
6922 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6923   if (LdSize >= 8)
6924     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6925                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6926   if (IsThumb1)
6927     return LdSize == 4 ? ARM::tLDRi
6928                        : LdSize == 2 ? ARM::tLDRHi
6929                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6930   if (IsThumb2)
6931     return LdSize == 4 ? ARM::t2LDR_POST
6932                        : LdSize == 2 ? ARM::t2LDRH_POST
6933                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6934   return LdSize == 4 ? ARM::LDR_POST_IMM
6935                      : LdSize == 2 ? ARM::LDRH_POST
6936                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6937 }
6938
6939 /// Return the store opcode for a given store size. If store size >= 8,
6940 /// neon opcode will be returned.
6941 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6942   if (StSize >= 8)
6943     return StSize == 16 ? ARM::VST1q32wb_fixed
6944                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6945   if (IsThumb1)
6946     return StSize == 4 ? ARM::tSTRi
6947                        : StSize == 2 ? ARM::tSTRHi
6948                                      : StSize == 1 ? ARM::tSTRBi : 0;
6949   if (IsThumb2)
6950     return StSize == 4 ? ARM::t2STR_POST
6951                        : StSize == 2 ? ARM::t2STRH_POST
6952                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6953   return StSize == 4 ? ARM::STR_POST_IMM
6954                      : StSize == 2 ? ARM::STRH_POST
6955                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6956 }
6957
6958 /// Emit a post-increment load operation with given size. The instructions
6959 /// will be added to BB at Pos.
6960 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6961                        const TargetInstrInfo *TII, DebugLoc dl,
6962                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6963                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6964   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6965   assert(LdOpc != 0 && "Should have a load opcode");
6966   if (LdSize >= 8) {
6967     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6968                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6969                        .addImm(0));
6970   } else if (IsThumb1) {
6971     // load + update AddrIn
6972     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6973                        .addReg(AddrIn).addImm(0));
6974     MachineInstrBuilder MIB =
6975         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6976     MIB = AddDefaultT1CC(MIB);
6977     MIB.addReg(AddrIn).addImm(LdSize);
6978     AddDefaultPred(MIB);
6979   } else if (IsThumb2) {
6980     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6981                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6982                        .addImm(LdSize));
6983   } else { // arm
6984     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6985                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6986                        .addReg(0).addImm(LdSize));
6987   }
6988 }
6989
6990 /// Emit a post-increment store operation with given size. The instructions
6991 /// will be added to BB at Pos.
6992 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6993                        const TargetInstrInfo *TII, DebugLoc dl,
6994                        unsigned StSize, unsigned Data, unsigned AddrIn,
6995                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6996   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6997   assert(StOpc != 0 && "Should have a store opcode");
6998   if (StSize >= 8) {
6999     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7000                        .addReg(AddrIn).addImm(0).addReg(Data));
7001   } else if (IsThumb1) {
7002     // store + update AddrIn
7003     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7004                        .addReg(AddrIn).addImm(0));
7005     MachineInstrBuilder MIB =
7006         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7007     MIB = AddDefaultT1CC(MIB);
7008     MIB.addReg(AddrIn).addImm(StSize);
7009     AddDefaultPred(MIB);
7010   } else if (IsThumb2) {
7011     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7012                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7013   } else { // arm
7014     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7015                        .addReg(Data).addReg(AddrIn).addReg(0)
7016                        .addImm(StSize));
7017   }
7018 }
7019
7020 MachineBasicBlock *
7021 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7022                                    MachineBasicBlock *BB) const {
7023   // This pseudo instruction has 3 operands: dst, src, size
7024   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7025   // Otherwise, we will generate unrolled scalar copies.
7026   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7027   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7028   MachineFunction::iterator It = BB;
7029   ++It;
7030
7031   unsigned dest = MI->getOperand(0).getReg();
7032   unsigned src = MI->getOperand(1).getReg();
7033   unsigned SizeVal = MI->getOperand(2).getImm();
7034   unsigned Align = MI->getOperand(3).getImm();
7035   DebugLoc dl = MI->getDebugLoc();
7036
7037   MachineFunction *MF = BB->getParent();
7038   MachineRegisterInfo &MRI = MF->getRegInfo();
7039   unsigned UnitSize = 0;
7040   const TargetRegisterClass *TRC = nullptr;
7041   const TargetRegisterClass *VecTRC = nullptr;
7042
7043   bool IsThumb1 = Subtarget->isThumb1Only();
7044   bool IsThumb2 = Subtarget->isThumb2();
7045
7046   if (Align & 1) {
7047     UnitSize = 1;
7048   } else if (Align & 2) {
7049     UnitSize = 2;
7050   } else {
7051     // Check whether we can use NEON instructions.
7052     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7053         Subtarget->hasNEON()) {
7054       if ((Align % 16 == 0) && SizeVal >= 16)
7055         UnitSize = 16;
7056       else if ((Align % 8 == 0) && SizeVal >= 8)
7057         UnitSize = 8;
7058     }
7059     // Can't use NEON instructions.
7060     if (UnitSize == 0)
7061       UnitSize = 4;
7062   }
7063
7064   // Select the correct opcode and register class for unit size load/store
7065   bool IsNeon = UnitSize >= 8;
7066   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7067   if (IsNeon)
7068     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7069                             : UnitSize == 8 ? &ARM::DPRRegClass
7070                                             : nullptr;
7071
7072   unsigned BytesLeft = SizeVal % UnitSize;
7073   unsigned LoopSize = SizeVal - BytesLeft;
7074
7075   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7076     // Use LDR and STR to copy.
7077     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7078     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7079     unsigned srcIn = src;
7080     unsigned destIn = dest;
7081     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7082       unsigned srcOut = MRI.createVirtualRegister(TRC);
7083       unsigned destOut = MRI.createVirtualRegister(TRC);
7084       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7085       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7086                  IsThumb1, IsThumb2);
7087       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7088                  IsThumb1, IsThumb2);
7089       srcIn = srcOut;
7090       destIn = destOut;
7091     }
7092
7093     // Handle the leftover bytes with LDRB and STRB.
7094     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7095     // [destOut] = STRB_POST(scratch, destIn, 1)
7096     for (unsigned i = 0; i < BytesLeft; i++) {
7097       unsigned srcOut = MRI.createVirtualRegister(TRC);
7098       unsigned destOut = MRI.createVirtualRegister(TRC);
7099       unsigned scratch = MRI.createVirtualRegister(TRC);
7100       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7101                  IsThumb1, IsThumb2);
7102       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7103                  IsThumb1, IsThumb2);
7104       srcIn = srcOut;
7105       destIn = destOut;
7106     }
7107     MI->eraseFromParent();   // The instruction is gone now.
7108     return BB;
7109   }
7110
7111   // Expand the pseudo op to a loop.
7112   // thisMBB:
7113   //   ...
7114   //   movw varEnd, # --> with thumb2
7115   //   movt varEnd, #
7116   //   ldrcp varEnd, idx --> without thumb2
7117   //   fallthrough --> loopMBB
7118   // loopMBB:
7119   //   PHI varPhi, varEnd, varLoop
7120   //   PHI srcPhi, src, srcLoop
7121   //   PHI destPhi, dst, destLoop
7122   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7123   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7124   //   subs varLoop, varPhi, #UnitSize
7125   //   bne loopMBB
7126   //   fallthrough --> exitMBB
7127   // exitMBB:
7128   //   epilogue to handle left-over bytes
7129   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7130   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7131   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7132   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7133   MF->insert(It, loopMBB);
7134   MF->insert(It, exitMBB);
7135
7136   // Transfer the remainder of BB and its successor edges to exitMBB.
7137   exitMBB->splice(exitMBB->begin(), BB,
7138                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7139   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7140
7141   // Load an immediate to varEnd.
7142   unsigned varEnd = MRI.createVirtualRegister(TRC);
7143   if (IsThumb2) {
7144     unsigned Vtmp = varEnd;
7145     if ((LoopSize & 0xFFFF0000) != 0)
7146       Vtmp = MRI.createVirtualRegister(TRC);
7147     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7148                        .addImm(LoopSize & 0xFFFF));
7149
7150     if ((LoopSize & 0xFFFF0000) != 0)
7151       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7152                          .addReg(Vtmp).addImm(LoopSize >> 16));
7153   } else {
7154     MachineConstantPool *ConstantPool = MF->getConstantPool();
7155     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7156     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7157
7158     // MachineConstantPool wants an explicit alignment.
7159     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7160     if (Align == 0)
7161       Align = getDataLayout()->getTypeAllocSize(C->getType());
7162     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7163
7164     if (IsThumb1)
7165       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7166           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7167     else
7168       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7169           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7170   }
7171   BB->addSuccessor(loopMBB);
7172
7173   // Generate the loop body:
7174   //   varPhi = PHI(varLoop, varEnd)
7175   //   srcPhi = PHI(srcLoop, src)
7176   //   destPhi = PHI(destLoop, dst)
7177   MachineBasicBlock *entryBB = BB;
7178   BB = loopMBB;
7179   unsigned varLoop = MRI.createVirtualRegister(TRC);
7180   unsigned varPhi = MRI.createVirtualRegister(TRC);
7181   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7182   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7183   unsigned destLoop = MRI.createVirtualRegister(TRC);
7184   unsigned destPhi = MRI.createVirtualRegister(TRC);
7185
7186   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7187     .addReg(varLoop).addMBB(loopMBB)
7188     .addReg(varEnd).addMBB(entryBB);
7189   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7190     .addReg(srcLoop).addMBB(loopMBB)
7191     .addReg(src).addMBB(entryBB);
7192   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7193     .addReg(destLoop).addMBB(loopMBB)
7194     .addReg(dest).addMBB(entryBB);
7195
7196   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7197   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7198   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7199   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7200              IsThumb1, IsThumb2);
7201   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7202              IsThumb1, IsThumb2);
7203
7204   // Decrement loop variable by UnitSize.
7205   if (IsThumb1) {
7206     MachineInstrBuilder MIB =
7207         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7208     MIB = AddDefaultT1CC(MIB);
7209     MIB.addReg(varPhi).addImm(UnitSize);
7210     AddDefaultPred(MIB);
7211   } else {
7212     MachineInstrBuilder MIB =
7213         BuildMI(*BB, BB->end(), dl,
7214                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7215     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7216     MIB->getOperand(5).setReg(ARM::CPSR);
7217     MIB->getOperand(5).setIsDef(true);
7218   }
7219   BuildMI(*BB, BB->end(), dl,
7220           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7221       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7222
7223   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7224   BB->addSuccessor(loopMBB);
7225   BB->addSuccessor(exitMBB);
7226
7227   // Add epilogue to handle BytesLeft.
7228   BB = exitMBB;
7229   MachineInstr *StartOfExit = exitMBB->begin();
7230
7231   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7232   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7233   unsigned srcIn = srcLoop;
7234   unsigned destIn = destLoop;
7235   for (unsigned i = 0; i < BytesLeft; i++) {
7236     unsigned srcOut = MRI.createVirtualRegister(TRC);
7237     unsigned destOut = MRI.createVirtualRegister(TRC);
7238     unsigned scratch = MRI.createVirtualRegister(TRC);
7239     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7240                IsThumb1, IsThumb2);
7241     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7242                IsThumb1, IsThumb2);
7243     srcIn = srcOut;
7244     destIn = destOut;
7245   }
7246
7247   MI->eraseFromParent();   // The instruction is gone now.
7248   return BB;
7249 }
7250
7251 MachineBasicBlock *
7252 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7253                                        MachineBasicBlock *MBB) const {
7254   const TargetMachine &TM = getTargetMachine();
7255   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7256   DebugLoc DL = MI->getDebugLoc();
7257
7258   assert(Subtarget->isTargetWindows() &&
7259          "__chkstk is only supported on Windows");
7260   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7261
7262   // __chkstk takes the number of words to allocate on the stack in R4, and
7263   // returns the stack adjustment in number of bytes in R4.  This will not
7264   // clober any other registers (other than the obvious lr).
7265   //
7266   // Although, technically, IP should be considered a register which may be
7267   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7268   // thumb-2 environment, so there is no interworking required.  As a result, we
7269   // do not expect a veneer to be emitted by the linker, clobbering IP.
7270   //
7271   // Each module receives its own copy of __chkstk, so no import thunk is
7272   // required, again, ensuring that IP is not clobbered.
7273   //
7274   // Finally, although some linkers may theoretically provide a trampoline for
7275   // out of range calls (which is quite common due to a 32M range limitation of
7276   // branches for Thumb), we can generate the long-call version via
7277   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7278   // IP.
7279
7280   switch (TM.getCodeModel()) {
7281   case CodeModel::Small:
7282   case CodeModel::Medium:
7283   case CodeModel::Default:
7284   case CodeModel::Kernel:
7285     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7286       .addImm((unsigned)ARMCC::AL).addReg(0)
7287       .addExternalSymbol("__chkstk")
7288       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7289       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7290       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7291     break;
7292   case CodeModel::Large:
7293   case CodeModel::JITDefault: {
7294     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7295     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7296
7297     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7298       .addExternalSymbol("__chkstk");
7299     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7300       .addImm((unsigned)ARMCC::AL).addReg(0)
7301       .addReg(Reg, RegState::Kill)
7302       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7303       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7304       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7305     break;
7306   }
7307   }
7308
7309   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7310                                       ARM::SP)
7311                               .addReg(ARM::SP).addReg(ARM::R4)));
7312
7313   MI->eraseFromParent();
7314   return MBB;
7315 }
7316
7317 MachineBasicBlock *
7318 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7319                                                MachineBasicBlock *BB) const {
7320   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7321   DebugLoc dl = MI->getDebugLoc();
7322   bool isThumb2 = Subtarget->isThumb2();
7323   switch (MI->getOpcode()) {
7324   default: {
7325     MI->dump();
7326     llvm_unreachable("Unexpected instr type to insert");
7327   }
7328   // The Thumb2 pre-indexed stores have the same MI operands, they just
7329   // define them differently in the .td files from the isel patterns, so
7330   // they need pseudos.
7331   case ARM::t2STR_preidx:
7332     MI->setDesc(TII->get(ARM::t2STR_PRE));
7333     return BB;
7334   case ARM::t2STRB_preidx:
7335     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7336     return BB;
7337   case ARM::t2STRH_preidx:
7338     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7339     return BB;
7340
7341   case ARM::STRi_preidx:
7342   case ARM::STRBi_preidx: {
7343     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7344       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7345     // Decode the offset.
7346     unsigned Offset = MI->getOperand(4).getImm();
7347     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7348     Offset = ARM_AM::getAM2Offset(Offset);
7349     if (isSub)
7350       Offset = -Offset;
7351
7352     MachineMemOperand *MMO = *MI->memoperands_begin();
7353     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7354       .addOperand(MI->getOperand(0))  // Rn_wb
7355       .addOperand(MI->getOperand(1))  // Rt
7356       .addOperand(MI->getOperand(2))  // Rn
7357       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7358       .addOperand(MI->getOperand(5))  // pred
7359       .addOperand(MI->getOperand(6))
7360       .addMemOperand(MMO);
7361     MI->eraseFromParent();
7362     return BB;
7363   }
7364   case ARM::STRr_preidx:
7365   case ARM::STRBr_preidx:
7366   case ARM::STRH_preidx: {
7367     unsigned NewOpc;
7368     switch (MI->getOpcode()) {
7369     default: llvm_unreachable("unexpected opcode!");
7370     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7371     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7372     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7373     }
7374     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7375     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7376       MIB.addOperand(MI->getOperand(i));
7377     MI->eraseFromParent();
7378     return BB;
7379   }
7380
7381   case ARM::tMOVCCr_pseudo: {
7382     // To "insert" a SELECT_CC instruction, we actually have to insert the
7383     // diamond control-flow pattern.  The incoming instruction knows the
7384     // destination vreg to set, the condition code register to branch on, the
7385     // true/false values to select between, and a branch opcode to use.
7386     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7387     MachineFunction::iterator It = BB;
7388     ++It;
7389
7390     //  thisMBB:
7391     //  ...
7392     //   TrueVal = ...
7393     //   cmpTY ccX, r1, r2
7394     //   bCC copy1MBB
7395     //   fallthrough --> copy0MBB
7396     MachineBasicBlock *thisMBB  = BB;
7397     MachineFunction *F = BB->getParent();
7398     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7399     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7400     F->insert(It, copy0MBB);
7401     F->insert(It, sinkMBB);
7402
7403     // Transfer the remainder of BB and its successor edges to sinkMBB.
7404     sinkMBB->splice(sinkMBB->begin(), BB,
7405                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7406     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7407
7408     BB->addSuccessor(copy0MBB);
7409     BB->addSuccessor(sinkMBB);
7410
7411     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7412       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7413
7414     //  copy0MBB:
7415     //   %FalseValue = ...
7416     //   # fallthrough to sinkMBB
7417     BB = copy0MBB;
7418
7419     // Update machine-CFG edges
7420     BB->addSuccessor(sinkMBB);
7421
7422     //  sinkMBB:
7423     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7424     //  ...
7425     BB = sinkMBB;
7426     BuildMI(*BB, BB->begin(), dl,
7427             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7428       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7429       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7430
7431     MI->eraseFromParent();   // The pseudo instruction is gone now.
7432     return BB;
7433   }
7434
7435   case ARM::BCCi64:
7436   case ARM::BCCZi64: {
7437     // If there is an unconditional branch to the other successor, remove it.
7438     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7439
7440     // Compare both parts that make up the double comparison separately for
7441     // equality.
7442     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7443
7444     unsigned LHS1 = MI->getOperand(1).getReg();
7445     unsigned LHS2 = MI->getOperand(2).getReg();
7446     if (RHSisZero) {
7447       AddDefaultPred(BuildMI(BB, dl,
7448                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7449                      .addReg(LHS1).addImm(0));
7450       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7451         .addReg(LHS2).addImm(0)
7452         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7453     } else {
7454       unsigned RHS1 = MI->getOperand(3).getReg();
7455       unsigned RHS2 = MI->getOperand(4).getReg();
7456       AddDefaultPred(BuildMI(BB, dl,
7457                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7458                      .addReg(LHS1).addReg(RHS1));
7459       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7460         .addReg(LHS2).addReg(RHS2)
7461         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7462     }
7463
7464     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7465     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7466     if (MI->getOperand(0).getImm() == ARMCC::NE)
7467       std::swap(destMBB, exitMBB);
7468
7469     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7470       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7471     if (isThumb2)
7472       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7473     else
7474       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7475
7476     MI->eraseFromParent();   // The pseudo instruction is gone now.
7477     return BB;
7478   }
7479
7480   case ARM::Int_eh_sjlj_setjmp:
7481   case ARM::Int_eh_sjlj_setjmp_nofp:
7482   case ARM::tInt_eh_sjlj_setjmp:
7483   case ARM::t2Int_eh_sjlj_setjmp:
7484   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7485     EmitSjLjDispatchBlock(MI, BB);
7486     return BB;
7487
7488   case ARM::ABS:
7489   case ARM::t2ABS: {
7490     // To insert an ABS instruction, we have to insert the
7491     // diamond control-flow pattern.  The incoming instruction knows the
7492     // source vreg to test against 0, the destination vreg to set,
7493     // the condition code register to branch on, the
7494     // true/false values to select between, and a branch opcode to use.
7495     // It transforms
7496     //     V1 = ABS V0
7497     // into
7498     //     V2 = MOVS V0
7499     //     BCC                      (branch to SinkBB if V0 >= 0)
7500     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7501     //     SinkBB: V1 = PHI(V2, V3)
7502     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7503     MachineFunction::iterator BBI = BB;
7504     ++BBI;
7505     MachineFunction *Fn = BB->getParent();
7506     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7507     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7508     Fn->insert(BBI, RSBBB);
7509     Fn->insert(BBI, SinkBB);
7510
7511     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7512     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7513     bool isThumb2 = Subtarget->isThumb2();
7514     MachineRegisterInfo &MRI = Fn->getRegInfo();
7515     // In Thumb mode S must not be specified if source register is the SP or
7516     // PC and if destination register is the SP, so restrict register class
7517     unsigned NewRsbDstReg =
7518       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7519
7520     // Transfer the remainder of BB and its successor edges to sinkMBB.
7521     SinkBB->splice(SinkBB->begin(), BB,
7522                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7523     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7524
7525     BB->addSuccessor(RSBBB);
7526     BB->addSuccessor(SinkBB);
7527
7528     // fall through to SinkMBB
7529     RSBBB->addSuccessor(SinkBB);
7530
7531     // insert a cmp at the end of BB
7532     AddDefaultPred(BuildMI(BB, dl,
7533                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7534                    .addReg(ABSSrcReg).addImm(0));
7535
7536     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7537     BuildMI(BB, dl,
7538       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7539       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7540
7541     // insert rsbri in RSBBB
7542     // Note: BCC and rsbri will be converted into predicated rsbmi
7543     // by if-conversion pass
7544     BuildMI(*RSBBB, RSBBB->begin(), dl,
7545       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7546       .addReg(ABSSrcReg, RegState::Kill)
7547       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7548
7549     // insert PHI in SinkBB,
7550     // reuse ABSDstReg to not change uses of ABS instruction
7551     BuildMI(*SinkBB, SinkBB->begin(), dl,
7552       TII->get(ARM::PHI), ABSDstReg)
7553       .addReg(NewRsbDstReg).addMBB(RSBBB)
7554       .addReg(ABSSrcReg).addMBB(BB);
7555
7556     // remove ABS instruction
7557     MI->eraseFromParent();
7558
7559     // return last added BB
7560     return SinkBB;
7561   }
7562   case ARM::COPY_STRUCT_BYVAL_I32:
7563     ++NumLoopByVals;
7564     return EmitStructByval(MI, BB);
7565   case ARM::WIN__CHKSTK:
7566     return EmitLowered__chkstk(MI, BB);
7567   }
7568 }
7569
7570 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7571                                                       SDNode *Node) const {
7572   const MCInstrDesc *MCID = &MI->getDesc();
7573   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7574   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7575   // operand is still set to noreg. If needed, set the optional operand's
7576   // register to CPSR, and remove the redundant implicit def.
7577   //
7578   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7579
7580   // Rename pseudo opcodes.
7581   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7582   if (NewOpc) {
7583     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7584     MCID = &TII->get(NewOpc);
7585
7586     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7587            "converted opcode should be the same except for cc_out");
7588
7589     MI->setDesc(*MCID);
7590
7591     // Add the optional cc_out operand
7592     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7593   }
7594   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7595
7596   // Any ARM instruction that sets the 's' bit should specify an optional
7597   // "cc_out" operand in the last operand position.
7598   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7599     assert(!NewOpc && "Optional cc_out operand required");
7600     return;
7601   }
7602   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7603   // since we already have an optional CPSR def.
7604   bool definesCPSR = false;
7605   bool deadCPSR = false;
7606   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7607        i != e; ++i) {
7608     const MachineOperand &MO = MI->getOperand(i);
7609     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7610       definesCPSR = true;
7611       if (MO.isDead())
7612         deadCPSR = true;
7613       MI->RemoveOperand(i);
7614       break;
7615     }
7616   }
7617   if (!definesCPSR) {
7618     assert(!NewOpc && "Optional cc_out operand required");
7619     return;
7620   }
7621   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7622   if (deadCPSR) {
7623     assert(!MI->getOperand(ccOutIdx).getReg() &&
7624            "expect uninitialized optional cc_out operand");
7625     return;
7626   }
7627
7628   // If this instruction was defined with an optional CPSR def and its dag node
7629   // had a live implicit CPSR def, then activate the optional CPSR def.
7630   MachineOperand &MO = MI->getOperand(ccOutIdx);
7631   MO.setReg(ARM::CPSR);
7632   MO.setIsDef(true);
7633 }
7634
7635 //===----------------------------------------------------------------------===//
7636 //                           ARM Optimization Hooks
7637 //===----------------------------------------------------------------------===//
7638
7639 // Helper function that checks if N is a null or all ones constant.
7640 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7641   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7642   if (!C)
7643     return false;
7644   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7645 }
7646
7647 // Return true if N is conditionally 0 or all ones.
7648 // Detects these expressions where cc is an i1 value:
7649 //
7650 //   (select cc 0, y)   [AllOnes=0]
7651 //   (select cc y, 0)   [AllOnes=0]
7652 //   (zext cc)          [AllOnes=0]
7653 //   (sext cc)          [AllOnes=0/1]
7654 //   (select cc -1, y)  [AllOnes=1]
7655 //   (select cc y, -1)  [AllOnes=1]
7656 //
7657 // Invert is set when N is the null/all ones constant when CC is false.
7658 // OtherOp is set to the alternative value of N.
7659 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7660                                        SDValue &CC, bool &Invert,
7661                                        SDValue &OtherOp,
7662                                        SelectionDAG &DAG) {
7663   switch (N->getOpcode()) {
7664   default: return false;
7665   case ISD::SELECT: {
7666     CC = N->getOperand(0);
7667     SDValue N1 = N->getOperand(1);
7668     SDValue N2 = N->getOperand(2);
7669     if (isZeroOrAllOnes(N1, AllOnes)) {
7670       Invert = false;
7671       OtherOp = N2;
7672       return true;
7673     }
7674     if (isZeroOrAllOnes(N2, AllOnes)) {
7675       Invert = true;
7676       OtherOp = N1;
7677       return true;
7678     }
7679     return false;
7680   }
7681   case ISD::ZERO_EXTEND:
7682     // (zext cc) can never be the all ones value.
7683     if (AllOnes)
7684       return false;
7685     // Fall through.
7686   case ISD::SIGN_EXTEND: {
7687     EVT VT = N->getValueType(0);
7688     CC = N->getOperand(0);
7689     if (CC.getValueType() != MVT::i1)
7690       return false;
7691     Invert = !AllOnes;
7692     if (AllOnes)
7693       // When looking for an AllOnes constant, N is an sext, and the 'other'
7694       // value is 0.
7695       OtherOp = DAG.getConstant(0, VT);
7696     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7697       // When looking for a 0 constant, N can be zext or sext.
7698       OtherOp = DAG.getConstant(1, VT);
7699     else
7700       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7701     return true;
7702   }
7703   }
7704 }
7705
7706 // Combine a constant select operand into its use:
7707 //
7708 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7709 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7710 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7711 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7712 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7713 //
7714 // The transform is rejected if the select doesn't have a constant operand that
7715 // is null, or all ones when AllOnes is set.
7716 //
7717 // Also recognize sext/zext from i1:
7718 //
7719 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7720 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7721 //
7722 // These transformations eventually create predicated instructions.
7723 //
7724 // @param N       The node to transform.
7725 // @param Slct    The N operand that is a select.
7726 // @param OtherOp The other N operand (x above).
7727 // @param DCI     Context.
7728 // @param AllOnes Require the select constant to be all ones instead of null.
7729 // @returns The new node, or SDValue() on failure.
7730 static
7731 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7732                             TargetLowering::DAGCombinerInfo &DCI,
7733                             bool AllOnes = false) {
7734   SelectionDAG &DAG = DCI.DAG;
7735   EVT VT = N->getValueType(0);
7736   SDValue NonConstantVal;
7737   SDValue CCOp;
7738   bool SwapSelectOps;
7739   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7740                                   NonConstantVal, DAG))
7741     return SDValue();
7742
7743   // Slct is now know to be the desired identity constant when CC is true.
7744   SDValue TrueVal = OtherOp;
7745   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7746                                  OtherOp, NonConstantVal);
7747   // Unless SwapSelectOps says CC should be false.
7748   if (SwapSelectOps)
7749     std::swap(TrueVal, FalseVal);
7750
7751   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7752                      CCOp, TrueVal, FalseVal);
7753 }
7754
7755 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7756 static
7757 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7758                                        TargetLowering::DAGCombinerInfo &DCI) {
7759   SDValue N0 = N->getOperand(0);
7760   SDValue N1 = N->getOperand(1);
7761   if (N0.getNode()->hasOneUse()) {
7762     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7763     if (Result.getNode())
7764       return Result;
7765   }
7766   if (N1.getNode()->hasOneUse()) {
7767     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7768     if (Result.getNode())
7769       return Result;
7770   }
7771   return SDValue();
7772 }
7773
7774 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7775 // (only after legalization).
7776 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7777                                  TargetLowering::DAGCombinerInfo &DCI,
7778                                  const ARMSubtarget *Subtarget) {
7779
7780   // Only perform optimization if after legalize, and if NEON is available. We
7781   // also expected both operands to be BUILD_VECTORs.
7782   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7783       || N0.getOpcode() != ISD::BUILD_VECTOR
7784       || N1.getOpcode() != ISD::BUILD_VECTOR)
7785     return SDValue();
7786
7787   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7788   EVT VT = N->getValueType(0);
7789   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7790     return SDValue();
7791
7792   // Check that the vector operands are of the right form.
7793   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7794   // operands, where N is the size of the formed vector.
7795   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7796   // index such that we have a pair wise add pattern.
7797
7798   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7799   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7800     return SDValue();
7801   SDValue Vec = N0->getOperand(0)->getOperand(0);
7802   SDNode *V = Vec.getNode();
7803   unsigned nextIndex = 0;
7804
7805   // For each operands to the ADD which are BUILD_VECTORs,
7806   // check to see if each of their operands are an EXTRACT_VECTOR with
7807   // the same vector and appropriate index.
7808   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7809     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7810         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7811
7812       SDValue ExtVec0 = N0->getOperand(i);
7813       SDValue ExtVec1 = N1->getOperand(i);
7814
7815       // First operand is the vector, verify its the same.
7816       if (V != ExtVec0->getOperand(0).getNode() ||
7817           V != ExtVec1->getOperand(0).getNode())
7818         return SDValue();
7819
7820       // Second is the constant, verify its correct.
7821       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7822       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7823
7824       // For the constant, we want to see all the even or all the odd.
7825       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7826           || C1->getZExtValue() != nextIndex+1)
7827         return SDValue();
7828
7829       // Increment index.
7830       nextIndex+=2;
7831     } else
7832       return SDValue();
7833   }
7834
7835   // Create VPADDL node.
7836   SelectionDAG &DAG = DCI.DAG;
7837   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7838
7839   // Build operand list.
7840   SmallVector<SDValue, 8> Ops;
7841   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7842                                 TLI.getPointerTy()));
7843
7844   // Input is the vector.
7845   Ops.push_back(Vec);
7846
7847   // Get widened type and narrowed type.
7848   MVT widenType;
7849   unsigned numElem = VT.getVectorNumElements();
7850   
7851   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7852   switch (inputLaneType.getSimpleVT().SimpleTy) {
7853     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7854     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7855     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7856     default:
7857       llvm_unreachable("Invalid vector element type for padd optimization.");
7858   }
7859
7860   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7861   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7862   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7863 }
7864
7865 static SDValue findMUL_LOHI(SDValue V) {
7866   if (V->getOpcode() == ISD::UMUL_LOHI ||
7867       V->getOpcode() == ISD::SMUL_LOHI)
7868     return V;
7869   return SDValue();
7870 }
7871
7872 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7873                                      TargetLowering::DAGCombinerInfo &DCI,
7874                                      const ARMSubtarget *Subtarget) {
7875
7876   if (Subtarget->isThumb1Only()) return SDValue();
7877
7878   // Only perform the checks after legalize when the pattern is available.
7879   if (DCI.isBeforeLegalize()) return SDValue();
7880
7881   // Look for multiply add opportunities.
7882   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7883   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7884   // a glue link from the first add to the second add.
7885   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7886   // a S/UMLAL instruction.
7887   //          loAdd   UMUL_LOHI
7888   //            \    / :lo    \ :hi
7889   //             \  /          \          [no multiline comment]
7890   //              ADDC         |  hiAdd
7891   //                 \ :glue  /  /
7892   //                  \      /  /
7893   //                    ADDE
7894   //
7895   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7896   SDValue AddcOp0 = AddcNode->getOperand(0);
7897   SDValue AddcOp1 = AddcNode->getOperand(1);
7898
7899   // Check if the two operands are from the same mul_lohi node.
7900   if (AddcOp0.getNode() == AddcOp1.getNode())
7901     return SDValue();
7902
7903   assert(AddcNode->getNumValues() == 2 &&
7904          AddcNode->getValueType(0) == MVT::i32 &&
7905          "Expect ADDC with two result values. First: i32");
7906
7907   // Check that we have a glued ADDC node.
7908   if (AddcNode->getValueType(1) != MVT::Glue)
7909     return SDValue();
7910
7911   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7912   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7913       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7914       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7915       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7916     return SDValue();
7917
7918   // Look for the glued ADDE.
7919   SDNode* AddeNode = AddcNode->getGluedUser();
7920   if (!AddeNode)
7921     return SDValue();
7922
7923   // Make sure it is really an ADDE.
7924   if (AddeNode->getOpcode() != ISD::ADDE)
7925     return SDValue();
7926
7927   assert(AddeNode->getNumOperands() == 3 &&
7928          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7929          "ADDE node has the wrong inputs");
7930
7931   // Check for the triangle shape.
7932   SDValue AddeOp0 = AddeNode->getOperand(0);
7933   SDValue AddeOp1 = AddeNode->getOperand(1);
7934
7935   // Make sure that the ADDE operands are not coming from the same node.
7936   if (AddeOp0.getNode() == AddeOp1.getNode())
7937     return SDValue();
7938
7939   // Find the MUL_LOHI node walking up ADDE's operands.
7940   bool IsLeftOperandMUL = false;
7941   SDValue MULOp = findMUL_LOHI(AddeOp0);
7942   if (MULOp == SDValue())
7943    MULOp = findMUL_LOHI(AddeOp1);
7944   else
7945     IsLeftOperandMUL = true;
7946   if (MULOp == SDValue())
7947     return SDValue();
7948
7949   // Figure out the right opcode.
7950   unsigned Opc = MULOp->getOpcode();
7951   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7952
7953   // Figure out the high and low input values to the MLAL node.
7954   SDValue* HiAdd = nullptr;
7955   SDValue* LoMul = nullptr;
7956   SDValue* LowAdd = nullptr;
7957
7958   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
7959   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
7960     return SDValue();
7961
7962   if (IsLeftOperandMUL)
7963     HiAdd = &AddeOp1;
7964   else
7965     HiAdd = &AddeOp0;
7966
7967
7968   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
7969   // whose low result is fed to the ADDC we are checking.
7970
7971   if (AddcOp0 == MULOp.getValue(0)) {
7972     LoMul = &AddcOp0;
7973     LowAdd = &AddcOp1;
7974   }
7975   if (AddcOp1 == MULOp.getValue(0)) {
7976     LoMul = &AddcOp1;
7977     LowAdd = &AddcOp0;
7978   }
7979
7980   if (!LoMul)
7981     return SDValue();
7982
7983   // Create the merged node.
7984   SelectionDAG &DAG = DCI.DAG;
7985
7986   // Build operand list.
7987   SmallVector<SDValue, 8> Ops;
7988   Ops.push_back(LoMul->getOperand(0));
7989   Ops.push_back(LoMul->getOperand(1));
7990   Ops.push_back(*LowAdd);
7991   Ops.push_back(*HiAdd);
7992
7993   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7994                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7995
7996   // Replace the ADDs' nodes uses by the MLA node's values.
7997   SDValue HiMLALResult(MLALNode.getNode(), 1);
7998   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7999
8000   SDValue LoMLALResult(MLALNode.getNode(), 0);
8001   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8002
8003   // Return original node to notify the driver to stop replacing.
8004   SDValue resNode(AddcNode, 0);
8005   return resNode;
8006 }
8007
8008 /// PerformADDCCombine - Target-specific dag combine transform from
8009 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8010 static SDValue PerformADDCCombine(SDNode *N,
8011                                  TargetLowering::DAGCombinerInfo &DCI,
8012                                  const ARMSubtarget *Subtarget) {
8013
8014   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8015
8016 }
8017
8018 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8019 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8020 /// called with the default operands, and if that fails, with commuted
8021 /// operands.
8022 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8023                                           TargetLowering::DAGCombinerInfo &DCI,
8024                                           const ARMSubtarget *Subtarget){
8025
8026   // Attempt to create vpaddl for this add.
8027   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8028   if (Result.getNode())
8029     return Result;
8030
8031   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8032   if (N0.getNode()->hasOneUse()) {
8033     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8034     if (Result.getNode()) return Result;
8035   }
8036   return SDValue();
8037 }
8038
8039 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8040 ///
8041 static SDValue PerformADDCombine(SDNode *N,
8042                                  TargetLowering::DAGCombinerInfo &DCI,
8043                                  const ARMSubtarget *Subtarget) {
8044   SDValue N0 = N->getOperand(0);
8045   SDValue N1 = N->getOperand(1);
8046
8047   // First try with the default operand order.
8048   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8049   if (Result.getNode())
8050     return Result;
8051
8052   // If that didn't work, try again with the operands commuted.
8053   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8054 }
8055
8056 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8057 ///
8058 static SDValue PerformSUBCombine(SDNode *N,
8059                                  TargetLowering::DAGCombinerInfo &DCI) {
8060   SDValue N0 = N->getOperand(0);
8061   SDValue N1 = N->getOperand(1);
8062
8063   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8064   if (N1.getNode()->hasOneUse()) {
8065     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8066     if (Result.getNode()) return Result;
8067   }
8068
8069   return SDValue();
8070 }
8071
8072 /// PerformVMULCombine
8073 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8074 /// special multiplier accumulator forwarding.
8075 ///   vmul d3, d0, d2
8076 ///   vmla d3, d1, d2
8077 /// is faster than
8078 ///   vadd d3, d0, d1
8079 ///   vmul d3, d3, d2
8080 //  However, for (A + B) * (A + B),
8081 //    vadd d2, d0, d1
8082 //    vmul d3, d0, d2
8083 //    vmla d3, d1, d2
8084 //  is slower than
8085 //    vadd d2, d0, d1
8086 //    vmul d3, d2, d2
8087 static SDValue PerformVMULCombine(SDNode *N,
8088                                   TargetLowering::DAGCombinerInfo &DCI,
8089                                   const ARMSubtarget *Subtarget) {
8090   if (!Subtarget->hasVMLxForwarding())
8091     return SDValue();
8092
8093   SelectionDAG &DAG = DCI.DAG;
8094   SDValue N0 = N->getOperand(0);
8095   SDValue N1 = N->getOperand(1);
8096   unsigned Opcode = N0.getOpcode();
8097   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8098       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8099     Opcode = N1.getOpcode();
8100     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8101         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8102       return SDValue();
8103     std::swap(N0, N1);
8104   }
8105
8106   if (N0 == N1)
8107     return SDValue();
8108
8109   EVT VT = N->getValueType(0);
8110   SDLoc DL(N);
8111   SDValue N00 = N0->getOperand(0);
8112   SDValue N01 = N0->getOperand(1);
8113   return DAG.getNode(Opcode, DL, VT,
8114                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8115                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8116 }
8117
8118 static SDValue PerformMULCombine(SDNode *N,
8119                                  TargetLowering::DAGCombinerInfo &DCI,
8120                                  const ARMSubtarget *Subtarget) {
8121   SelectionDAG &DAG = DCI.DAG;
8122
8123   if (Subtarget->isThumb1Only())
8124     return SDValue();
8125
8126   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8127     return SDValue();
8128
8129   EVT VT = N->getValueType(0);
8130   if (VT.is64BitVector() || VT.is128BitVector())
8131     return PerformVMULCombine(N, DCI, Subtarget);
8132   if (VT != MVT::i32)
8133     return SDValue();
8134
8135   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8136   if (!C)
8137     return SDValue();
8138
8139   int64_t MulAmt = C->getSExtValue();
8140   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8141
8142   ShiftAmt = ShiftAmt & (32 - 1);
8143   SDValue V = N->getOperand(0);
8144   SDLoc DL(N);
8145
8146   SDValue Res;
8147   MulAmt >>= ShiftAmt;
8148
8149   if (MulAmt >= 0) {
8150     if (isPowerOf2_32(MulAmt - 1)) {
8151       // (mul x, 2^N + 1) => (add (shl x, N), x)
8152       Res = DAG.getNode(ISD::ADD, DL, VT,
8153                         V,
8154                         DAG.getNode(ISD::SHL, DL, VT,
8155                                     V,
8156                                     DAG.getConstant(Log2_32(MulAmt - 1),
8157                                                     MVT::i32)));
8158     } else if (isPowerOf2_32(MulAmt + 1)) {
8159       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8160       Res = DAG.getNode(ISD::SUB, DL, VT,
8161                         DAG.getNode(ISD::SHL, DL, VT,
8162                                     V,
8163                                     DAG.getConstant(Log2_32(MulAmt + 1),
8164                                                     MVT::i32)),
8165                         V);
8166     } else
8167       return SDValue();
8168   } else {
8169     uint64_t MulAmtAbs = -MulAmt;
8170     if (isPowerOf2_32(MulAmtAbs + 1)) {
8171       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8172       Res = DAG.getNode(ISD::SUB, DL, VT,
8173                         V,
8174                         DAG.getNode(ISD::SHL, DL, VT,
8175                                     V,
8176                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8177                                                     MVT::i32)));
8178     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8179       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8180       Res = DAG.getNode(ISD::ADD, DL, VT,
8181                         V,
8182                         DAG.getNode(ISD::SHL, DL, VT,
8183                                     V,
8184                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8185                                                     MVT::i32)));
8186       Res = DAG.getNode(ISD::SUB, DL, VT,
8187                         DAG.getConstant(0, MVT::i32),Res);
8188
8189     } else
8190       return SDValue();
8191   }
8192
8193   if (ShiftAmt != 0)
8194     Res = DAG.getNode(ISD::SHL, DL, VT,
8195                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8196
8197   // Do not add new nodes to DAG combiner worklist.
8198   DCI.CombineTo(N, Res, false);
8199   return SDValue();
8200 }
8201
8202 static SDValue PerformANDCombine(SDNode *N,
8203                                  TargetLowering::DAGCombinerInfo &DCI,
8204                                  const ARMSubtarget *Subtarget) {
8205
8206   // Attempt to use immediate-form VBIC
8207   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8208   SDLoc dl(N);
8209   EVT VT = N->getValueType(0);
8210   SelectionDAG &DAG = DCI.DAG;
8211
8212   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8213     return SDValue();
8214
8215   APInt SplatBits, SplatUndef;
8216   unsigned SplatBitSize;
8217   bool HasAnyUndefs;
8218   if (BVN &&
8219       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8220     if (SplatBitSize <= 64) {
8221       EVT VbicVT;
8222       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8223                                       SplatUndef.getZExtValue(), SplatBitSize,
8224                                       DAG, VbicVT, VT.is128BitVector(),
8225                                       OtherModImm);
8226       if (Val.getNode()) {
8227         SDValue Input =
8228           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8229         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8230         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8231       }
8232     }
8233   }
8234
8235   if (!Subtarget->isThumb1Only()) {
8236     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8237     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8238     if (Result.getNode())
8239       return Result;
8240   }
8241
8242   return SDValue();
8243 }
8244
8245 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8246 static SDValue PerformORCombine(SDNode *N,
8247                                 TargetLowering::DAGCombinerInfo &DCI,
8248                                 const ARMSubtarget *Subtarget) {
8249   // Attempt to use immediate-form VORR
8250   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8251   SDLoc dl(N);
8252   EVT VT = N->getValueType(0);
8253   SelectionDAG &DAG = DCI.DAG;
8254
8255   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8256     return SDValue();
8257
8258   APInt SplatBits, SplatUndef;
8259   unsigned SplatBitSize;
8260   bool HasAnyUndefs;
8261   if (BVN && Subtarget->hasNEON() &&
8262       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8263     if (SplatBitSize <= 64) {
8264       EVT VorrVT;
8265       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8266                                       SplatUndef.getZExtValue(), SplatBitSize,
8267                                       DAG, VorrVT, VT.is128BitVector(),
8268                                       OtherModImm);
8269       if (Val.getNode()) {
8270         SDValue Input =
8271           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8272         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8273         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8274       }
8275     }
8276   }
8277
8278   if (!Subtarget->isThumb1Only()) {
8279     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8280     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8281     if (Result.getNode())
8282       return Result;
8283   }
8284
8285   // The code below optimizes (or (and X, Y), Z).
8286   // The AND operand needs to have a single user to make these optimizations
8287   // profitable.
8288   SDValue N0 = N->getOperand(0);
8289   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8290     return SDValue();
8291   SDValue N1 = N->getOperand(1);
8292
8293   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8294   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8295       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8296     APInt SplatUndef;
8297     unsigned SplatBitSize;
8298     bool HasAnyUndefs;
8299
8300     APInt SplatBits0, SplatBits1;
8301     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8302     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8303     // Ensure that the second operand of both ands are constants
8304     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8305                                       HasAnyUndefs) && !HasAnyUndefs) {
8306         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8307                                           HasAnyUndefs) && !HasAnyUndefs) {
8308             // Ensure that the bit width of the constants are the same and that
8309             // the splat arguments are logical inverses as per the pattern we
8310             // are trying to simplify.
8311             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8312                 SplatBits0 == ~SplatBits1) {
8313                 // Canonicalize the vector type to make instruction selection
8314                 // simpler.
8315                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8316                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8317                                              N0->getOperand(1),
8318                                              N0->getOperand(0),
8319                                              N1->getOperand(0));
8320                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8321             }
8322         }
8323     }
8324   }
8325
8326   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8327   // reasonable.
8328
8329   // BFI is only available on V6T2+
8330   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8331     return SDValue();
8332
8333   SDLoc DL(N);
8334   // 1) or (and A, mask), val => ARMbfi A, val, mask
8335   //      iff (val & mask) == val
8336   //
8337   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8338   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8339   //          && mask == ~mask2
8340   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8341   //          && ~mask == mask2
8342   //  (i.e., copy a bitfield value into another bitfield of the same width)
8343
8344   if (VT != MVT::i32)
8345     return SDValue();
8346
8347   SDValue N00 = N0.getOperand(0);
8348
8349   // The value and the mask need to be constants so we can verify this is
8350   // actually a bitfield set. If the mask is 0xffff, we can do better
8351   // via a movt instruction, so don't use BFI in that case.
8352   SDValue MaskOp = N0.getOperand(1);
8353   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8354   if (!MaskC)
8355     return SDValue();
8356   unsigned Mask = MaskC->getZExtValue();
8357   if (Mask == 0xffff)
8358     return SDValue();
8359   SDValue Res;
8360   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8361   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8362   if (N1C) {
8363     unsigned Val = N1C->getZExtValue();
8364     if ((Val & ~Mask) != Val)
8365       return SDValue();
8366
8367     if (ARM::isBitFieldInvertedMask(Mask)) {
8368       Val >>= countTrailingZeros(~Mask);
8369
8370       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8371                         DAG.getConstant(Val, MVT::i32),
8372                         DAG.getConstant(Mask, MVT::i32));
8373
8374       // Do not add new nodes to DAG combiner worklist.
8375       DCI.CombineTo(N, Res, false);
8376       return SDValue();
8377     }
8378   } else if (N1.getOpcode() == ISD::AND) {
8379     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8380     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8381     if (!N11C)
8382       return SDValue();
8383     unsigned Mask2 = N11C->getZExtValue();
8384
8385     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8386     // as is to match.
8387     if (ARM::isBitFieldInvertedMask(Mask) &&
8388         (Mask == ~Mask2)) {
8389       // The pack halfword instruction works better for masks that fit it,
8390       // so use that when it's available.
8391       if (Subtarget->hasT2ExtractPack() &&
8392           (Mask == 0xffff || Mask == 0xffff0000))
8393         return SDValue();
8394       // 2a
8395       unsigned amt = countTrailingZeros(Mask2);
8396       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8397                         DAG.getConstant(amt, MVT::i32));
8398       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8399                         DAG.getConstant(Mask, MVT::i32));
8400       // Do not add new nodes to DAG combiner worklist.
8401       DCI.CombineTo(N, Res, false);
8402       return SDValue();
8403     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8404                (~Mask == Mask2)) {
8405       // The pack halfword instruction works better for masks that fit it,
8406       // so use that when it's available.
8407       if (Subtarget->hasT2ExtractPack() &&
8408           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8409         return SDValue();
8410       // 2b
8411       unsigned lsb = countTrailingZeros(Mask);
8412       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8413                         DAG.getConstant(lsb, MVT::i32));
8414       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8415                         DAG.getConstant(Mask2, MVT::i32));
8416       // Do not add new nodes to DAG combiner worklist.
8417       DCI.CombineTo(N, Res, false);
8418       return SDValue();
8419     }
8420   }
8421
8422   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8423       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8424       ARM::isBitFieldInvertedMask(~Mask)) {
8425     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8426     // where lsb(mask) == #shamt and masked bits of B are known zero.
8427     SDValue ShAmt = N00.getOperand(1);
8428     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8429     unsigned LSB = countTrailingZeros(Mask);
8430     if (ShAmtC != LSB)
8431       return SDValue();
8432
8433     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8434                       DAG.getConstant(~Mask, MVT::i32));
8435
8436     // Do not add new nodes to DAG combiner worklist.
8437     DCI.CombineTo(N, Res, false);
8438   }
8439
8440   return SDValue();
8441 }
8442
8443 static SDValue PerformXORCombine(SDNode *N,
8444                                  TargetLowering::DAGCombinerInfo &DCI,
8445                                  const ARMSubtarget *Subtarget) {
8446   EVT VT = N->getValueType(0);
8447   SelectionDAG &DAG = DCI.DAG;
8448
8449   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8450     return SDValue();
8451
8452   if (!Subtarget->isThumb1Only()) {
8453     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8454     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8455     if (Result.getNode())
8456       return Result;
8457   }
8458
8459   return SDValue();
8460 }
8461
8462 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8463 /// the bits being cleared by the AND are not demanded by the BFI.
8464 static SDValue PerformBFICombine(SDNode *N,
8465                                  TargetLowering::DAGCombinerInfo &DCI) {
8466   SDValue N1 = N->getOperand(1);
8467   if (N1.getOpcode() == ISD::AND) {
8468     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8469     if (!N11C)
8470       return SDValue();
8471     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8472     unsigned LSB = countTrailingZeros(~InvMask);
8473     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8474     assert(Width <
8475                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8476            "undefined behavior");
8477     unsigned Mask = (1u << Width) - 1;
8478     unsigned Mask2 = N11C->getZExtValue();
8479     if ((Mask & (~Mask2)) == 0)
8480       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8481                              N->getOperand(0), N1.getOperand(0),
8482                              N->getOperand(2));
8483   }
8484   return SDValue();
8485 }
8486
8487 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8488 /// ARMISD::VMOVRRD.
8489 static SDValue PerformVMOVRRDCombine(SDNode *N,
8490                                      TargetLowering::DAGCombinerInfo &DCI,
8491                                      const ARMSubtarget *Subtarget) {
8492   // vmovrrd(vmovdrr x, y) -> x,y
8493   SDValue InDouble = N->getOperand(0);
8494   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8495     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8496
8497   // vmovrrd(load f64) -> (load i32), (load i32)
8498   SDNode *InNode = InDouble.getNode();
8499   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8500       InNode->getValueType(0) == MVT::f64 &&
8501       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8502       !cast<LoadSDNode>(InNode)->isVolatile()) {
8503     // TODO: Should this be done for non-FrameIndex operands?
8504     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8505
8506     SelectionDAG &DAG = DCI.DAG;
8507     SDLoc DL(LD);
8508     SDValue BasePtr = LD->getBasePtr();
8509     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8510                                  LD->getPointerInfo(), LD->isVolatile(),
8511                                  LD->isNonTemporal(), LD->isInvariant(),
8512                                  LD->getAlignment());
8513
8514     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8515                                     DAG.getConstant(4, MVT::i32));
8516     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8517                                  LD->getPointerInfo(), LD->isVolatile(),
8518                                  LD->isNonTemporal(), LD->isInvariant(),
8519                                  std::min(4U, LD->getAlignment() / 2));
8520
8521     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8522     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8523       std::swap (NewLD1, NewLD2);
8524     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8525     return Result;
8526   }
8527
8528   return SDValue();
8529 }
8530
8531 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8532 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8533 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8534   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8535   SDValue Op0 = N->getOperand(0);
8536   SDValue Op1 = N->getOperand(1);
8537   if (Op0.getOpcode() == ISD::BITCAST)
8538     Op0 = Op0.getOperand(0);
8539   if (Op1.getOpcode() == ISD::BITCAST)
8540     Op1 = Op1.getOperand(0);
8541   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8542       Op0.getNode() == Op1.getNode() &&
8543       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8544     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8545                        N->getValueType(0), Op0.getOperand(0));
8546   return SDValue();
8547 }
8548
8549 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8550 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8551 /// i64 vector to have f64 elements, since the value can then be loaded
8552 /// directly into a VFP register.
8553 static bool hasNormalLoadOperand(SDNode *N) {
8554   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8555   for (unsigned i = 0; i < NumElts; ++i) {
8556     SDNode *Elt = N->getOperand(i).getNode();
8557     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8558       return true;
8559   }
8560   return false;
8561 }
8562
8563 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8564 /// ISD::BUILD_VECTOR.
8565 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8566                                           TargetLowering::DAGCombinerInfo &DCI,
8567                                           const ARMSubtarget *Subtarget) {
8568   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8569   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8570   // into a pair of GPRs, which is fine when the value is used as a scalar,
8571   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8572   SelectionDAG &DAG = DCI.DAG;
8573   if (N->getNumOperands() == 2) {
8574     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8575     if (RV.getNode())
8576       return RV;
8577   }
8578
8579   // Load i64 elements as f64 values so that type legalization does not split
8580   // them up into i32 values.
8581   EVT VT = N->getValueType(0);
8582   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8583     return SDValue();
8584   SDLoc dl(N);
8585   SmallVector<SDValue, 8> Ops;
8586   unsigned NumElts = VT.getVectorNumElements();
8587   for (unsigned i = 0; i < NumElts; ++i) {
8588     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8589     Ops.push_back(V);
8590     // Make the DAGCombiner fold the bitcast.
8591     DCI.AddToWorklist(V.getNode());
8592   }
8593   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8594   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8595   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8596 }
8597
8598 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8599 static SDValue
8600 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8601   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8602   // At that time, we may have inserted bitcasts from integer to float.
8603   // If these bitcasts have survived DAGCombine, change the lowering of this
8604   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8605   // force to use floating point types.
8606
8607   // Make sure we can change the type of the vector.
8608   // This is possible iff:
8609   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8610   //    1.1. Vector is used only once.
8611   //    1.2. Use is a bit convert to an integer type.
8612   // 2. The size of its operands are 32-bits (64-bits are not legal).
8613   EVT VT = N->getValueType(0);
8614   EVT EltVT = VT.getVectorElementType();
8615
8616   // Check 1.1. and 2.
8617   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8618     return SDValue();
8619
8620   // By construction, the input type must be float.
8621   assert(EltVT == MVT::f32 && "Unexpected type!");
8622
8623   // Check 1.2.
8624   SDNode *Use = *N->use_begin();
8625   if (Use->getOpcode() != ISD::BITCAST ||
8626       Use->getValueType(0).isFloatingPoint())
8627     return SDValue();
8628
8629   // Check profitability.
8630   // Model is, if more than half of the relevant operands are bitcast from
8631   // i32, turn the build_vector into a sequence of insert_vector_elt.
8632   // Relevant operands are everything that is not statically
8633   // (i.e., at compile time) bitcasted.
8634   unsigned NumOfBitCastedElts = 0;
8635   unsigned NumElts = VT.getVectorNumElements();
8636   unsigned NumOfRelevantElts = NumElts;
8637   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8638     SDValue Elt = N->getOperand(Idx);
8639     if (Elt->getOpcode() == ISD::BITCAST) {
8640       // Assume only bit cast to i32 will go away.
8641       if (Elt->getOperand(0).getValueType() == MVT::i32)
8642         ++NumOfBitCastedElts;
8643     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8644       // Constants are statically casted, thus do not count them as
8645       // relevant operands.
8646       --NumOfRelevantElts;
8647   }
8648
8649   // Check if more than half of the elements require a non-free bitcast.
8650   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8651     return SDValue();
8652
8653   SelectionDAG &DAG = DCI.DAG;
8654   // Create the new vector type.
8655   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8656   // Check if the type is legal.
8657   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8658   if (!TLI.isTypeLegal(VecVT))
8659     return SDValue();
8660
8661   // Combine:
8662   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8663   // => BITCAST INSERT_VECTOR_ELT
8664   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8665   //                      (BITCAST EN), N.
8666   SDValue Vec = DAG.getUNDEF(VecVT);
8667   SDLoc dl(N);
8668   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8669     SDValue V = N->getOperand(Idx);
8670     if (V.getOpcode() == ISD::UNDEF)
8671       continue;
8672     if (V.getOpcode() == ISD::BITCAST &&
8673         V->getOperand(0).getValueType() == MVT::i32)
8674       // Fold obvious case.
8675       V = V.getOperand(0);
8676     else {
8677       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8678       // Make the DAGCombiner fold the bitcasts.
8679       DCI.AddToWorklist(V.getNode());
8680     }
8681     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8682     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8683   }
8684   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8685   // Make the DAGCombiner fold the bitcasts.
8686   DCI.AddToWorklist(Vec.getNode());
8687   return Vec;
8688 }
8689
8690 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8691 /// ISD::INSERT_VECTOR_ELT.
8692 static SDValue PerformInsertEltCombine(SDNode *N,
8693                                        TargetLowering::DAGCombinerInfo &DCI) {
8694   // Bitcast an i64 load inserted into a vector to f64.
8695   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8696   EVT VT = N->getValueType(0);
8697   SDNode *Elt = N->getOperand(1).getNode();
8698   if (VT.getVectorElementType() != MVT::i64 ||
8699       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8700     return SDValue();
8701
8702   SelectionDAG &DAG = DCI.DAG;
8703   SDLoc dl(N);
8704   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8705                                  VT.getVectorNumElements());
8706   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8707   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8708   // Make the DAGCombiner fold the bitcasts.
8709   DCI.AddToWorklist(Vec.getNode());
8710   DCI.AddToWorklist(V.getNode());
8711   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8712                                Vec, V, N->getOperand(2));
8713   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8714 }
8715
8716 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8717 /// ISD::VECTOR_SHUFFLE.
8718 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8719   // The LLVM shufflevector instruction does not require the shuffle mask
8720   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8721   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8722   // operands do not match the mask length, they are extended by concatenating
8723   // them with undef vectors.  That is probably the right thing for other
8724   // targets, but for NEON it is better to concatenate two double-register
8725   // size vector operands into a single quad-register size vector.  Do that
8726   // transformation here:
8727   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8728   //   shuffle(concat(v1, v2), undef)
8729   SDValue Op0 = N->getOperand(0);
8730   SDValue Op1 = N->getOperand(1);
8731   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8732       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8733       Op0.getNumOperands() != 2 ||
8734       Op1.getNumOperands() != 2)
8735     return SDValue();
8736   SDValue Concat0Op1 = Op0.getOperand(1);
8737   SDValue Concat1Op1 = Op1.getOperand(1);
8738   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8739       Concat1Op1.getOpcode() != ISD::UNDEF)
8740     return SDValue();
8741   // Skip the transformation if any of the types are illegal.
8742   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8743   EVT VT = N->getValueType(0);
8744   if (!TLI.isTypeLegal(VT) ||
8745       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8746       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8747     return SDValue();
8748
8749   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8750                                   Op0.getOperand(0), Op1.getOperand(0));
8751   // Translate the shuffle mask.
8752   SmallVector<int, 16> NewMask;
8753   unsigned NumElts = VT.getVectorNumElements();
8754   unsigned HalfElts = NumElts/2;
8755   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8756   for (unsigned n = 0; n < NumElts; ++n) {
8757     int MaskElt = SVN->getMaskElt(n);
8758     int NewElt = -1;
8759     if (MaskElt < (int)HalfElts)
8760       NewElt = MaskElt;
8761     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8762       NewElt = HalfElts + MaskElt - NumElts;
8763     NewMask.push_back(NewElt);
8764   }
8765   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8766                               DAG.getUNDEF(VT), NewMask.data());
8767 }
8768
8769 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8770 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8771 /// base address updates.
8772 /// For generic load/stores, the memory type is assumed to be a vector.
8773 /// The caller is assumed to have checked legality.
8774 static SDValue CombineBaseUpdate(SDNode *N,
8775                                  TargetLowering::DAGCombinerInfo &DCI) {
8776   SelectionDAG &DAG = DCI.DAG;
8777   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8778                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8779   const bool isStore = N->getOpcode() == ISD::STORE;
8780   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8781   SDValue Addr = N->getOperand(AddrOpIdx);
8782   MemSDNode *MemN = cast<MemSDNode>(N);
8783
8784   // Search for a use of the address operand that is an increment.
8785   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8786          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8787     SDNode *User = *UI;
8788     if (User->getOpcode() != ISD::ADD ||
8789         UI.getUse().getResNo() != Addr.getResNo())
8790       continue;
8791
8792     // Check that the add is independent of the load/store.  Otherwise, folding
8793     // it would create a cycle.
8794     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8795       continue;
8796
8797     // Find the new opcode for the updating load/store.
8798     bool isLoadOp = true;
8799     bool isLaneOp = false;
8800     unsigned NewOpc = 0;
8801     unsigned NumVecs = 0;
8802     if (isIntrinsic) {
8803       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8804       switch (IntNo) {
8805       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8806       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8807         NumVecs = 1; break;
8808       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8809         NumVecs = 2; break;
8810       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8811         NumVecs = 3; break;
8812       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8813         NumVecs = 4; break;
8814       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8815         NumVecs = 2; isLaneOp = true; break;
8816       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8817         NumVecs = 3; isLaneOp = true; break;
8818       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8819         NumVecs = 4; isLaneOp = true; break;
8820       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8821         NumVecs = 1; isLoadOp = false; break;
8822       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8823         NumVecs = 2; isLoadOp = false; break;
8824       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8825         NumVecs = 3; isLoadOp = false; break;
8826       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8827         NumVecs = 4; isLoadOp = false; break;
8828       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8829         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8830       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8831         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8832       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8833         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8834       }
8835     } else {
8836       isLaneOp = true;
8837       switch (N->getOpcode()) {
8838       default: llvm_unreachable("unexpected opcode for Neon base update");
8839       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8840       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8841       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8842       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
8843         NumVecs = 1; isLaneOp = false; break;
8844       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
8845         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8846       }
8847     }
8848
8849     // Find the size of memory referenced by the load/store.
8850     EVT VecTy;
8851     if (isLoadOp) {
8852       VecTy = N->getValueType(0);
8853     } else if (isIntrinsic) {
8854       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8855     } else {
8856       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8857       VecTy = N->getOperand(1).getValueType();
8858     }
8859
8860     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8861     if (isLaneOp)
8862       NumBytes /= VecTy.getVectorNumElements();
8863
8864     // If the increment is a constant, it must match the memory ref size.
8865     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8866     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8867       uint64_t IncVal = CInc->getZExtValue();
8868       if (IncVal != NumBytes)
8869         continue;
8870     } else if (NumBytes >= 3 * 16) {
8871       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8872       // separate instructions that make it harder to use a non-constant update.
8873       continue;
8874     }
8875
8876     // OK, we found an ADD we can fold into the base update.
8877     // Now, create a _UPD node, taking care of not breaking alignment.
8878
8879     EVT AlignedVecTy = VecTy;
8880     unsigned Alignment = MemN->getAlignment();
8881
8882     // If this is a less-than-standard-aligned load/store, change the type to
8883     // match the standard alignment.
8884     // The alignment is overlooked when selecting _UPD variants; and it's
8885     // easier to introduce bitcasts here than fix that.
8886     // There are 3 ways to get to this base-update combine:
8887     // - intrinsics: they are assumed to be properly aligned (to the standard
8888     //   alignment of the memory type), so we don't need to do anything.
8889     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
8890     //   intrinsics, so, likewise, there's nothing to do.
8891     // - generic load/store instructions: the alignment is specified as an
8892     //   explicit operand, rather than implicitly as the standard alignment
8893     //   of the memory type (like the intrisics).  We need to change the
8894     //   memory type to match the explicit alignment.  That way, we don't
8895     //   generate non-standard-aligned ARMISD::VLDx nodes.
8896     if (isa<LSBaseSDNode>(N)) {
8897       if (Alignment == 0)
8898         Alignment = 1;
8899       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
8900         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
8901         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
8902         assert(!isLaneOp && "Unexpected generic load/store lane.");
8903         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
8904         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
8905       }
8906       // Don't set an explicit alignment on regular load/stores that we want
8907       // to transform to VLD/VST 1_UPD nodes.
8908       // This matches the behavior of regular load/stores, which only get an
8909       // explicit alignment if the MMO alignment is larger than the standard
8910       // alignment of the memory type.
8911       // Intrinsics, however, always get an explicit alignment, set to the
8912       // alignment of the MMO.
8913       Alignment = 1;
8914     }
8915
8916     // Create the new updating load/store node.
8917     // First, create an SDVTList for the new updating node's results.
8918     EVT Tys[6];
8919     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
8920     unsigned n;
8921     for (n = 0; n < NumResultVecs; ++n)
8922       Tys[n] = AlignedVecTy;
8923     Tys[n++] = MVT::i32;
8924     Tys[n] = MVT::Other;
8925     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
8926
8927     // Then, gather the new node's operands.
8928     SmallVector<SDValue, 8> Ops;
8929     Ops.push_back(N->getOperand(0)); // incoming chain
8930     Ops.push_back(N->getOperand(AddrOpIdx));
8931     Ops.push_back(Inc);
8932
8933     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
8934       // Try to match the intrinsic's signature
8935       Ops.push_back(StN->getValue());
8936     } else {
8937       // Loads (and of course intrinsics) match the intrinsics' signature,
8938       // so just add all but the alignment operand.
8939       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
8940         Ops.push_back(N->getOperand(i));
8941     }
8942
8943     // For all node types, the alignment operand is always the last one.
8944     Ops.push_back(DAG.getConstant(Alignment, MVT::i32));
8945
8946     // If this is a non-standard-aligned STORE, the penultimate operand is the
8947     // stored value.  Bitcast it to the aligned type.
8948     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
8949       SDValue &StVal = Ops[Ops.size()-2];
8950       StVal = DAG.getNode(ISD::BITCAST, SDLoc(N), AlignedVecTy, StVal);
8951     }
8952
8953     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8954                                            Ops, AlignedVecTy,
8955                                            MemN->getMemOperand());
8956
8957     // Update the uses.
8958     SmallVector<SDValue, 5> NewResults;
8959     for (unsigned i = 0; i < NumResultVecs; ++i)
8960       NewResults.push_back(SDValue(UpdN.getNode(), i));
8961
8962     // If this is an non-standard-aligned LOAD, the first result is the loaded
8963     // value.  Bitcast it to the expected result type.
8964     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
8965       SDValue &LdVal = NewResults[0];
8966       LdVal = DAG.getNode(ISD::BITCAST, SDLoc(N), VecTy, LdVal);
8967     }
8968
8969     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8970     DCI.CombineTo(N, NewResults);
8971     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8972
8973     break;
8974   }
8975   return SDValue();
8976 }
8977
8978 static SDValue PerformVLDCombine(SDNode *N,
8979                                  TargetLowering::DAGCombinerInfo &DCI) {
8980   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8981     return SDValue();
8982
8983   return CombineBaseUpdate(N, DCI);
8984 }
8985
8986 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8987 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8988 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8989 /// return true.
8990 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8991   SelectionDAG &DAG = DCI.DAG;
8992   EVT VT = N->getValueType(0);
8993   // vldN-dup instructions only support 64-bit vectors for N > 1.
8994   if (!VT.is64BitVector())
8995     return false;
8996
8997   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8998   SDNode *VLD = N->getOperand(0).getNode();
8999   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9000     return false;
9001   unsigned NumVecs = 0;
9002   unsigned NewOpc = 0;
9003   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9004   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9005     NumVecs = 2;
9006     NewOpc = ARMISD::VLD2DUP;
9007   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9008     NumVecs = 3;
9009     NewOpc = ARMISD::VLD3DUP;
9010   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9011     NumVecs = 4;
9012     NewOpc = ARMISD::VLD4DUP;
9013   } else {
9014     return false;
9015   }
9016
9017   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9018   // numbers match the load.
9019   unsigned VLDLaneNo =
9020     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9021   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9022        UI != UE; ++UI) {
9023     // Ignore uses of the chain result.
9024     if (UI.getUse().getResNo() == NumVecs)
9025       continue;
9026     SDNode *User = *UI;
9027     if (User->getOpcode() != ARMISD::VDUPLANE ||
9028         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9029       return false;
9030   }
9031
9032   // Create the vldN-dup node.
9033   EVT Tys[5];
9034   unsigned n;
9035   for (n = 0; n < NumVecs; ++n)
9036     Tys[n] = VT;
9037   Tys[n] = MVT::Other;
9038   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9039   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9040   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9041   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9042                                            Ops, VLDMemInt->getMemoryVT(),
9043                                            VLDMemInt->getMemOperand());
9044
9045   // Update the uses.
9046   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9047        UI != UE; ++UI) {
9048     unsigned ResNo = UI.getUse().getResNo();
9049     // Ignore uses of the chain result.
9050     if (ResNo == NumVecs)
9051       continue;
9052     SDNode *User = *UI;
9053     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9054   }
9055
9056   // Now the vldN-lane intrinsic is dead except for its chain result.
9057   // Update uses of the chain.
9058   std::vector<SDValue> VLDDupResults;
9059   for (unsigned n = 0; n < NumVecs; ++n)
9060     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9061   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9062   DCI.CombineTo(VLD, VLDDupResults);
9063
9064   return true;
9065 }
9066
9067 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9068 /// ARMISD::VDUPLANE.
9069 static SDValue PerformVDUPLANECombine(SDNode *N,
9070                                       TargetLowering::DAGCombinerInfo &DCI) {
9071   SDValue Op = N->getOperand(0);
9072
9073   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9074   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9075   if (CombineVLDDUP(N, DCI))
9076     return SDValue(N, 0);
9077
9078   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9079   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9080   while (Op.getOpcode() == ISD::BITCAST)
9081     Op = Op.getOperand(0);
9082   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9083     return SDValue();
9084
9085   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9086   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9087   // The canonical VMOV for a zero vector uses a 32-bit element size.
9088   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9089   unsigned EltBits;
9090   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9091     EltSize = 8;
9092   EVT VT = N->getValueType(0);
9093   if (EltSize > VT.getVectorElementType().getSizeInBits())
9094     return SDValue();
9095
9096   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9097 }
9098
9099 static SDValue PerformLOADCombine(SDNode *N,
9100                                   TargetLowering::DAGCombinerInfo &DCI) {
9101   EVT VT = N->getValueType(0);
9102
9103   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9104   if (ISD::isNormalLoad(N) && VT.isVector() &&
9105       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9106     return CombineBaseUpdate(N, DCI);
9107
9108   return SDValue();
9109 }
9110
9111 /// PerformSTORECombine - Target-specific dag combine xforms for
9112 /// ISD::STORE.
9113 static SDValue PerformSTORECombine(SDNode *N,
9114                                    TargetLowering::DAGCombinerInfo &DCI) {
9115   StoreSDNode *St = cast<StoreSDNode>(N);
9116   if (St->isVolatile())
9117     return SDValue();
9118
9119   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9120   // pack all of the elements in one place.  Next, store to memory in fewer
9121   // chunks.
9122   SDValue StVal = St->getValue();
9123   EVT VT = StVal.getValueType();
9124   if (St->isTruncatingStore() && VT.isVector()) {
9125     SelectionDAG &DAG = DCI.DAG;
9126     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9127     EVT StVT = St->getMemoryVT();
9128     unsigned NumElems = VT.getVectorNumElements();
9129     assert(StVT != VT && "Cannot truncate to the same type");
9130     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9131     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9132
9133     // From, To sizes and ElemCount must be pow of two
9134     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9135
9136     // We are going to use the original vector elt for storing.
9137     // Accumulated smaller vector elements must be a multiple of the store size.
9138     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9139
9140     unsigned SizeRatio  = FromEltSz / ToEltSz;
9141     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9142
9143     // Create a type on which we perform the shuffle.
9144     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9145                                      NumElems*SizeRatio);
9146     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9147
9148     SDLoc DL(St);
9149     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9150     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9151     for (unsigned i = 0; i < NumElems; ++i)
9152       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9153
9154     // Can't shuffle using an illegal type.
9155     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9156
9157     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9158                                 DAG.getUNDEF(WideVec.getValueType()),
9159                                 ShuffleVec.data());
9160     // At this point all of the data is stored at the bottom of the
9161     // register. We now need to save it to mem.
9162
9163     // Find the largest store unit
9164     MVT StoreType = MVT::i8;
9165     for (MVT Tp : MVT::integer_valuetypes()) {
9166       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9167         StoreType = Tp;
9168     }
9169     // Didn't find a legal store type.
9170     if (!TLI.isTypeLegal(StoreType))
9171       return SDValue();
9172
9173     // Bitcast the original vector into a vector of store-size units
9174     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9175             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9176     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9177     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9178     SmallVector<SDValue, 8> Chains;
9179     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9180                                         TLI.getPointerTy());
9181     SDValue BasePtr = St->getBasePtr();
9182
9183     // Perform one or more big stores into memory.
9184     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9185     for (unsigned I = 0; I < E; I++) {
9186       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9187                                    StoreType, ShuffWide,
9188                                    DAG.getIntPtrConstant(I));
9189       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9190                                 St->getPointerInfo(), St->isVolatile(),
9191                                 St->isNonTemporal(), St->getAlignment());
9192       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9193                             Increment);
9194       Chains.push_back(Ch);
9195     }
9196     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9197   }
9198
9199   if (!ISD::isNormalStore(St))
9200     return SDValue();
9201
9202   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9203   // ARM stores of arguments in the same cache line.
9204   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9205       StVal.getNode()->hasOneUse()) {
9206     SelectionDAG  &DAG = DCI.DAG;
9207     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9208     SDLoc DL(St);
9209     SDValue BasePtr = St->getBasePtr();
9210     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9211                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9212                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9213                                   St->isNonTemporal(), St->getAlignment());
9214
9215     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9216                                     DAG.getConstant(4, MVT::i32));
9217     return DAG.getStore(NewST1.getValue(0), DL,
9218                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9219                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9220                         St->isNonTemporal(),
9221                         std::min(4U, St->getAlignment() / 2));
9222   }
9223
9224   if (StVal.getValueType() == MVT::i64 &&
9225       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9226
9227     // Bitcast an i64 store extracted from a vector to f64.
9228     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9229     SelectionDAG &DAG = DCI.DAG;
9230     SDLoc dl(StVal);
9231     SDValue IntVec = StVal.getOperand(0);
9232     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9233                                    IntVec.getValueType().getVectorNumElements());
9234     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9235     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9236                                  Vec, StVal.getOperand(1));
9237     dl = SDLoc(N);
9238     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9239     // Make the DAGCombiner fold the bitcasts.
9240     DCI.AddToWorklist(Vec.getNode());
9241     DCI.AddToWorklist(ExtElt.getNode());
9242     DCI.AddToWorklist(V.getNode());
9243     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9244                         St->getPointerInfo(), St->isVolatile(),
9245                         St->isNonTemporal(), St->getAlignment(),
9246                         St->getAAInfo());
9247   }
9248
9249   // If this is a legal vector store, try to combine it into a VST1_UPD.
9250   if (ISD::isNormalStore(N) && VT.isVector() &&
9251       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9252     return CombineBaseUpdate(N, DCI);
9253
9254   return SDValue();
9255 }
9256
9257 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9258 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9259 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9260 {
9261   integerPart cN;
9262   integerPart c0 = 0;
9263   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9264        I != E; I++) {
9265     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9266     if (!C)
9267       return false;
9268
9269     bool isExact;
9270     APFloat APF = C->getValueAPF();
9271     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9272         != APFloat::opOK || !isExact)
9273       return false;
9274
9275     c0 = (I == 0) ? cN : c0;
9276     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9277       return false;
9278   }
9279   C = c0;
9280   return true;
9281 }
9282
9283 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9284 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9285 /// when the VMUL has a constant operand that is a power of 2.
9286 ///
9287 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9288 ///  vmul.f32        d16, d17, d16
9289 ///  vcvt.s32.f32    d16, d16
9290 /// becomes:
9291 ///  vcvt.s32.f32    d16, d16, #3
9292 static SDValue PerformVCVTCombine(SDNode *N,
9293                                   TargetLowering::DAGCombinerInfo &DCI,
9294                                   const ARMSubtarget *Subtarget) {
9295   SelectionDAG &DAG = DCI.DAG;
9296   SDValue Op = N->getOperand(0);
9297
9298   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9299       Op.getOpcode() != ISD::FMUL)
9300     return SDValue();
9301
9302   uint64_t C;
9303   SDValue N0 = Op->getOperand(0);
9304   SDValue ConstVec = Op->getOperand(1);
9305   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9306
9307   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9308       !isConstVecPow2(ConstVec, isSigned, C))
9309     return SDValue();
9310
9311   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9312   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9313   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9314   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9315       NumLanes > 4) {
9316     // These instructions only exist converting from f32 to i32. We can handle
9317     // smaller integers by generating an extra truncate, but larger ones would
9318     // be lossy. We also can't handle more then 4 lanes, since these intructions
9319     // only support v2i32/v4i32 types.
9320     return SDValue();
9321   }
9322
9323   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9324     Intrinsic::arm_neon_vcvtfp2fxu;
9325   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9326                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9327                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9328                                  DAG.getConstant(Log2_64(C), MVT::i32));
9329
9330   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9331     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9332
9333   return FixConv;
9334 }
9335
9336 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9337 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9338 /// when the VDIV has a constant operand that is a power of 2.
9339 ///
9340 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9341 ///  vcvt.f32.s32    d16, d16
9342 ///  vdiv.f32        d16, d17, d16
9343 /// becomes:
9344 ///  vcvt.f32.s32    d16, d16, #3
9345 static SDValue PerformVDIVCombine(SDNode *N,
9346                                   TargetLowering::DAGCombinerInfo &DCI,
9347                                   const ARMSubtarget *Subtarget) {
9348   SelectionDAG &DAG = DCI.DAG;
9349   SDValue Op = N->getOperand(0);
9350   unsigned OpOpcode = Op.getNode()->getOpcode();
9351
9352   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9353       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9354     return SDValue();
9355
9356   uint64_t C;
9357   SDValue ConstVec = N->getOperand(1);
9358   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9359
9360   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9361       !isConstVecPow2(ConstVec, isSigned, C))
9362     return SDValue();
9363
9364   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9365   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9366   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9367     // These instructions only exist converting from i32 to f32. We can handle
9368     // smaller integers by generating an extra extend, but larger ones would
9369     // be lossy.
9370     return SDValue();
9371   }
9372
9373   SDValue ConvInput = Op.getOperand(0);
9374   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9375   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9376     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9377                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9378                             ConvInput);
9379
9380   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9381     Intrinsic::arm_neon_vcvtfxu2fp;
9382   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9383                      Op.getValueType(),
9384                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9385                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9386 }
9387
9388 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9389 /// operand of a vector shift operation, where all the elements of the
9390 /// build_vector must have the same constant integer value.
9391 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9392   // Ignore bit_converts.
9393   while (Op.getOpcode() == ISD::BITCAST)
9394     Op = Op.getOperand(0);
9395   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9396   APInt SplatBits, SplatUndef;
9397   unsigned SplatBitSize;
9398   bool HasAnyUndefs;
9399   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9400                                       HasAnyUndefs, ElementBits) ||
9401       SplatBitSize > ElementBits)
9402     return false;
9403   Cnt = SplatBits.getSExtValue();
9404   return true;
9405 }
9406
9407 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9408 /// operand of a vector shift left operation.  That value must be in the range:
9409 ///   0 <= Value < ElementBits for a left shift; or
9410 ///   0 <= Value <= ElementBits for a long left shift.
9411 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9412   assert(VT.isVector() && "vector shift count is not a vector type");
9413   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9414   if (! getVShiftImm(Op, ElementBits, Cnt))
9415     return false;
9416   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9417 }
9418
9419 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9420 /// operand of a vector shift right operation.  For a shift opcode, the value
9421 /// is positive, but for an intrinsic the value count must be negative. The
9422 /// absolute value must be in the range:
9423 ///   1 <= |Value| <= ElementBits for a right shift; or
9424 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9425 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9426                          int64_t &Cnt) {
9427   assert(VT.isVector() && "vector shift count is not a vector type");
9428   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9429   if (! getVShiftImm(Op, ElementBits, Cnt))
9430     return false;
9431   if (isIntrinsic)
9432     Cnt = -Cnt;
9433   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9434 }
9435
9436 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9437 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9438   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9439   switch (IntNo) {
9440   default:
9441     // Don't do anything for most intrinsics.
9442     break;
9443
9444   // Vector shifts: check for immediate versions and lower them.
9445   // Note: This is done during DAG combining instead of DAG legalizing because
9446   // the build_vectors for 64-bit vector element shift counts are generally
9447   // not legal, and it is hard to see their values after they get legalized to
9448   // loads from a constant pool.
9449   case Intrinsic::arm_neon_vshifts:
9450   case Intrinsic::arm_neon_vshiftu:
9451   case Intrinsic::arm_neon_vrshifts:
9452   case Intrinsic::arm_neon_vrshiftu:
9453   case Intrinsic::arm_neon_vrshiftn:
9454   case Intrinsic::arm_neon_vqshifts:
9455   case Intrinsic::arm_neon_vqshiftu:
9456   case Intrinsic::arm_neon_vqshiftsu:
9457   case Intrinsic::arm_neon_vqshiftns:
9458   case Intrinsic::arm_neon_vqshiftnu:
9459   case Intrinsic::arm_neon_vqshiftnsu:
9460   case Intrinsic::arm_neon_vqrshiftns:
9461   case Intrinsic::arm_neon_vqrshiftnu:
9462   case Intrinsic::arm_neon_vqrshiftnsu: {
9463     EVT VT = N->getOperand(1).getValueType();
9464     int64_t Cnt;
9465     unsigned VShiftOpc = 0;
9466
9467     switch (IntNo) {
9468     case Intrinsic::arm_neon_vshifts:
9469     case Intrinsic::arm_neon_vshiftu:
9470       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9471         VShiftOpc = ARMISD::VSHL;
9472         break;
9473       }
9474       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9475         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9476                      ARMISD::VSHRs : ARMISD::VSHRu);
9477         break;
9478       }
9479       return SDValue();
9480
9481     case Intrinsic::arm_neon_vrshifts:
9482     case Intrinsic::arm_neon_vrshiftu:
9483       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9484         break;
9485       return SDValue();
9486
9487     case Intrinsic::arm_neon_vqshifts:
9488     case Intrinsic::arm_neon_vqshiftu:
9489       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9490         break;
9491       return SDValue();
9492
9493     case Intrinsic::arm_neon_vqshiftsu:
9494       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9495         break;
9496       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9497
9498     case Intrinsic::arm_neon_vrshiftn:
9499     case Intrinsic::arm_neon_vqshiftns:
9500     case Intrinsic::arm_neon_vqshiftnu:
9501     case Intrinsic::arm_neon_vqshiftnsu:
9502     case Intrinsic::arm_neon_vqrshiftns:
9503     case Intrinsic::arm_neon_vqrshiftnu:
9504     case Intrinsic::arm_neon_vqrshiftnsu:
9505       // Narrowing shifts require an immediate right shift.
9506       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9507         break;
9508       llvm_unreachable("invalid shift count for narrowing vector shift "
9509                        "intrinsic");
9510
9511     default:
9512       llvm_unreachable("unhandled vector shift");
9513     }
9514
9515     switch (IntNo) {
9516     case Intrinsic::arm_neon_vshifts:
9517     case Intrinsic::arm_neon_vshiftu:
9518       // Opcode already set above.
9519       break;
9520     case Intrinsic::arm_neon_vrshifts:
9521       VShiftOpc = ARMISD::VRSHRs; break;
9522     case Intrinsic::arm_neon_vrshiftu:
9523       VShiftOpc = ARMISD::VRSHRu; break;
9524     case Intrinsic::arm_neon_vrshiftn:
9525       VShiftOpc = ARMISD::VRSHRN; break;
9526     case Intrinsic::arm_neon_vqshifts:
9527       VShiftOpc = ARMISD::VQSHLs; break;
9528     case Intrinsic::arm_neon_vqshiftu:
9529       VShiftOpc = ARMISD::VQSHLu; break;
9530     case Intrinsic::arm_neon_vqshiftsu:
9531       VShiftOpc = ARMISD::VQSHLsu; break;
9532     case Intrinsic::arm_neon_vqshiftns:
9533       VShiftOpc = ARMISD::VQSHRNs; break;
9534     case Intrinsic::arm_neon_vqshiftnu:
9535       VShiftOpc = ARMISD::VQSHRNu; break;
9536     case Intrinsic::arm_neon_vqshiftnsu:
9537       VShiftOpc = ARMISD::VQSHRNsu; break;
9538     case Intrinsic::arm_neon_vqrshiftns:
9539       VShiftOpc = ARMISD::VQRSHRNs; break;
9540     case Intrinsic::arm_neon_vqrshiftnu:
9541       VShiftOpc = ARMISD::VQRSHRNu; break;
9542     case Intrinsic::arm_neon_vqrshiftnsu:
9543       VShiftOpc = ARMISD::VQRSHRNsu; break;
9544     }
9545
9546     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9547                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9548   }
9549
9550   case Intrinsic::arm_neon_vshiftins: {
9551     EVT VT = N->getOperand(1).getValueType();
9552     int64_t Cnt;
9553     unsigned VShiftOpc = 0;
9554
9555     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9556       VShiftOpc = ARMISD::VSLI;
9557     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9558       VShiftOpc = ARMISD::VSRI;
9559     else {
9560       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9561     }
9562
9563     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9564                        N->getOperand(1), N->getOperand(2),
9565                        DAG.getConstant(Cnt, MVT::i32));
9566   }
9567
9568   case Intrinsic::arm_neon_vqrshifts:
9569   case Intrinsic::arm_neon_vqrshiftu:
9570     // No immediate versions of these to check for.
9571     break;
9572   }
9573
9574   return SDValue();
9575 }
9576
9577 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9578 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9579 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9580 /// vector element shift counts are generally not legal, and it is hard to see
9581 /// their values after they get legalized to loads from a constant pool.
9582 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9583                                    const ARMSubtarget *ST) {
9584   EVT VT = N->getValueType(0);
9585   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9586     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9587     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9588     SDValue N1 = N->getOperand(1);
9589     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9590       SDValue N0 = N->getOperand(0);
9591       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9592           DAG.MaskedValueIsZero(N0.getOperand(0),
9593                                 APInt::getHighBitsSet(32, 16)))
9594         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9595     }
9596   }
9597
9598   // Nothing to be done for scalar shifts.
9599   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9600   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9601     return SDValue();
9602
9603   assert(ST->hasNEON() && "unexpected vector shift");
9604   int64_t Cnt;
9605
9606   switch (N->getOpcode()) {
9607   default: llvm_unreachable("unexpected shift opcode");
9608
9609   case ISD::SHL:
9610     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9611       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9612                          DAG.getConstant(Cnt, MVT::i32));
9613     break;
9614
9615   case ISD::SRA:
9616   case ISD::SRL:
9617     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9618       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9619                             ARMISD::VSHRs : ARMISD::VSHRu);
9620       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9621                          DAG.getConstant(Cnt, MVT::i32));
9622     }
9623   }
9624   return SDValue();
9625 }
9626
9627 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9628 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9629 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9630                                     const ARMSubtarget *ST) {
9631   SDValue N0 = N->getOperand(0);
9632
9633   // Check for sign- and zero-extensions of vector extract operations of 8-
9634   // and 16-bit vector elements.  NEON supports these directly.  They are
9635   // handled during DAG combining because type legalization will promote them
9636   // to 32-bit types and it is messy to recognize the operations after that.
9637   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9638     SDValue Vec = N0.getOperand(0);
9639     SDValue Lane = N0.getOperand(1);
9640     EVT VT = N->getValueType(0);
9641     EVT EltVT = N0.getValueType();
9642     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9643
9644     if (VT == MVT::i32 &&
9645         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9646         TLI.isTypeLegal(Vec.getValueType()) &&
9647         isa<ConstantSDNode>(Lane)) {
9648
9649       unsigned Opc = 0;
9650       switch (N->getOpcode()) {
9651       default: llvm_unreachable("unexpected opcode");
9652       case ISD::SIGN_EXTEND:
9653         Opc = ARMISD::VGETLANEs;
9654         break;
9655       case ISD::ZERO_EXTEND:
9656       case ISD::ANY_EXTEND:
9657         Opc = ARMISD::VGETLANEu;
9658         break;
9659       }
9660       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9661     }
9662   }
9663
9664   return SDValue();
9665 }
9666
9667 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9668 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9669 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9670                                        const ARMSubtarget *ST) {
9671   // If the target supports NEON, try to use vmax/vmin instructions for f32
9672   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9673   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9674   // a NaN; only do the transformation when it matches that behavior.
9675
9676   // For now only do this when using NEON for FP operations; if using VFP, it
9677   // is not obvious that the benefit outweighs the cost of switching to the
9678   // NEON pipeline.
9679   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9680       N->getValueType(0) != MVT::f32)
9681     return SDValue();
9682
9683   SDValue CondLHS = N->getOperand(0);
9684   SDValue CondRHS = N->getOperand(1);
9685   SDValue LHS = N->getOperand(2);
9686   SDValue RHS = N->getOperand(3);
9687   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9688
9689   unsigned Opcode = 0;
9690   bool IsReversed;
9691   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9692     IsReversed = false; // x CC y ? x : y
9693   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9694     IsReversed = true ; // x CC y ? y : x
9695   } else {
9696     return SDValue();
9697   }
9698
9699   bool IsUnordered;
9700   switch (CC) {
9701   default: break;
9702   case ISD::SETOLT:
9703   case ISD::SETOLE:
9704   case ISD::SETLT:
9705   case ISD::SETLE:
9706   case ISD::SETULT:
9707   case ISD::SETULE:
9708     // If LHS is NaN, an ordered comparison will be false and the result will
9709     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9710     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9711     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9712     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9713       break;
9714     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9715     // will return -0, so vmin can only be used for unsafe math or if one of
9716     // the operands is known to be nonzero.
9717     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9718         !DAG.getTarget().Options.UnsafeFPMath &&
9719         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9720       break;
9721     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9722     break;
9723
9724   case ISD::SETOGT:
9725   case ISD::SETOGE:
9726   case ISD::SETGT:
9727   case ISD::SETGE:
9728   case ISD::SETUGT:
9729   case ISD::SETUGE:
9730     // If LHS is NaN, an ordered comparison will be false and the result will
9731     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9732     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9733     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9734     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9735       break;
9736     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9737     // will return +0, so vmax can only be used for unsafe math or if one of
9738     // the operands is known to be nonzero.
9739     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9740         !DAG.getTarget().Options.UnsafeFPMath &&
9741         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9742       break;
9743     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9744     break;
9745   }
9746
9747   if (!Opcode)
9748     return SDValue();
9749   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9750 }
9751
9752 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9753 SDValue
9754 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9755   SDValue Cmp = N->getOperand(4);
9756   if (Cmp.getOpcode() != ARMISD::CMPZ)
9757     // Only looking at EQ and NE cases.
9758     return SDValue();
9759
9760   EVT VT = N->getValueType(0);
9761   SDLoc dl(N);
9762   SDValue LHS = Cmp.getOperand(0);
9763   SDValue RHS = Cmp.getOperand(1);
9764   SDValue FalseVal = N->getOperand(0);
9765   SDValue TrueVal = N->getOperand(1);
9766   SDValue ARMcc = N->getOperand(2);
9767   ARMCC::CondCodes CC =
9768     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9769
9770   // Simplify
9771   //   mov     r1, r0
9772   //   cmp     r1, x
9773   //   mov     r0, y
9774   //   moveq   r0, x
9775   // to
9776   //   cmp     r0, x
9777   //   movne   r0, y
9778   //
9779   //   mov     r1, r0
9780   //   cmp     r1, x
9781   //   mov     r0, x
9782   //   movne   r0, y
9783   // to
9784   //   cmp     r0, x
9785   //   movne   r0, y
9786   /// FIXME: Turn this into a target neutral optimization?
9787   SDValue Res;
9788   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9789     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9790                       N->getOperand(3), Cmp);
9791   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9792     SDValue ARMcc;
9793     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9794     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9795                       N->getOperand(3), NewCmp);
9796   }
9797
9798   if (Res.getNode()) {
9799     APInt KnownZero, KnownOne;
9800     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9801     // Capture demanded bits information that would be otherwise lost.
9802     if (KnownZero == 0xfffffffe)
9803       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9804                         DAG.getValueType(MVT::i1));
9805     else if (KnownZero == 0xffffff00)
9806       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9807                         DAG.getValueType(MVT::i8));
9808     else if (KnownZero == 0xffff0000)
9809       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9810                         DAG.getValueType(MVT::i16));
9811   }
9812
9813   return Res;
9814 }
9815
9816 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9817                                              DAGCombinerInfo &DCI) const {
9818   switch (N->getOpcode()) {
9819   default: break;
9820   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9821   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9822   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9823   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9824   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9825   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9826   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9827   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9828   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9829   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9830   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9831   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9832   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9833   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9834   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9835   case ISD::FP_TO_SINT:
9836   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9837   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9838   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9839   case ISD::SHL:
9840   case ISD::SRA:
9841   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9842   case ISD::SIGN_EXTEND:
9843   case ISD::ZERO_EXTEND:
9844   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9845   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9846   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9847   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
9848   case ARMISD::VLD2DUP:
9849   case ARMISD::VLD3DUP:
9850   case ARMISD::VLD4DUP:
9851     return PerformVLDCombine(N, DCI);
9852   case ARMISD::BUILD_VECTOR:
9853     return PerformARMBUILD_VECTORCombine(N, DCI);
9854   case ISD::INTRINSIC_VOID:
9855   case ISD::INTRINSIC_W_CHAIN:
9856     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9857     case Intrinsic::arm_neon_vld1:
9858     case Intrinsic::arm_neon_vld2:
9859     case Intrinsic::arm_neon_vld3:
9860     case Intrinsic::arm_neon_vld4:
9861     case Intrinsic::arm_neon_vld2lane:
9862     case Intrinsic::arm_neon_vld3lane:
9863     case Intrinsic::arm_neon_vld4lane:
9864     case Intrinsic::arm_neon_vst1:
9865     case Intrinsic::arm_neon_vst2:
9866     case Intrinsic::arm_neon_vst3:
9867     case Intrinsic::arm_neon_vst4:
9868     case Intrinsic::arm_neon_vst2lane:
9869     case Intrinsic::arm_neon_vst3lane:
9870     case Intrinsic::arm_neon_vst4lane:
9871       return PerformVLDCombine(N, DCI);
9872     default: break;
9873     }
9874     break;
9875   }
9876   return SDValue();
9877 }
9878
9879 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9880                                                           EVT VT) const {
9881   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9882 }
9883
9884 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9885                                                        unsigned,
9886                                                        unsigned,
9887                                                        bool *Fast) const {
9888   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9889   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9890
9891   switch (VT.getSimpleVT().SimpleTy) {
9892   default:
9893     return false;
9894   case MVT::i8:
9895   case MVT::i16:
9896   case MVT::i32: {
9897     // Unaligned access can use (for example) LRDB, LRDH, LDR
9898     if (AllowsUnaligned) {
9899       if (Fast)
9900         *Fast = Subtarget->hasV7Ops();
9901       return true;
9902     }
9903     return false;
9904   }
9905   case MVT::f64:
9906   case MVT::v2f64: {
9907     // For any little-endian targets with neon, we can support unaligned ld/st
9908     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9909     // A big-endian target may also explicitly support unaligned accesses
9910     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9911       if (Fast)
9912         *Fast = true;
9913       return true;
9914     }
9915     return false;
9916   }
9917   }
9918 }
9919
9920 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9921                        unsigned AlignCheck) {
9922   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9923           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9924 }
9925
9926 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9927                                            unsigned DstAlign, unsigned SrcAlign,
9928                                            bool IsMemset, bool ZeroMemset,
9929                                            bool MemcpyStrSrc,
9930                                            MachineFunction &MF) const {
9931   const Function *F = MF.getFunction();
9932
9933   // See if we can use NEON instructions for this...
9934   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
9935       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
9936     bool Fast;
9937     if (Size >= 16 &&
9938         (memOpAlign(SrcAlign, DstAlign, 16) ||
9939          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9940       return MVT::v2f64;
9941     } else if (Size >= 8 &&
9942                (memOpAlign(SrcAlign, DstAlign, 8) ||
9943                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9944                  Fast))) {
9945       return MVT::f64;
9946     }
9947   }
9948
9949   // Lowering to i32/i16 if the size permits.
9950   if (Size >= 4)
9951     return MVT::i32;
9952   else if (Size >= 2)
9953     return MVT::i16;
9954
9955   // Let the target-independent logic figure it out.
9956   return MVT::Other;
9957 }
9958
9959 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9960   if (Val.getOpcode() != ISD::LOAD)
9961     return false;
9962
9963   EVT VT1 = Val.getValueType();
9964   if (!VT1.isSimple() || !VT1.isInteger() ||
9965       !VT2.isSimple() || !VT2.isInteger())
9966     return false;
9967
9968   switch (VT1.getSimpleVT().SimpleTy) {
9969   default: break;
9970   case MVT::i1:
9971   case MVT::i8:
9972   case MVT::i16:
9973     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9974     return true;
9975   }
9976
9977   return false;
9978 }
9979
9980 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
9981   EVT VT = ExtVal.getValueType();
9982
9983   if (!isTypeLegal(VT))
9984     return false;
9985
9986   // Don't create a loadext if we can fold the extension into a wide/long
9987   // instruction.
9988   // If there's more than one user instruction, the loadext is desirable no
9989   // matter what.  There can be two uses by the same instruction.
9990   if (ExtVal->use_empty() ||
9991       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
9992     return true;
9993
9994   SDNode *U = *ExtVal->use_begin();
9995   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
9996        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
9997     return false;
9998
9999   return true;
10000 }
10001
10002 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10003   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10004     return false;
10005
10006   if (!isTypeLegal(EVT::getEVT(Ty1)))
10007     return false;
10008
10009   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10010
10011   // Assuming the caller doesn't have a zeroext or signext return parameter,
10012   // truncation all the way down to i1 is valid.
10013   return true;
10014 }
10015
10016
10017 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10018   if (V < 0)
10019     return false;
10020
10021   unsigned Scale = 1;
10022   switch (VT.getSimpleVT().SimpleTy) {
10023   default: return false;
10024   case MVT::i1:
10025   case MVT::i8:
10026     // Scale == 1;
10027     break;
10028   case MVT::i16:
10029     // Scale == 2;
10030     Scale = 2;
10031     break;
10032   case MVT::i32:
10033     // Scale == 4;
10034     Scale = 4;
10035     break;
10036   }
10037
10038   if ((V & (Scale - 1)) != 0)
10039     return false;
10040   V /= Scale;
10041   return V == (V & ((1LL << 5) - 1));
10042 }
10043
10044 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10045                                       const ARMSubtarget *Subtarget) {
10046   bool isNeg = false;
10047   if (V < 0) {
10048     isNeg = true;
10049     V = - V;
10050   }
10051
10052   switch (VT.getSimpleVT().SimpleTy) {
10053   default: return false;
10054   case MVT::i1:
10055   case MVT::i8:
10056   case MVT::i16:
10057   case MVT::i32:
10058     // + imm12 or - imm8
10059     if (isNeg)
10060       return V == (V & ((1LL << 8) - 1));
10061     return V == (V & ((1LL << 12) - 1));
10062   case MVT::f32:
10063   case MVT::f64:
10064     // Same as ARM mode. FIXME: NEON?
10065     if (!Subtarget->hasVFP2())
10066       return false;
10067     if ((V & 3) != 0)
10068       return false;
10069     V >>= 2;
10070     return V == (V & ((1LL << 8) - 1));
10071   }
10072 }
10073
10074 /// isLegalAddressImmediate - Return true if the integer value can be used
10075 /// as the offset of the target addressing mode for load / store of the
10076 /// given type.
10077 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10078                                     const ARMSubtarget *Subtarget) {
10079   if (V == 0)
10080     return true;
10081
10082   if (!VT.isSimple())
10083     return false;
10084
10085   if (Subtarget->isThumb1Only())
10086     return isLegalT1AddressImmediate(V, VT);
10087   else if (Subtarget->isThumb2())
10088     return isLegalT2AddressImmediate(V, VT, Subtarget);
10089
10090   // ARM mode.
10091   if (V < 0)
10092     V = - V;
10093   switch (VT.getSimpleVT().SimpleTy) {
10094   default: return false;
10095   case MVT::i1:
10096   case MVT::i8:
10097   case MVT::i32:
10098     // +- imm12
10099     return V == (V & ((1LL << 12) - 1));
10100   case MVT::i16:
10101     // +- imm8
10102     return V == (V & ((1LL << 8) - 1));
10103   case MVT::f32:
10104   case MVT::f64:
10105     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10106       return false;
10107     if ((V & 3) != 0)
10108       return false;
10109     V >>= 2;
10110     return V == (V & ((1LL << 8) - 1));
10111   }
10112 }
10113
10114 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10115                                                       EVT VT) const {
10116   int Scale = AM.Scale;
10117   if (Scale < 0)
10118     return false;
10119
10120   switch (VT.getSimpleVT().SimpleTy) {
10121   default: return false;
10122   case MVT::i1:
10123   case MVT::i8:
10124   case MVT::i16:
10125   case MVT::i32:
10126     if (Scale == 1)
10127       return true;
10128     // r + r << imm
10129     Scale = Scale & ~1;
10130     return Scale == 2 || Scale == 4 || Scale == 8;
10131   case MVT::i64:
10132     // r + r
10133     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10134       return true;
10135     return false;
10136   case MVT::isVoid:
10137     // Note, we allow "void" uses (basically, uses that aren't loads or
10138     // stores), because arm allows folding a scale into many arithmetic
10139     // operations.  This should be made more precise and revisited later.
10140
10141     // Allow r << imm, but the imm has to be a multiple of two.
10142     if (Scale & 1) return false;
10143     return isPowerOf2_32(Scale);
10144   }
10145 }
10146
10147 /// isLegalAddressingMode - Return true if the addressing mode represented
10148 /// by AM is legal for this target, for a load/store of the specified type.
10149 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10150                                               Type *Ty) const {
10151   EVT VT = getValueType(Ty, true);
10152   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10153     return false;
10154
10155   // Can never fold addr of global into load/store.
10156   if (AM.BaseGV)
10157     return false;
10158
10159   switch (AM.Scale) {
10160   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10161     break;
10162   case 1:
10163     if (Subtarget->isThumb1Only())
10164       return false;
10165     // FALL THROUGH.
10166   default:
10167     // ARM doesn't support any R+R*scale+imm addr modes.
10168     if (AM.BaseOffs)
10169       return false;
10170
10171     if (!VT.isSimple())
10172       return false;
10173
10174     if (Subtarget->isThumb2())
10175       return isLegalT2ScaledAddressingMode(AM, VT);
10176
10177     int Scale = AM.Scale;
10178     switch (VT.getSimpleVT().SimpleTy) {
10179     default: return false;
10180     case MVT::i1:
10181     case MVT::i8:
10182     case MVT::i32:
10183       if (Scale < 0) Scale = -Scale;
10184       if (Scale == 1)
10185         return true;
10186       // r + r << imm
10187       return isPowerOf2_32(Scale & ~1);
10188     case MVT::i16:
10189     case MVT::i64:
10190       // r + r
10191       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10192         return true;
10193       return false;
10194
10195     case MVT::isVoid:
10196       // Note, we allow "void" uses (basically, uses that aren't loads or
10197       // stores), because arm allows folding a scale into many arithmetic
10198       // operations.  This should be made more precise and revisited later.
10199
10200       // Allow r << imm, but the imm has to be a multiple of two.
10201       if (Scale & 1) return false;
10202       return isPowerOf2_32(Scale);
10203     }
10204   }
10205   return true;
10206 }
10207
10208 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10209 /// icmp immediate, that is the target has icmp instructions which can compare
10210 /// a register against the immediate without having to materialize the
10211 /// immediate into a register.
10212 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10213   // Thumb2 and ARM modes can use cmn for negative immediates.
10214   if (!Subtarget->isThumb())
10215     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10216   if (Subtarget->isThumb2())
10217     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10218   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10219   return Imm >= 0 && Imm <= 255;
10220 }
10221
10222 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10223 /// *or sub* immediate, that is the target has add or sub instructions which can
10224 /// add a register with the immediate without having to materialize the
10225 /// immediate into a register.
10226 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10227   // Same encoding for add/sub, just flip the sign.
10228   int64_t AbsImm = std::abs(Imm);
10229   if (!Subtarget->isThumb())
10230     return ARM_AM::getSOImmVal(AbsImm) != -1;
10231   if (Subtarget->isThumb2())
10232     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10233   // Thumb1 only has 8-bit unsigned immediate.
10234   return AbsImm >= 0 && AbsImm <= 255;
10235 }
10236
10237 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10238                                       bool isSEXTLoad, SDValue &Base,
10239                                       SDValue &Offset, bool &isInc,
10240                                       SelectionDAG &DAG) {
10241   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10242     return false;
10243
10244   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10245     // AddressingMode 3
10246     Base = Ptr->getOperand(0);
10247     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10248       int RHSC = (int)RHS->getZExtValue();
10249       if (RHSC < 0 && RHSC > -256) {
10250         assert(Ptr->getOpcode() == ISD::ADD);
10251         isInc = false;
10252         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10253         return true;
10254       }
10255     }
10256     isInc = (Ptr->getOpcode() == ISD::ADD);
10257     Offset = Ptr->getOperand(1);
10258     return true;
10259   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10260     // AddressingMode 2
10261     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10262       int RHSC = (int)RHS->getZExtValue();
10263       if (RHSC < 0 && RHSC > -0x1000) {
10264         assert(Ptr->getOpcode() == ISD::ADD);
10265         isInc = false;
10266         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10267         Base = Ptr->getOperand(0);
10268         return true;
10269       }
10270     }
10271
10272     if (Ptr->getOpcode() == ISD::ADD) {
10273       isInc = true;
10274       ARM_AM::ShiftOpc ShOpcVal=
10275         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10276       if (ShOpcVal != ARM_AM::no_shift) {
10277         Base = Ptr->getOperand(1);
10278         Offset = Ptr->getOperand(0);
10279       } else {
10280         Base = Ptr->getOperand(0);
10281         Offset = Ptr->getOperand(1);
10282       }
10283       return true;
10284     }
10285
10286     isInc = (Ptr->getOpcode() == ISD::ADD);
10287     Base = Ptr->getOperand(0);
10288     Offset = Ptr->getOperand(1);
10289     return true;
10290   }
10291
10292   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10293   return false;
10294 }
10295
10296 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10297                                      bool isSEXTLoad, SDValue &Base,
10298                                      SDValue &Offset, bool &isInc,
10299                                      SelectionDAG &DAG) {
10300   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10301     return false;
10302
10303   Base = Ptr->getOperand(0);
10304   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10305     int RHSC = (int)RHS->getZExtValue();
10306     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10307       assert(Ptr->getOpcode() == ISD::ADD);
10308       isInc = false;
10309       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10310       return true;
10311     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10312       isInc = Ptr->getOpcode() == ISD::ADD;
10313       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10314       return true;
10315     }
10316   }
10317
10318   return false;
10319 }
10320
10321 /// getPreIndexedAddressParts - returns true by value, base pointer and
10322 /// offset pointer and addressing mode by reference if the node's address
10323 /// can be legally represented as pre-indexed load / store address.
10324 bool
10325 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10326                                              SDValue &Offset,
10327                                              ISD::MemIndexedMode &AM,
10328                                              SelectionDAG &DAG) const {
10329   if (Subtarget->isThumb1Only())
10330     return false;
10331
10332   EVT VT;
10333   SDValue Ptr;
10334   bool isSEXTLoad = false;
10335   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10336     Ptr = LD->getBasePtr();
10337     VT  = LD->getMemoryVT();
10338     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10339   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10340     Ptr = ST->getBasePtr();
10341     VT  = ST->getMemoryVT();
10342   } else
10343     return false;
10344
10345   bool isInc;
10346   bool isLegal = false;
10347   if (Subtarget->isThumb2())
10348     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10349                                        Offset, isInc, DAG);
10350   else
10351     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10352                                         Offset, isInc, DAG);
10353   if (!isLegal)
10354     return false;
10355
10356   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10357   return true;
10358 }
10359
10360 /// getPostIndexedAddressParts - returns true by value, base pointer and
10361 /// offset pointer and addressing mode by reference if this node can be
10362 /// combined with a load / store to form a post-indexed load / store.
10363 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10364                                                    SDValue &Base,
10365                                                    SDValue &Offset,
10366                                                    ISD::MemIndexedMode &AM,
10367                                                    SelectionDAG &DAG) const {
10368   if (Subtarget->isThumb1Only())
10369     return false;
10370
10371   EVT VT;
10372   SDValue Ptr;
10373   bool isSEXTLoad = false;
10374   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10375     VT  = LD->getMemoryVT();
10376     Ptr = LD->getBasePtr();
10377     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10378   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10379     VT  = ST->getMemoryVT();
10380     Ptr = ST->getBasePtr();
10381   } else
10382     return false;
10383
10384   bool isInc;
10385   bool isLegal = false;
10386   if (Subtarget->isThumb2())
10387     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10388                                        isInc, DAG);
10389   else
10390     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10391                                         isInc, DAG);
10392   if (!isLegal)
10393     return false;
10394
10395   if (Ptr != Base) {
10396     // Swap base ptr and offset to catch more post-index load / store when
10397     // it's legal. In Thumb2 mode, offset must be an immediate.
10398     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10399         !Subtarget->isThumb2())
10400       std::swap(Base, Offset);
10401
10402     // Post-indexed load / store update the base pointer.
10403     if (Ptr != Base)
10404       return false;
10405   }
10406
10407   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10408   return true;
10409 }
10410
10411 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10412                                                       APInt &KnownZero,
10413                                                       APInt &KnownOne,
10414                                                       const SelectionDAG &DAG,
10415                                                       unsigned Depth) const {
10416   unsigned BitWidth = KnownOne.getBitWidth();
10417   KnownZero = KnownOne = APInt(BitWidth, 0);
10418   switch (Op.getOpcode()) {
10419   default: break;
10420   case ARMISD::ADDC:
10421   case ARMISD::ADDE:
10422   case ARMISD::SUBC:
10423   case ARMISD::SUBE:
10424     // These nodes' second result is a boolean
10425     if (Op.getResNo() == 0)
10426       break;
10427     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10428     break;
10429   case ARMISD::CMOV: {
10430     // Bits are known zero/one if known on the LHS and RHS.
10431     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10432     if (KnownZero == 0 && KnownOne == 0) return;
10433
10434     APInt KnownZeroRHS, KnownOneRHS;
10435     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10436     KnownZero &= KnownZeroRHS;
10437     KnownOne  &= KnownOneRHS;
10438     return;
10439   }
10440   case ISD::INTRINSIC_W_CHAIN: {
10441     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10442     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10443     switch (IntID) {
10444     default: return;
10445     case Intrinsic::arm_ldaex:
10446     case Intrinsic::arm_ldrex: {
10447       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10448       unsigned MemBits = VT.getScalarType().getSizeInBits();
10449       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10450       return;
10451     }
10452     }
10453   }
10454   }
10455 }
10456
10457 //===----------------------------------------------------------------------===//
10458 //                           ARM Inline Assembly Support
10459 //===----------------------------------------------------------------------===//
10460
10461 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10462   // Looking for "rev" which is V6+.
10463   if (!Subtarget->hasV6Ops())
10464     return false;
10465
10466   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10467   std::string AsmStr = IA->getAsmString();
10468   SmallVector<StringRef, 4> AsmPieces;
10469   SplitString(AsmStr, AsmPieces, ";\n");
10470
10471   switch (AsmPieces.size()) {
10472   default: return false;
10473   case 1:
10474     AsmStr = AsmPieces[0];
10475     AsmPieces.clear();
10476     SplitString(AsmStr, AsmPieces, " \t,");
10477
10478     // rev $0, $1
10479     if (AsmPieces.size() == 3 &&
10480         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10481         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10482       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10483       if (Ty && Ty->getBitWidth() == 32)
10484         return IntrinsicLowering::LowerToByteSwap(CI);
10485     }
10486     break;
10487   }
10488
10489   return false;
10490 }
10491
10492 /// getConstraintType - Given a constraint letter, return the type of
10493 /// constraint it is for this target.
10494 ARMTargetLowering::ConstraintType
10495 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10496   if (Constraint.size() == 1) {
10497     switch (Constraint[0]) {
10498     default:  break;
10499     case 'l': return C_RegisterClass;
10500     case 'w': return C_RegisterClass;
10501     case 'h': return C_RegisterClass;
10502     case 'x': return C_RegisterClass;
10503     case 't': return C_RegisterClass;
10504     case 'j': return C_Other; // Constant for movw.
10505       // An address with a single base register. Due to the way we
10506       // currently handle addresses it is the same as an 'r' memory constraint.
10507     case 'Q': return C_Memory;
10508     }
10509   } else if (Constraint.size() == 2) {
10510     switch (Constraint[0]) {
10511     default: break;
10512     // All 'U+' constraints are addresses.
10513     case 'U': return C_Memory;
10514     }
10515   }
10516   return TargetLowering::getConstraintType(Constraint);
10517 }
10518
10519 /// Examine constraint type and operand type and determine a weight value.
10520 /// This object must already have been set up with the operand type
10521 /// and the current alternative constraint selected.
10522 TargetLowering::ConstraintWeight
10523 ARMTargetLowering::getSingleConstraintMatchWeight(
10524     AsmOperandInfo &info, const char *constraint) const {
10525   ConstraintWeight weight = CW_Invalid;
10526   Value *CallOperandVal = info.CallOperandVal;
10527     // If we don't have a value, we can't do a match,
10528     // but allow it at the lowest weight.
10529   if (!CallOperandVal)
10530     return CW_Default;
10531   Type *type = CallOperandVal->getType();
10532   // Look at the constraint type.
10533   switch (*constraint) {
10534   default:
10535     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10536     break;
10537   case 'l':
10538     if (type->isIntegerTy()) {
10539       if (Subtarget->isThumb())
10540         weight = CW_SpecificReg;
10541       else
10542         weight = CW_Register;
10543     }
10544     break;
10545   case 'w':
10546     if (type->isFloatingPointTy())
10547       weight = CW_Register;
10548     break;
10549   }
10550   return weight;
10551 }
10552
10553 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10554 RCPair
10555 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10556                                                 const std::string &Constraint,
10557                                                 MVT VT) const {
10558   if (Constraint.size() == 1) {
10559     // GCC ARM Constraint Letters
10560     switch (Constraint[0]) {
10561     case 'l': // Low regs or general regs.
10562       if (Subtarget->isThumb())
10563         return RCPair(0U, &ARM::tGPRRegClass);
10564       return RCPair(0U, &ARM::GPRRegClass);
10565     case 'h': // High regs or no regs.
10566       if (Subtarget->isThumb())
10567         return RCPair(0U, &ARM::hGPRRegClass);
10568       break;
10569     case 'r':
10570       if (Subtarget->isThumb1Only())
10571         return RCPair(0U, &ARM::tGPRRegClass);
10572       return RCPair(0U, &ARM::GPRRegClass);
10573     case 'w':
10574       if (VT == MVT::Other)
10575         break;
10576       if (VT == MVT::f32)
10577         return RCPair(0U, &ARM::SPRRegClass);
10578       if (VT.getSizeInBits() == 64)
10579         return RCPair(0U, &ARM::DPRRegClass);
10580       if (VT.getSizeInBits() == 128)
10581         return RCPair(0U, &ARM::QPRRegClass);
10582       break;
10583     case 'x':
10584       if (VT == MVT::Other)
10585         break;
10586       if (VT == MVT::f32)
10587         return RCPair(0U, &ARM::SPR_8RegClass);
10588       if (VT.getSizeInBits() == 64)
10589         return RCPair(0U, &ARM::DPR_8RegClass);
10590       if (VT.getSizeInBits() == 128)
10591         return RCPair(0U, &ARM::QPR_8RegClass);
10592       break;
10593     case 't':
10594       if (VT == MVT::f32)
10595         return RCPair(0U, &ARM::SPRRegClass);
10596       break;
10597     }
10598   }
10599   if (StringRef("{cc}").equals_lower(Constraint))
10600     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10601
10602   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10603 }
10604
10605 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10606 /// vector.  If it is invalid, don't add anything to Ops.
10607 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10608                                                      std::string &Constraint,
10609                                                      std::vector<SDValue>&Ops,
10610                                                      SelectionDAG &DAG) const {
10611   SDValue Result;
10612
10613   // Currently only support length 1 constraints.
10614   if (Constraint.length() != 1) return;
10615
10616   char ConstraintLetter = Constraint[0];
10617   switch (ConstraintLetter) {
10618   default: break;
10619   case 'j':
10620   case 'I': case 'J': case 'K': case 'L':
10621   case 'M': case 'N': case 'O':
10622     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10623     if (!C)
10624       return;
10625
10626     int64_t CVal64 = C->getSExtValue();
10627     int CVal = (int) CVal64;
10628     // None of these constraints allow values larger than 32 bits.  Check
10629     // that the value fits in an int.
10630     if (CVal != CVal64)
10631       return;
10632
10633     switch (ConstraintLetter) {
10634       case 'j':
10635         // Constant suitable for movw, must be between 0 and
10636         // 65535.
10637         if (Subtarget->hasV6T2Ops())
10638           if (CVal >= 0 && CVal <= 65535)
10639             break;
10640         return;
10641       case 'I':
10642         if (Subtarget->isThumb1Only()) {
10643           // This must be a constant between 0 and 255, for ADD
10644           // immediates.
10645           if (CVal >= 0 && CVal <= 255)
10646             break;
10647         } else if (Subtarget->isThumb2()) {
10648           // A constant that can be used as an immediate value in a
10649           // data-processing instruction.
10650           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10651             break;
10652         } else {
10653           // A constant that can be used as an immediate value in a
10654           // data-processing instruction.
10655           if (ARM_AM::getSOImmVal(CVal) != -1)
10656             break;
10657         }
10658         return;
10659
10660       case 'J':
10661         if (Subtarget->isThumb()) {  // FIXME thumb2
10662           // This must be a constant between -255 and -1, for negated ADD
10663           // immediates. This can be used in GCC with an "n" modifier that
10664           // prints the negated value, for use with SUB instructions. It is
10665           // not useful otherwise but is implemented for compatibility.
10666           if (CVal >= -255 && CVal <= -1)
10667             break;
10668         } else {
10669           // This must be a constant between -4095 and 4095. It is not clear
10670           // what this constraint is intended for. Implemented for
10671           // compatibility with GCC.
10672           if (CVal >= -4095 && CVal <= 4095)
10673             break;
10674         }
10675         return;
10676
10677       case 'K':
10678         if (Subtarget->isThumb1Only()) {
10679           // A 32-bit value where only one byte has a nonzero value. Exclude
10680           // zero to match GCC. This constraint is used by GCC internally for
10681           // constants that can be loaded with a move/shift combination.
10682           // It is not useful otherwise but is implemented for compatibility.
10683           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10684             break;
10685         } else if (Subtarget->isThumb2()) {
10686           // A constant whose bitwise inverse can be used as an immediate
10687           // value in a data-processing instruction. This can be used in GCC
10688           // with a "B" modifier that prints the inverted value, for use with
10689           // BIC and MVN instructions. It is not useful otherwise but is
10690           // implemented for compatibility.
10691           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10692             break;
10693         } else {
10694           // A constant whose bitwise inverse can be used as an immediate
10695           // value in a data-processing instruction. This can be used in GCC
10696           // with a "B" modifier that prints the inverted value, for use with
10697           // BIC and MVN instructions. It is not useful otherwise but is
10698           // implemented for compatibility.
10699           if (ARM_AM::getSOImmVal(~CVal) != -1)
10700             break;
10701         }
10702         return;
10703
10704       case 'L':
10705         if (Subtarget->isThumb1Only()) {
10706           // This must be a constant between -7 and 7,
10707           // for 3-operand ADD/SUB immediate instructions.
10708           if (CVal >= -7 && CVal < 7)
10709             break;
10710         } else if (Subtarget->isThumb2()) {
10711           // A constant whose negation can be used as an immediate value in a
10712           // data-processing instruction. This can be used in GCC with an "n"
10713           // modifier that prints the negated value, for use with SUB
10714           // instructions. It is not useful otherwise but is implemented for
10715           // compatibility.
10716           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10717             break;
10718         } else {
10719           // A constant whose negation can be used as an immediate value in a
10720           // data-processing instruction. This can be used in GCC with an "n"
10721           // modifier that prints the negated value, for use with SUB
10722           // instructions. It is not useful otherwise but is implemented for
10723           // compatibility.
10724           if (ARM_AM::getSOImmVal(-CVal) != -1)
10725             break;
10726         }
10727         return;
10728
10729       case 'M':
10730         if (Subtarget->isThumb()) { // FIXME thumb2
10731           // This must be a multiple of 4 between 0 and 1020, for
10732           // ADD sp + immediate.
10733           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10734             break;
10735         } else {
10736           // A power of two or a constant between 0 and 32.  This is used in
10737           // GCC for the shift amount on shifted register operands, but it is
10738           // useful in general for any shift amounts.
10739           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10740             break;
10741         }
10742         return;
10743
10744       case 'N':
10745         if (Subtarget->isThumb()) {  // FIXME thumb2
10746           // This must be a constant between 0 and 31, for shift amounts.
10747           if (CVal >= 0 && CVal <= 31)
10748             break;
10749         }
10750         return;
10751
10752       case 'O':
10753         if (Subtarget->isThumb()) {  // FIXME thumb2
10754           // This must be a multiple of 4 between -508 and 508, for
10755           // ADD/SUB sp = sp + immediate.
10756           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10757             break;
10758         }
10759         return;
10760     }
10761     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10762     break;
10763   }
10764
10765   if (Result.getNode()) {
10766     Ops.push_back(Result);
10767     return;
10768   }
10769   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10770 }
10771
10772 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10773   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10774   unsigned Opcode = Op->getOpcode();
10775   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10776          "Invalid opcode for Div/Rem lowering");
10777   bool isSigned = (Opcode == ISD::SDIVREM);
10778   EVT VT = Op->getValueType(0);
10779   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10780
10781   RTLIB::Libcall LC;
10782   switch (VT.getSimpleVT().SimpleTy) {
10783   default: llvm_unreachable("Unexpected request for libcall!");
10784   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10785   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10786   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10787   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10788   }
10789
10790   SDValue InChain = DAG.getEntryNode();
10791
10792   TargetLowering::ArgListTy Args;
10793   TargetLowering::ArgListEntry Entry;
10794   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10795     EVT ArgVT = Op->getOperand(i).getValueType();
10796     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10797     Entry.Node = Op->getOperand(i);
10798     Entry.Ty = ArgTy;
10799     Entry.isSExt = isSigned;
10800     Entry.isZExt = !isSigned;
10801     Args.push_back(Entry);
10802   }
10803
10804   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10805                                          getPointerTy());
10806
10807   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10808
10809   SDLoc dl(Op);
10810   TargetLowering::CallLoweringInfo CLI(DAG);
10811   CLI.setDebugLoc(dl).setChain(InChain)
10812     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10813     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10814
10815   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10816   return CallInfo.first;
10817 }
10818
10819 SDValue
10820 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10821   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10822   SDLoc DL(Op);
10823
10824   // Get the inputs.
10825   SDValue Chain = Op.getOperand(0);
10826   SDValue Size  = Op.getOperand(1);
10827
10828   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10829                               DAG.getConstant(2, MVT::i32));
10830
10831   SDValue Flag;
10832   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10833   Flag = Chain.getValue(1);
10834
10835   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10836   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10837
10838   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10839   Chain = NewSP.getValue(1);
10840
10841   SDValue Ops[2] = { NewSP, Chain };
10842   return DAG.getMergeValues(Ops, DL);
10843 }
10844
10845 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10846   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10847          "Unexpected type for custom-lowering FP_EXTEND");
10848
10849   RTLIB::Libcall LC;
10850   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10851
10852   SDValue SrcVal = Op.getOperand(0);
10853   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10854                      /*isSigned*/ false, SDLoc(Op)).first;
10855 }
10856
10857 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10858   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10859          Subtarget->isFPOnlySP() &&
10860          "Unexpected type for custom-lowering FP_ROUND");
10861
10862   RTLIB::Libcall LC;
10863   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10864
10865   SDValue SrcVal = Op.getOperand(0);
10866   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10867                      /*isSigned*/ false, SDLoc(Op)).first;
10868 }
10869
10870 bool
10871 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10872   // The ARM target isn't yet aware of offsets.
10873   return false;
10874 }
10875
10876 bool ARM::isBitFieldInvertedMask(unsigned v) {
10877   if (v == 0xffffffff)
10878     return false;
10879
10880   // there can be 1's on either or both "outsides", all the "inside"
10881   // bits must be 0's
10882   return isShiftedMask_32(~v);
10883 }
10884
10885 /// isFPImmLegal - Returns true if the target can instruction select the
10886 /// specified FP immediate natively. If false, the legalizer will
10887 /// materialize the FP immediate as a load from a constant pool.
10888 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10889   if (!Subtarget->hasVFP3())
10890     return false;
10891   if (VT == MVT::f32)
10892     return ARM_AM::getFP32Imm(Imm) != -1;
10893   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10894     return ARM_AM::getFP64Imm(Imm) != -1;
10895   return false;
10896 }
10897
10898 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10899 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10900 /// specified in the intrinsic calls.
10901 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10902                                            const CallInst &I,
10903                                            unsigned Intrinsic) const {
10904   switch (Intrinsic) {
10905   case Intrinsic::arm_neon_vld1:
10906   case Intrinsic::arm_neon_vld2:
10907   case Intrinsic::arm_neon_vld3:
10908   case Intrinsic::arm_neon_vld4:
10909   case Intrinsic::arm_neon_vld2lane:
10910   case Intrinsic::arm_neon_vld3lane:
10911   case Intrinsic::arm_neon_vld4lane: {
10912     Info.opc = ISD::INTRINSIC_W_CHAIN;
10913     // Conservatively set memVT to the entire set of vectors loaded.
10914     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10915     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10916     Info.ptrVal = I.getArgOperand(0);
10917     Info.offset = 0;
10918     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10919     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10920     Info.vol = false; // volatile loads with NEON intrinsics not supported
10921     Info.readMem = true;
10922     Info.writeMem = false;
10923     return true;
10924   }
10925   case Intrinsic::arm_neon_vst1:
10926   case Intrinsic::arm_neon_vst2:
10927   case Intrinsic::arm_neon_vst3:
10928   case Intrinsic::arm_neon_vst4:
10929   case Intrinsic::arm_neon_vst2lane:
10930   case Intrinsic::arm_neon_vst3lane:
10931   case Intrinsic::arm_neon_vst4lane: {
10932     Info.opc = ISD::INTRINSIC_VOID;
10933     // Conservatively set memVT to the entire set of vectors stored.
10934     unsigned NumElts = 0;
10935     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10936       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10937       if (!ArgTy->isVectorTy())
10938         break;
10939       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10940     }
10941     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10942     Info.ptrVal = I.getArgOperand(0);
10943     Info.offset = 0;
10944     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10945     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10946     Info.vol = false; // volatile stores with NEON intrinsics not supported
10947     Info.readMem = false;
10948     Info.writeMem = true;
10949     return true;
10950   }
10951   case Intrinsic::arm_ldaex:
10952   case Intrinsic::arm_ldrex: {
10953     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10954     Info.opc = ISD::INTRINSIC_W_CHAIN;
10955     Info.memVT = MVT::getVT(PtrTy->getElementType());
10956     Info.ptrVal = I.getArgOperand(0);
10957     Info.offset = 0;
10958     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10959     Info.vol = true;
10960     Info.readMem = true;
10961     Info.writeMem = false;
10962     return true;
10963   }
10964   case Intrinsic::arm_stlex:
10965   case Intrinsic::arm_strex: {
10966     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10967     Info.opc = ISD::INTRINSIC_W_CHAIN;
10968     Info.memVT = MVT::getVT(PtrTy->getElementType());
10969     Info.ptrVal = I.getArgOperand(1);
10970     Info.offset = 0;
10971     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10972     Info.vol = true;
10973     Info.readMem = false;
10974     Info.writeMem = true;
10975     return true;
10976   }
10977   case Intrinsic::arm_stlexd:
10978   case Intrinsic::arm_strexd: {
10979     Info.opc = ISD::INTRINSIC_W_CHAIN;
10980     Info.memVT = MVT::i64;
10981     Info.ptrVal = I.getArgOperand(2);
10982     Info.offset = 0;
10983     Info.align = 8;
10984     Info.vol = true;
10985     Info.readMem = false;
10986     Info.writeMem = true;
10987     return true;
10988   }
10989   case Intrinsic::arm_ldaexd:
10990   case Intrinsic::arm_ldrexd: {
10991     Info.opc = ISD::INTRINSIC_W_CHAIN;
10992     Info.memVT = MVT::i64;
10993     Info.ptrVal = I.getArgOperand(0);
10994     Info.offset = 0;
10995     Info.align = 8;
10996     Info.vol = true;
10997     Info.readMem = true;
10998     Info.writeMem = false;
10999     return true;
11000   }
11001   default:
11002     break;
11003   }
11004
11005   return false;
11006 }
11007
11008 /// \brief Returns true if it is beneficial to convert a load of a constant
11009 /// to just the constant itself.
11010 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11011                                                           Type *Ty) const {
11012   assert(Ty->isIntegerTy());
11013
11014   unsigned Bits = Ty->getPrimitiveSizeInBits();
11015   if (Bits == 0 || Bits > 32)
11016     return false;
11017   return true;
11018 }
11019
11020 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11021
11022 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11023                                         ARM_MB::MemBOpt Domain) const {
11024   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11025
11026   // First, if the target has no DMB, see what fallback we can use.
11027   if (!Subtarget->hasDataBarrier()) {
11028     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11029     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11030     // here.
11031     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11032       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11033       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11034                         Builder.getInt32(0), Builder.getInt32(7),
11035                         Builder.getInt32(10), Builder.getInt32(5)};
11036       return Builder.CreateCall(MCR, args);
11037     } else {
11038       // Instead of using barriers, atomic accesses on these subtargets use
11039       // libcalls.
11040       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11041     }
11042   } else {
11043     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11044     // Only a full system barrier exists in the M-class architectures.
11045     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11046     Constant *CDomain = Builder.getInt32(Domain);
11047     return Builder.CreateCall(DMB, CDomain);
11048   }
11049 }
11050
11051 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11052 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11053                                          AtomicOrdering Ord, bool IsStore,
11054                                          bool IsLoad) const {
11055   if (!getInsertFencesForAtomic())
11056     return nullptr;
11057
11058   switch (Ord) {
11059   case NotAtomic:
11060   case Unordered:
11061     llvm_unreachable("Invalid fence: unordered/non-atomic");
11062   case Monotonic:
11063   case Acquire:
11064     return nullptr; // Nothing to do
11065   case SequentiallyConsistent:
11066     if (!IsStore)
11067       return nullptr; // Nothing to do
11068     /*FALLTHROUGH*/
11069   case Release:
11070   case AcquireRelease:
11071     if (Subtarget->isSwift())
11072       return makeDMB(Builder, ARM_MB::ISHST);
11073     // FIXME: add a comment with a link to documentation justifying this.
11074     else
11075       return makeDMB(Builder, ARM_MB::ISH);
11076   }
11077   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11078 }
11079
11080 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11081                                           AtomicOrdering Ord, bool IsStore,
11082                                           bool IsLoad) const {
11083   if (!getInsertFencesForAtomic())
11084     return nullptr;
11085
11086   switch (Ord) {
11087   case NotAtomic:
11088   case Unordered:
11089     llvm_unreachable("Invalid fence: unordered/not-atomic");
11090   case Monotonic:
11091   case Release:
11092     return nullptr; // Nothing to do
11093   case Acquire:
11094   case AcquireRelease:
11095   case SequentiallyConsistent:
11096     return makeDMB(Builder, ARM_MB::ISH);
11097   }
11098   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11099 }
11100
11101 // Loads and stores less than 64-bits are already atomic; ones above that
11102 // are doomed anyway, so defer to the default libcall and blame the OS when
11103 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11104 // anything for those.
11105 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11106   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11107   return (Size == 64) && !Subtarget->isMClass();
11108 }
11109
11110 // Loads and stores less than 64-bits are already atomic; ones above that
11111 // are doomed anyway, so defer to the default libcall and blame the OS when
11112 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11113 // anything for those.
11114 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11115 // guarantee, see DDI0406C ARM architecture reference manual,
11116 // sections A8.8.72-74 LDRD)
11117 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11118   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11119   return (Size == 64) && !Subtarget->isMClass();
11120 }
11121
11122 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11123 // and up to 64 bits on the non-M profiles
11124 TargetLoweringBase::AtomicRMWExpansionKind
11125 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11126   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11127   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11128              ? AtomicRMWExpansionKind::LLSC
11129              : AtomicRMWExpansionKind::None;
11130 }
11131
11132 // This has so far only been implemented for MachO.
11133 bool ARMTargetLowering::useLoadStackGuardNode() const {
11134   return Subtarget->isTargetMachO();
11135 }
11136
11137 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11138                                                   unsigned &Cost) const {
11139   // If we do not have NEON, vector types are not natively supported.
11140   if (!Subtarget->hasNEON())
11141     return false;
11142
11143   // Floating point values and vector values map to the same register file.
11144   // Therefore, althought we could do a store extract of a vector type, this is
11145   // better to leave at float as we have more freedom in the addressing mode for
11146   // those.
11147   if (VectorTy->isFPOrFPVectorTy())
11148     return false;
11149
11150   // If the index is unknown at compile time, this is very expensive to lower
11151   // and it is not possible to combine the store with the extract.
11152   if (!isa<ConstantInt>(Idx))
11153     return false;
11154
11155   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11156   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11157   // We can do a store + vector extract on any vector that fits perfectly in a D
11158   // or Q register.
11159   if (BitWidth == 64 || BitWidth == 128) {
11160     Cost = 0;
11161     return true;
11162   }
11163   return false;
11164 }
11165
11166 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11167                                          AtomicOrdering Ord) const {
11168   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11169   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11170   bool IsAcquire = isAtLeastAcquire(Ord);
11171
11172   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11173   // intrinsic must return {i32, i32} and we have to recombine them into a
11174   // single i64 here.
11175   if (ValTy->getPrimitiveSizeInBits() == 64) {
11176     Intrinsic::ID Int =
11177         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11178     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11179
11180     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11181     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11182
11183     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11184     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11185     if (!Subtarget->isLittle())
11186       std::swap (Lo, Hi);
11187     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11188     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11189     return Builder.CreateOr(
11190         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11191   }
11192
11193   Type *Tys[] = { Addr->getType() };
11194   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11195   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11196
11197   return Builder.CreateTruncOrBitCast(
11198       Builder.CreateCall(Ldrex, Addr),
11199       cast<PointerType>(Addr->getType())->getElementType());
11200 }
11201
11202 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11203                                                Value *Addr,
11204                                                AtomicOrdering Ord) const {
11205   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11206   bool IsRelease = isAtLeastRelease(Ord);
11207
11208   // Since the intrinsics must have legal type, the i64 intrinsics take two
11209   // parameters: "i32, i32". We must marshal Val into the appropriate form
11210   // before the call.
11211   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11212     Intrinsic::ID Int =
11213         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11214     Function *Strex = Intrinsic::getDeclaration(M, Int);
11215     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11216
11217     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11218     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11219     if (!Subtarget->isLittle())
11220       std::swap (Lo, Hi);
11221     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11222     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11223   }
11224
11225   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11226   Type *Tys[] = { Addr->getType() };
11227   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11228
11229   return Builder.CreateCall2(
11230       Strex, Builder.CreateZExtOrBitCast(
11231                  Val, Strex->getFunctionType()->getParamType(0)),
11232       Addr);
11233 }
11234
11235 enum HABaseType {
11236   HA_UNKNOWN = 0,
11237   HA_FLOAT,
11238   HA_DOUBLE,
11239   HA_VECT64,
11240   HA_VECT128
11241 };
11242
11243 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11244                                    uint64_t &Members) {
11245   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11246     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11247       uint64_t SubMembers = 0;
11248       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11249         return false;
11250       Members += SubMembers;
11251     }
11252   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11253     uint64_t SubMembers = 0;
11254     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11255       return false;
11256     Members += SubMembers * AT->getNumElements();
11257   } else if (Ty->isFloatTy()) {
11258     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11259       return false;
11260     Members = 1;
11261     Base = HA_FLOAT;
11262   } else if (Ty->isDoubleTy()) {
11263     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11264       return false;
11265     Members = 1;
11266     Base = HA_DOUBLE;
11267   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11268     Members = 1;
11269     switch (Base) {
11270     case HA_FLOAT:
11271     case HA_DOUBLE:
11272       return false;
11273     case HA_VECT64:
11274       return VT->getBitWidth() == 64;
11275     case HA_VECT128:
11276       return VT->getBitWidth() == 128;
11277     case HA_UNKNOWN:
11278       switch (VT->getBitWidth()) {
11279       case 64:
11280         Base = HA_VECT64;
11281         return true;
11282       case 128:
11283         Base = HA_VECT128;
11284         return true;
11285       default:
11286         return false;
11287       }
11288     }
11289   }
11290
11291   return (Members > 0 && Members <= 4);
11292 }
11293
11294 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11295 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11296 /// passing according to AAPCS rules.
11297 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11298     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11299   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11300       CallingConv::ARM_AAPCS_VFP)
11301     return false;
11302
11303   HABaseType Base = HA_UNKNOWN;
11304   uint64_t Members = 0;
11305   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11306   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11307
11308   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11309   return IsHA || IsIntArray;
11310 }