]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/ARM/ARMISelLowering.cpp
MFV r284234:
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalValue.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <utility>
52 using namespace llvm;
53
54 #define DEBUG_TYPE "arm-isel"
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
58 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
59
60 cl::opt<bool>
61 EnableARMLongCalls("arm-long-calls", cl::Hidden,
62   cl::desc("Generate calls via indirect call instructions"),
63   cl::init(false));
64
65 static cl::opt<bool>
66 ARMInterworking("arm-interworking", cl::Hidden,
67   cl::desc("Enable / disable ARM interworking (for debugging only)"),
68   cl::init(true));
69
70 namespace {
71   class ARMCCState : public CCState {
72   public:
73     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
74                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
75                ParmContext PC)
76         : CCState(CC, isVarArg, MF, locs, C) {
77       assert(((PC == Call) || (PC == Prologue)) &&
78              "ARMCCState users must specify whether their context is call"
79              "or prologue generation.");
80       CallOrPrologue = PC;
81     }
82   };
83 }
84
85 // The APCS parameter registers.
86 static const MCPhysReg GPRArgRegs[] = {
87   ARM::R0, ARM::R1, ARM::R2, ARM::R3
88 };
89
90 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
91                                        MVT PromotedBitwiseVT) {
92   if (VT != PromotedLdStVT) {
93     setOperationAction(ISD::LOAD, VT, Promote);
94     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
95
96     setOperationAction(ISD::STORE, VT, Promote);
97     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
98   }
99
100   MVT ElemTy = VT.getVectorElementType();
101   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
102     setOperationAction(ISD::SETCC, VT, Custom);
103   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
104   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
105   if (ElemTy == MVT::i32) {
106     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
107     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
108     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
109     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
110   } else {
111     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
112     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
113     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
114     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
115   }
116   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
117   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
118   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
119   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
120   setOperationAction(ISD::SELECT,            VT, Expand);
121   setOperationAction(ISD::SELECT_CC,         VT, Expand);
122   setOperationAction(ISD::VSELECT,           VT, Expand);
123   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
124   if (VT.isInteger()) {
125     setOperationAction(ISD::SHL, VT, Custom);
126     setOperationAction(ISD::SRA, VT, Custom);
127     setOperationAction(ISD::SRL, VT, Custom);
128   }
129
130   // Promote all bit-wise operations.
131   if (VT.isInteger() && VT != PromotedBitwiseVT) {
132     setOperationAction(ISD::AND, VT, Promote);
133     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
134     setOperationAction(ISD::OR,  VT, Promote);
135     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
136     setOperationAction(ISD::XOR, VT, Promote);
137     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
138   }
139
140   // Neon does not support vector divide/remainder operations.
141   setOperationAction(ISD::SDIV, VT, Expand);
142   setOperationAction(ISD::UDIV, VT, Expand);
143   setOperationAction(ISD::FDIV, VT, Expand);
144   setOperationAction(ISD::SREM, VT, Expand);
145   setOperationAction(ISD::UREM, VT, Expand);
146   setOperationAction(ISD::FREM, VT, Expand);
147 }
148
149 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
150   addRegisterClass(VT, &ARM::DPRRegClass);
151   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
152 }
153
154 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
155   addRegisterClass(VT, &ARM::DPairRegClass);
156   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
157 }
158
159 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM)
160     : TargetLowering(TM) {
161   Subtarget = &TM.getSubtarget<ARMSubtarget>();
162   RegInfo = TM.getSubtargetImpl()->getRegisterInfo();
163   Itins = TM.getSubtargetImpl()->getInstrItineraryData();
164
165   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
166
167   if (Subtarget->isTargetMachO()) {
168     // Uses VFP for Thumb libfuncs if available.
169     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
170         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
171       // Single-precision floating-point arithmetic.
172       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
173       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
174       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
175       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
176
177       // Double-precision floating-point arithmetic.
178       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
179       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
180       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
181       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
182
183       // Single-precision comparisons.
184       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
185       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
186       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
187       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
188       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
189       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
190       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
191       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
192
193       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
194       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
195       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
196       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
197       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
198       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
199       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
200       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
201
202       // Double-precision comparisons.
203       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
204       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
205       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
206       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
207       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
208       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
209       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
210       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
211
212       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
213       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
214       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
215       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
216       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
217       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
218       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
219       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
220
221       // Floating-point to integer conversions.
222       // i64 conversions are done via library routines even when generating VFP
223       // instructions, so use the same ones.
224       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
225       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
226       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
227       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
228
229       // Conversions between floating types.
230       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
231       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
232
233       // Integer to floating-point conversions.
234       // i64 conversions are done via library routines even when generating VFP
235       // instructions, so use the same ones.
236       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
237       // e.g., __floatunsidf vs. __floatunssidfvfp.
238       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
239       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
240       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
241       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
242     }
243   }
244
245   // These libcalls are not available in 32-bit.
246   setLibcallName(RTLIB::SHL_I128, nullptr);
247   setLibcallName(RTLIB::SRL_I128, nullptr);
248   setLibcallName(RTLIB::SRA_I128, nullptr);
249
250   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
251       !Subtarget->isTargetWindows()) {
252     static const struct {
253       const RTLIB::Libcall Op;
254       const char * const Name;
255       const CallingConv::ID CC;
256       const ISD::CondCode Cond;
257     } LibraryCalls[] = {
258       // Double-precision floating-point arithmetic helper functions
259       // RTABI chapter 4.1.2, Table 2
260       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
261       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
262       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
263       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264
265       // Double-precision floating-point comparison helper functions
266       // RTABI chapter 4.1.2, Table 3
267       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
268       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
269       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
270       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
271       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
272       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
273       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
274       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
275
276       // Single-precision floating-point arithmetic helper functions
277       // RTABI chapter 4.1.2, Table 4
278       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
279       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
280       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
281       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282
283       // Single-precision floating-point comparison helper functions
284       // RTABI chapter 4.1.2, Table 5
285       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
286       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
287       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
288       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
289       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
290       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
291       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
292       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
293
294       // Floating-point to integer conversions.
295       // RTABI chapter 4.1.2, Table 6
296       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
297       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
298       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304
305       // Conversions between floating types.
306       // RTABI chapter 4.1.2, Table 7
307       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310
311       // Integer to floating-point conversions.
312       // RTABI chapter 4.1.2, Table 8
313       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321
322       // Long long helper functions
323       // RTABI chapter 4.2, Table 9
324       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328
329       // Integer division functions
330       // RTABI chapter 4.3.1
331       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339
340       // Memory operations
341       // RTABI chapter 4.3.4
342       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345     };
346
347     for (const auto &LC : LibraryCalls) {
348       setLibcallName(LC.Op, LC.Name);
349       setLibcallCallingConv(LC.Op, LC.CC);
350       if (LC.Cond != ISD::SETCC_INVALID)
351         setCmpLibcallCC(LC.Op, LC.Cond);
352     }
353   }
354
355   if (Subtarget->isTargetWindows()) {
356     static const struct {
357       const RTLIB::Libcall Op;
358       const char * const Name;
359       const CallingConv::ID CC;
360     } LibraryCalls[] = {
361       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
362       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
363       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
364       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
366       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
367       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
369     };
370
371     for (const auto &LC : LibraryCalls) {
372       setLibcallName(LC.Op, LC.Name);
373       setLibcallCallingConv(LC.Op, LC.CC);
374     }
375   }
376
377   // Use divmod compiler-rt calls for iOS 5.0 and later.
378   if (Subtarget->getTargetTriple().isiOS() &&
379       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
380     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
381     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
382   }
383
384   // The half <-> float conversion functions are always soft-float, but are
385   // needed for some targets which use a hard-float calling convention by
386   // default.
387   if (Subtarget->isAAPCS_ABI()) {
388     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
391   } else {
392     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
393     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
394     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
395   }
396
397   if (Subtarget->isThumb1Only())
398     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
399   else
400     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
401   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
402       !Subtarget->isThumb1Only()) {
403     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
404     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
405   }
406
407   for (MVT VT : MVT::vector_valuetypes()) {
408     for (MVT InnerVT : MVT::vector_valuetypes()) {
409       setTruncStoreAction(VT, InnerVT, Expand);
410       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
411       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
412       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
413     }
414
415     setOperationAction(ISD::MULHS, VT, Expand);
416     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
417     setOperationAction(ISD::MULHU, VT, Expand);
418     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
419
420     setOperationAction(ISD::BSWAP, VT, Expand);
421   }
422
423   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
424   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
425
426   if (Subtarget->hasNEON()) {
427     addDRTypeForNEON(MVT::v2f32);
428     addDRTypeForNEON(MVT::v8i8);
429     addDRTypeForNEON(MVT::v4i16);
430     addDRTypeForNEON(MVT::v2i32);
431     addDRTypeForNEON(MVT::v1i64);
432
433     addQRTypeForNEON(MVT::v4f32);
434     addQRTypeForNEON(MVT::v2f64);
435     addQRTypeForNEON(MVT::v16i8);
436     addQRTypeForNEON(MVT::v8i16);
437     addQRTypeForNEON(MVT::v4i32);
438     addQRTypeForNEON(MVT::v2i64);
439
440     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
441     // neither Neon nor VFP support any arithmetic operations on it.
442     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
443     // supported for v4f32.
444     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
445     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
446     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
447     // FIXME: Code duplication: FDIV and FREM are expanded always, see
448     // ARMTargetLowering::addTypeForNEON method for details.
449     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
450     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
451     // FIXME: Create unittest.
452     // In another words, find a way when "copysign" appears in DAG with vector
453     // operands.
454     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
455     // FIXME: Code duplication: SETCC has custom operation action, see
456     // ARMTargetLowering::addTypeForNEON method for details.
457     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
458     // FIXME: Create unittest for FNEG and for FABS.
459     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
460     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
461     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
462     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
463     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
464     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
465     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
466     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
467     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
468     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
469     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
470     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
471     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
472     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
473     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
474     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
475     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
476     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
477     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
478
479     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
480     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
481     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
482     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
483     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
484     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
485     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
486     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
487     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
488     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
489     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
490     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
491     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
492     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
493     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
494
495     // Mark v2f32 intrinsics.
496     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
497     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
498     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
499     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
500     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
501     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
502     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
503     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
504     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
505     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
506     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
507     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
508     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
509     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
510     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
511
512     // Neon does not support some operations on v1i64 and v2i64 types.
513     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
514     // Custom handling for some quad-vector types to detect VMULL.
515     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
516     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
517     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
518     // Custom handling for some vector types to avoid expensive expansions
519     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
520     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
521     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
522     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
523     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
524     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
525     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
526     // a destination type that is wider than the source, and nor does
527     // it have a FP_TO_[SU]INT instruction with a narrower destination than
528     // source.
529     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
530     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
531     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
532     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
533
534     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
535     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
536
537     // NEON does not have single instruction CTPOP for vectors with element
538     // types wider than 8-bits.  However, custom lowering can leverage the
539     // v8i8/v16i8 vcnt instruction.
540     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
541     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
542     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
543     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
544
545     // NEON only has FMA instructions as of VFP4.
546     if (!Subtarget->hasVFP4()) {
547       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
548       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
549     }
550
551     setTargetDAGCombine(ISD::INTRINSIC_VOID);
552     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
553     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
554     setTargetDAGCombine(ISD::SHL);
555     setTargetDAGCombine(ISD::SRL);
556     setTargetDAGCombine(ISD::SRA);
557     setTargetDAGCombine(ISD::SIGN_EXTEND);
558     setTargetDAGCombine(ISD::ZERO_EXTEND);
559     setTargetDAGCombine(ISD::ANY_EXTEND);
560     setTargetDAGCombine(ISD::SELECT_CC);
561     setTargetDAGCombine(ISD::BUILD_VECTOR);
562     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
563     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
564     setTargetDAGCombine(ISD::STORE);
565     setTargetDAGCombine(ISD::FP_TO_SINT);
566     setTargetDAGCombine(ISD::FP_TO_UINT);
567     setTargetDAGCombine(ISD::FDIV);
568
569     // It is legal to extload from v4i8 to v4i16 or v4i32.
570     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
571                   MVT::v4i16, MVT::v2i16,
572                   MVT::v2i32};
573     for (unsigned i = 0; i < 6; ++i) {
574       for (MVT VT : MVT::integer_vector_valuetypes()) {
575         setLoadExtAction(ISD::EXTLOAD, VT, Tys[i], Legal);
576         setLoadExtAction(ISD::ZEXTLOAD, VT, Tys[i], Legal);
577         setLoadExtAction(ISD::SEXTLOAD, VT, Tys[i], Legal);
578       }
579     }
580   }
581
582   // ARM and Thumb2 support UMLAL/SMLAL.
583   if (!Subtarget->isThumb1Only())
584     setTargetDAGCombine(ISD::ADDC);
585
586   if (Subtarget->isFPOnlySP()) {
587     // When targetting a floating-point unit with only single-precision
588     // operations, f64 is legal for the few double-precision instructions which
589     // are present However, no double-precision operations other than moves,
590     // loads and stores are provided by the hardware.
591     setOperationAction(ISD::FADD,       MVT::f64, Expand);
592     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
593     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
594     setOperationAction(ISD::FMA,        MVT::f64, Expand);
595     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
596     setOperationAction(ISD::FREM,       MVT::f64, Expand);
597     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
598     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
599     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
600     setOperationAction(ISD::FABS,       MVT::f64, Expand);
601     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
602     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
603     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
604     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
605     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
606     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
607     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
608     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
609     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
610     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
611     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
612     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
613     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
614     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
615     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
616     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
617     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
618   }
619
620   computeRegisterProperties();
621
622   // ARM does not have floating-point extending loads.
623   for (MVT VT : MVT::fp_valuetypes()) {
624     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
625     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
626   }
627
628   // ... or truncating stores
629   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
630   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
631   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
632
633   // ARM does not have i1 sign extending load.
634   for (MVT VT : MVT::integer_valuetypes())
635     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
636
637   // ARM supports all 4 flavors of integer indexed load / store.
638   if (!Subtarget->isThumb1Only()) {
639     for (unsigned im = (unsigned)ISD::PRE_INC;
640          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
641       setIndexedLoadAction(im,  MVT::i1,  Legal);
642       setIndexedLoadAction(im,  MVT::i8,  Legal);
643       setIndexedLoadAction(im,  MVT::i16, Legal);
644       setIndexedLoadAction(im,  MVT::i32, Legal);
645       setIndexedStoreAction(im, MVT::i1,  Legal);
646       setIndexedStoreAction(im, MVT::i8,  Legal);
647       setIndexedStoreAction(im, MVT::i16, Legal);
648       setIndexedStoreAction(im, MVT::i32, Legal);
649     }
650   }
651
652   setOperationAction(ISD::SADDO, MVT::i32, Custom);
653   setOperationAction(ISD::UADDO, MVT::i32, Custom);
654   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
655   setOperationAction(ISD::USUBO, MVT::i32, Custom);
656
657   // i64 operation support.
658   setOperationAction(ISD::MUL,     MVT::i64, Expand);
659   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
660   if (Subtarget->isThumb1Only()) {
661     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
662     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
663   }
664   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
665       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
666     setOperationAction(ISD::MULHS, MVT::i32, Expand);
667
668   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
669   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
670   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
671   setOperationAction(ISD::SRL,       MVT::i64, Custom);
672   setOperationAction(ISD::SRA,       MVT::i64, Custom);
673
674   if (!Subtarget->isThumb1Only()) {
675     // FIXME: We should do this for Thumb1 as well.
676     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
677     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
678     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
679     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
680   }
681
682   // ARM does not have ROTL.
683   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
684   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
685   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
686   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
687     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
688
689   // These just redirect to CTTZ and CTLZ on ARM.
690   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
691   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
692
693   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
694
695   // Only ARMv6 has BSWAP.
696   if (!Subtarget->hasV6Ops())
697     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
698
699   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
700       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
701     // These are expanded into libcalls if the cpu doesn't have HW divider.
702     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
703     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
704   }
705
706   // FIXME: Also set divmod for SREM on EABI
707   setOperationAction(ISD::SREM,  MVT::i32, Expand);
708   setOperationAction(ISD::UREM,  MVT::i32, Expand);
709   // Register based DivRem for AEABI (RTABI 4.2)
710   if (Subtarget->isTargetAEABI()) {
711     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
712     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
713     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
714     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
715     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
716     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
717     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
718     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
719
720     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
721     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
722     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
723     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
724     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
725     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
726     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
727     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
728
729     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
730     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
731   } else {
732     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
733     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
734   }
735
736   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
737   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
738   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
739   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
740   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
741
742   setOperationAction(ISD::TRAP, MVT::Other, Legal);
743
744   // Use the default implementation.
745   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
746   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
747   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
748   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
749   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
750   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
751
752   if (!Subtarget->isTargetMachO()) {
753     // Non-MachO platforms may return values in these registers via the
754     // personality function.
755     setExceptionPointerRegister(ARM::R0);
756     setExceptionSelectorRegister(ARM::R1);
757   }
758
759   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
760     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
761   else
762     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
763
764   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
765   // the default expansion. If we are targeting a single threaded system,
766   // then set them all for expand so we can lower them later into their
767   // non-atomic form.
768   if (TM.Options.ThreadModel == ThreadModel::Single)
769     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
770   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
771     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
772     // to ldrex/strex loops already.
773     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
774
775     // On v8, we have particularly efficient implementations of atomic fences
776     // if they can be combined with nearby atomic loads and stores.
777     if (!Subtarget->hasV8Ops()) {
778       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
779       setInsertFencesForAtomic(true);
780     }
781   } else {
782     // If there's anything we can use as a barrier, go through custom lowering
783     // for ATOMIC_FENCE.
784     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
785                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
786
787     // Set them all for expansion, which will force libcalls.
788     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
789     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
790     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
791     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
792     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
793     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
794     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
795     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
796     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
800     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
801     // Unordered/Monotonic case.
802     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
803     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
804   }
805
806   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
807
808   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
809   if (!Subtarget->hasV6Ops()) {
810     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
811     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
812   }
813   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
814
815   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
816       !Subtarget->isThumb1Only()) {
817     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
818     // iff target supports vfp2.
819     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
820     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
821   }
822
823   // We want to custom lower some of our intrinsics.
824   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
825   if (Subtarget->isTargetDarwin()) {
826     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
827     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
828     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
829   }
830
831   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
832   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
833   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
834   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
835   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
836   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
837   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
838   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
839   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
840
841   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
842   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
843   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
844   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
845   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
846
847   // We don't support sin/cos/fmod/copysign/pow
848   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
849   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
850   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
851   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
852   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
853   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
854   setOperationAction(ISD::FREM,      MVT::f64, Expand);
855   setOperationAction(ISD::FREM,      MVT::f32, Expand);
856   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
857       !Subtarget->isThumb1Only()) {
858     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
859     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
860   }
861   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
862   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
863
864   if (!Subtarget->hasVFP4()) {
865     setOperationAction(ISD::FMA, MVT::f64, Expand);
866     setOperationAction(ISD::FMA, MVT::f32, Expand);
867   }
868
869   // Various VFP goodness
870   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
871     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
872     if (Subtarget->hasVFP2()) {
873       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
874       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
875       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
876       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
877     }
878
879     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
880     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
881       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
882       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
883     }
884
885     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
886     if (!Subtarget->hasFP16()) {
887       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
888       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
889     }
890   }
891
892   // Combine sin / cos into one node or libcall if possible.
893   if (Subtarget->hasSinCos()) {
894     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
895     setLibcallName(RTLIB::SINCOS_F64, "sincos");
896     if (Subtarget->getTargetTriple().isiOS()) {
897       // For iOS, we don't want to the normal expansion of a libcall to
898       // sincos. We want to issue a libcall to __sincos_stret.
899       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
900       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
901     }
902   }
903
904   // FP-ARMv8 implements a lot of rounding-like FP operations.
905   if (Subtarget->hasFPARMv8()) {
906     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
907     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
908     setOperationAction(ISD::FROUND, MVT::f32, Legal);
909     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
910     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
911     setOperationAction(ISD::FRINT, MVT::f32, Legal);
912     if (!Subtarget->isFPOnlySP()) {
913       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
914       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
915       setOperationAction(ISD::FROUND, MVT::f64, Legal);
916       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
917       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
918       setOperationAction(ISD::FRINT, MVT::f64, Legal);
919     }
920   }
921   // We have target-specific dag combine patterns for the following nodes:
922   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
923   setTargetDAGCombine(ISD::ADD);
924   setTargetDAGCombine(ISD::SUB);
925   setTargetDAGCombine(ISD::MUL);
926   setTargetDAGCombine(ISD::AND);
927   setTargetDAGCombine(ISD::OR);
928   setTargetDAGCombine(ISD::XOR);
929
930   if (Subtarget->hasV6Ops())
931     setTargetDAGCombine(ISD::SRL);
932
933   setStackPointerRegisterToSaveRestore(ARM::SP);
934
935   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
936       !Subtarget->hasVFP2())
937     setSchedulingPreference(Sched::RegPressure);
938   else
939     setSchedulingPreference(Sched::Hybrid);
940
941   //// temporary - rewrite interface to use type
942   MaxStoresPerMemset = 8;
943   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
944   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
945   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
946   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
947   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
948
949   // On ARM arguments smaller than 4 bytes are extended, so all arguments
950   // are at least 4 bytes aligned.
951   setMinStackArgumentAlignment(4);
952
953   // Prefer likely predicted branches to selects on out-of-order cores.
954   PredictableSelectIsExpensive = Subtarget->isLikeA9();
955
956   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
957 }
958
959 // FIXME: It might make sense to define the representative register class as the
960 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
961 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
962 // SPR's representative would be DPR_VFP2. This should work well if register
963 // pressure tracking were modified such that a register use would increment the
964 // pressure of the register class's representative and all of it's super
965 // classes' representatives transitively. We have not implemented this because
966 // of the difficulty prior to coalescing of modeling operand register classes
967 // due to the common occurrence of cross class copies and subregister insertions
968 // and extractions.
969 std::pair<const TargetRegisterClass*, uint8_t>
970 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
971   const TargetRegisterClass *RRC = nullptr;
972   uint8_t Cost = 1;
973   switch (VT.SimpleTy) {
974   default:
975     return TargetLowering::findRepresentativeClass(VT);
976   // Use DPR as representative register class for all floating point
977   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
978   // the cost is 1 for both f32 and f64.
979   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
980   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
981     RRC = &ARM::DPRRegClass;
982     // When NEON is used for SP, only half of the register file is available
983     // because operations that define both SP and DP results will be constrained
984     // to the VFP2 class (D0-D15). We currently model this constraint prior to
985     // coalescing by double-counting the SP regs. See the FIXME above.
986     if (Subtarget->useNEONForSinglePrecisionFP())
987       Cost = 2;
988     break;
989   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
990   case MVT::v4f32: case MVT::v2f64:
991     RRC = &ARM::DPRRegClass;
992     Cost = 2;
993     break;
994   case MVT::v4i64:
995     RRC = &ARM::DPRRegClass;
996     Cost = 4;
997     break;
998   case MVT::v8i64:
999     RRC = &ARM::DPRRegClass;
1000     Cost = 8;
1001     break;
1002   }
1003   return std::make_pair(RRC, Cost);
1004 }
1005
1006 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1007   switch (Opcode) {
1008   default: return nullptr;
1009   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1010   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1011   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1012   case ARMISD::CALL:          return "ARMISD::CALL";
1013   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1014   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1015   case ARMISD::tCALL:         return "ARMISD::tCALL";
1016   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1017   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1018   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1019   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1020   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1021   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1022   case ARMISD::CMP:           return "ARMISD::CMP";
1023   case ARMISD::CMN:           return "ARMISD::CMN";
1024   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1025   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1026   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1027   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1028   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1029
1030   case ARMISD::CMOV:          return "ARMISD::CMOV";
1031
1032   case ARMISD::RBIT:          return "ARMISD::RBIT";
1033
1034   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1035   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1036   case ARMISD::SITOF:         return "ARMISD::SITOF";
1037   case ARMISD::UITOF:         return "ARMISD::UITOF";
1038
1039   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1040   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1041   case ARMISD::RRX:           return "ARMISD::RRX";
1042
1043   case ARMISD::ADDC:          return "ARMISD::ADDC";
1044   case ARMISD::ADDE:          return "ARMISD::ADDE";
1045   case ARMISD::SUBC:          return "ARMISD::SUBC";
1046   case ARMISD::SUBE:          return "ARMISD::SUBE";
1047
1048   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1049   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1050
1051   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1052   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1053
1054   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1055
1056   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1057
1058   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1059
1060   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1061
1062   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1063
1064   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1065
1066   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1067   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1068   case ARMISD::VCGE:          return "ARMISD::VCGE";
1069   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1070   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1071   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1072   case ARMISD::VCGT:          return "ARMISD::VCGT";
1073   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1074   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1075   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1076   case ARMISD::VTST:          return "ARMISD::VTST";
1077
1078   case ARMISD::VSHL:          return "ARMISD::VSHL";
1079   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1080   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1081   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1082   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1083   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1084   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1085   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1086   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1087   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1088   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1089   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1090   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1091   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1092   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1093   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1094   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1095   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1096   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1097   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1098   case ARMISD::VDUP:          return "ARMISD::VDUP";
1099   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1100   case ARMISD::VEXT:          return "ARMISD::VEXT";
1101   case ARMISD::VREV64:        return "ARMISD::VREV64";
1102   case ARMISD::VREV32:        return "ARMISD::VREV32";
1103   case ARMISD::VREV16:        return "ARMISD::VREV16";
1104   case ARMISD::VZIP:          return "ARMISD::VZIP";
1105   case ARMISD::VUZP:          return "ARMISD::VUZP";
1106   case ARMISD::VTRN:          return "ARMISD::VTRN";
1107   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1108   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1109   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1110   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1111   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1112   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1113   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1114   case ARMISD::FMAX:          return "ARMISD::FMAX";
1115   case ARMISD::FMIN:          return "ARMISD::FMIN";
1116   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1117   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1118   case ARMISD::BFI:           return "ARMISD::BFI";
1119   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1120   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1121   case ARMISD::VBSL:          return "ARMISD::VBSL";
1122   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1123   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1124   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1125   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1126   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1127   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1128   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1129   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1130   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1131   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1132   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1133   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1134   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1135   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1136   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1137   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1138   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1139   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1140   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1141   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1142   }
1143 }
1144
1145 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1146   if (!VT.isVector()) return getPointerTy();
1147   return VT.changeVectorElementTypeToInteger();
1148 }
1149
1150 /// getRegClassFor - Return the register class that should be used for the
1151 /// specified value type.
1152 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1153   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1154   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1155   // load / store 4 to 8 consecutive D registers.
1156   if (Subtarget->hasNEON()) {
1157     if (VT == MVT::v4i64)
1158       return &ARM::QQPRRegClass;
1159     if (VT == MVT::v8i64)
1160       return &ARM::QQQQPRRegClass;
1161   }
1162   return TargetLowering::getRegClassFor(VT);
1163 }
1164
1165 // Create a fast isel object.
1166 FastISel *
1167 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1168                                   const TargetLibraryInfo *libInfo) const {
1169   return ARM::createFastISel(funcInfo, libInfo);
1170 }
1171
1172 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1173 /// be used for loads / stores from the global.
1174 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1175   return (Subtarget->isThumb1Only() ? 127 : 4095);
1176 }
1177
1178 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1179   unsigned NumVals = N->getNumValues();
1180   if (!NumVals)
1181     return Sched::RegPressure;
1182
1183   for (unsigned i = 0; i != NumVals; ++i) {
1184     EVT VT = N->getValueType(i);
1185     if (VT == MVT::Glue || VT == MVT::Other)
1186       continue;
1187     if (VT.isFloatingPoint() || VT.isVector())
1188       return Sched::ILP;
1189   }
1190
1191   if (!N->isMachineOpcode())
1192     return Sched::RegPressure;
1193
1194   // Load are scheduled for latency even if there instruction itinerary
1195   // is not available.
1196   const TargetInstrInfo *TII =
1197       getTargetMachine().getSubtargetImpl()->getInstrInfo();
1198   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1199
1200   if (MCID.getNumDefs() == 0)
1201     return Sched::RegPressure;
1202   if (!Itins->isEmpty() &&
1203       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1204     return Sched::ILP;
1205
1206   return Sched::RegPressure;
1207 }
1208
1209 //===----------------------------------------------------------------------===//
1210 // Lowering Code
1211 //===----------------------------------------------------------------------===//
1212
1213 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1214 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1215   switch (CC) {
1216   default: llvm_unreachable("Unknown condition code!");
1217   case ISD::SETNE:  return ARMCC::NE;
1218   case ISD::SETEQ:  return ARMCC::EQ;
1219   case ISD::SETGT:  return ARMCC::GT;
1220   case ISD::SETGE:  return ARMCC::GE;
1221   case ISD::SETLT:  return ARMCC::LT;
1222   case ISD::SETLE:  return ARMCC::LE;
1223   case ISD::SETUGT: return ARMCC::HI;
1224   case ISD::SETUGE: return ARMCC::HS;
1225   case ISD::SETULT: return ARMCC::LO;
1226   case ISD::SETULE: return ARMCC::LS;
1227   }
1228 }
1229
1230 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1231 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1232                         ARMCC::CondCodes &CondCode2) {
1233   CondCode2 = ARMCC::AL;
1234   switch (CC) {
1235   default: llvm_unreachable("Unknown FP condition!");
1236   case ISD::SETEQ:
1237   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1238   case ISD::SETGT:
1239   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1240   case ISD::SETGE:
1241   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1242   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1243   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1244   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1245   case ISD::SETO:   CondCode = ARMCC::VC; break;
1246   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1247   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1248   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1249   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1250   case ISD::SETLT:
1251   case ISD::SETULT: CondCode = ARMCC::LT; break;
1252   case ISD::SETLE:
1253   case ISD::SETULE: CondCode = ARMCC::LE; break;
1254   case ISD::SETNE:
1255   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1256   }
1257 }
1258
1259 //===----------------------------------------------------------------------===//
1260 //                      Calling Convention Implementation
1261 //===----------------------------------------------------------------------===//
1262
1263 #include "ARMGenCallingConv.inc"
1264
1265 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1266 /// account presence of floating point hardware and calling convention
1267 /// limitations, such as support for variadic functions.
1268 CallingConv::ID
1269 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1270                                            bool isVarArg) const {
1271   switch (CC) {
1272   default:
1273     llvm_unreachable("Unsupported calling convention");
1274   case CallingConv::ARM_AAPCS:
1275   case CallingConv::ARM_APCS:
1276   case CallingConv::GHC:
1277     return CC;
1278   case CallingConv::ARM_AAPCS_VFP:
1279     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1280   case CallingConv::C:
1281     if (!Subtarget->isAAPCS_ABI())
1282       return CallingConv::ARM_APCS;
1283     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1284              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1285              !isVarArg)
1286       return CallingConv::ARM_AAPCS_VFP;
1287     else
1288       return CallingConv::ARM_AAPCS;
1289   case CallingConv::Fast:
1290     if (!Subtarget->isAAPCS_ABI()) {
1291       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1292         return CallingConv::Fast;
1293       return CallingConv::ARM_APCS;
1294     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1295       return CallingConv::ARM_AAPCS_VFP;
1296     else
1297       return CallingConv::ARM_AAPCS;
1298   }
1299 }
1300
1301 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1302 /// CallingConvention.
1303 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1304                                                  bool Return,
1305                                                  bool isVarArg) const {
1306   switch (getEffectiveCallingConv(CC, isVarArg)) {
1307   default:
1308     llvm_unreachable("Unsupported calling convention");
1309   case CallingConv::ARM_APCS:
1310     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1311   case CallingConv::ARM_AAPCS:
1312     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1313   case CallingConv::ARM_AAPCS_VFP:
1314     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1315   case CallingConv::Fast:
1316     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1317   case CallingConv::GHC:
1318     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1319   }
1320 }
1321
1322 /// LowerCallResult - Lower the result values of a call into the
1323 /// appropriate copies out of appropriate physical registers.
1324 SDValue
1325 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1326                                    CallingConv::ID CallConv, bool isVarArg,
1327                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1328                                    SDLoc dl, SelectionDAG &DAG,
1329                                    SmallVectorImpl<SDValue> &InVals,
1330                                    bool isThisReturn, SDValue ThisVal) const {
1331
1332   // Assign locations to each value returned by this call.
1333   SmallVector<CCValAssign, 16> RVLocs;
1334   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1335                     *DAG.getContext(), Call);
1336   CCInfo.AnalyzeCallResult(Ins,
1337                            CCAssignFnForNode(CallConv, /* Return*/ true,
1338                                              isVarArg));
1339
1340   // Copy all of the result registers out of their specified physreg.
1341   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1342     CCValAssign VA = RVLocs[i];
1343
1344     // Pass 'this' value directly from the argument to return value, to avoid
1345     // reg unit interference
1346     if (i == 0 && isThisReturn) {
1347       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1348              "unexpected return calling convention register assignment");
1349       InVals.push_back(ThisVal);
1350       continue;
1351     }
1352
1353     SDValue Val;
1354     if (VA.needsCustom()) {
1355       // Handle f64 or half of a v2f64.
1356       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1357                                       InFlag);
1358       Chain = Lo.getValue(1);
1359       InFlag = Lo.getValue(2);
1360       VA = RVLocs[++i]; // skip ahead to next loc
1361       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1362                                       InFlag);
1363       Chain = Hi.getValue(1);
1364       InFlag = Hi.getValue(2);
1365       if (!Subtarget->isLittle())
1366         std::swap (Lo, Hi);
1367       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1368
1369       if (VA.getLocVT() == MVT::v2f64) {
1370         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1371         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1372                           DAG.getConstant(0, MVT::i32));
1373
1374         VA = RVLocs[++i]; // skip ahead to next loc
1375         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1376         Chain = Lo.getValue(1);
1377         InFlag = Lo.getValue(2);
1378         VA = RVLocs[++i]; // skip ahead to next loc
1379         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1380         Chain = Hi.getValue(1);
1381         InFlag = Hi.getValue(2);
1382         if (!Subtarget->isLittle())
1383           std::swap (Lo, Hi);
1384         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1385         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1386                           DAG.getConstant(1, MVT::i32));
1387       }
1388     } else {
1389       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1390                                InFlag);
1391       Chain = Val.getValue(1);
1392       InFlag = Val.getValue(2);
1393     }
1394
1395     switch (VA.getLocInfo()) {
1396     default: llvm_unreachable("Unknown loc info!");
1397     case CCValAssign::Full: break;
1398     case CCValAssign::BCvt:
1399       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1400       break;
1401     }
1402
1403     InVals.push_back(Val);
1404   }
1405
1406   return Chain;
1407 }
1408
1409 /// LowerMemOpCallTo - Store the argument to the stack.
1410 SDValue
1411 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1412                                     SDValue StackPtr, SDValue Arg,
1413                                     SDLoc dl, SelectionDAG &DAG,
1414                                     const CCValAssign &VA,
1415                                     ISD::ArgFlagsTy Flags) const {
1416   unsigned LocMemOffset = VA.getLocMemOffset();
1417   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1418   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1419   return DAG.getStore(Chain, dl, Arg, PtrOff,
1420                       MachinePointerInfo::getStack(LocMemOffset),
1421                       false, false, 0);
1422 }
1423
1424 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1425                                          SDValue Chain, SDValue &Arg,
1426                                          RegsToPassVector &RegsToPass,
1427                                          CCValAssign &VA, CCValAssign &NextVA,
1428                                          SDValue &StackPtr,
1429                                          SmallVectorImpl<SDValue> &MemOpChains,
1430                                          ISD::ArgFlagsTy Flags) const {
1431
1432   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1433                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1434   unsigned id = Subtarget->isLittle() ? 0 : 1;
1435   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1436
1437   if (NextVA.isRegLoc())
1438     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1439   else {
1440     assert(NextVA.isMemLoc());
1441     if (!StackPtr.getNode())
1442       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1443
1444     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1445                                            dl, DAG, NextVA,
1446                                            Flags));
1447   }
1448 }
1449
1450 /// LowerCall - Lowering a call into a callseq_start <-
1451 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1452 /// nodes.
1453 SDValue
1454 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1455                              SmallVectorImpl<SDValue> &InVals) const {
1456   SelectionDAG &DAG                     = CLI.DAG;
1457   SDLoc &dl                          = CLI.DL;
1458   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1459   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1460   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1461   SDValue Chain                         = CLI.Chain;
1462   SDValue Callee                        = CLI.Callee;
1463   bool &isTailCall                      = CLI.IsTailCall;
1464   CallingConv::ID CallConv              = CLI.CallConv;
1465   bool doesNotRet                       = CLI.DoesNotReturn;
1466   bool isVarArg                         = CLI.IsVarArg;
1467
1468   MachineFunction &MF = DAG.getMachineFunction();
1469   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1470   bool isThisReturn   = false;
1471   bool isSibCall      = false;
1472
1473   // Disable tail calls if they're not supported.
1474   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1475     isTailCall = false;
1476
1477   if (isTailCall) {
1478     // Check if it's really possible to do a tail call.
1479     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1480                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1481                                                    Outs, OutVals, Ins, DAG);
1482     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1483       report_fatal_error("failed to perform tail call elimination on a call "
1484                          "site marked musttail");
1485     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1486     // detected sibcalls.
1487     if (isTailCall) {
1488       ++NumTailCalls;
1489       isSibCall = true;
1490     }
1491   }
1492
1493   // Analyze operands of the call, assigning locations to each operand.
1494   SmallVector<CCValAssign, 16> ArgLocs;
1495   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1496                     *DAG.getContext(), Call);
1497   CCInfo.AnalyzeCallOperands(Outs,
1498                              CCAssignFnForNode(CallConv, /* Return*/ false,
1499                                                isVarArg));
1500
1501   // Get a count of how many bytes are to be pushed on the stack.
1502   unsigned NumBytes = CCInfo.getNextStackOffset();
1503
1504   // For tail calls, memory operands are available in our caller's stack.
1505   if (isSibCall)
1506     NumBytes = 0;
1507
1508   // Adjust the stack pointer for the new arguments...
1509   // These operations are automatically eliminated by the prolog/epilog pass
1510   if (!isSibCall)
1511     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1512                                  dl);
1513
1514   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1515
1516   RegsToPassVector RegsToPass;
1517   SmallVector<SDValue, 8> MemOpChains;
1518
1519   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1520   // of tail call optimization, arguments are handled later.
1521   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1522        i != e;
1523        ++i, ++realArgIdx) {
1524     CCValAssign &VA = ArgLocs[i];
1525     SDValue Arg = OutVals[realArgIdx];
1526     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1527     bool isByVal = Flags.isByVal();
1528
1529     // Promote the value if needed.
1530     switch (VA.getLocInfo()) {
1531     default: llvm_unreachable("Unknown loc info!");
1532     case CCValAssign::Full: break;
1533     case CCValAssign::SExt:
1534       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1535       break;
1536     case CCValAssign::ZExt:
1537       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1538       break;
1539     case CCValAssign::AExt:
1540       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1541       break;
1542     case CCValAssign::BCvt:
1543       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1544       break;
1545     }
1546
1547     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1548     if (VA.needsCustom()) {
1549       if (VA.getLocVT() == MVT::v2f64) {
1550         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1551                                   DAG.getConstant(0, MVT::i32));
1552         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1553                                   DAG.getConstant(1, MVT::i32));
1554
1555         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1556                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1557
1558         VA = ArgLocs[++i]; // skip ahead to next loc
1559         if (VA.isRegLoc()) {
1560           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1561                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1562         } else {
1563           assert(VA.isMemLoc());
1564
1565           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1566                                                  dl, DAG, VA, Flags));
1567         }
1568       } else {
1569         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1570                          StackPtr, MemOpChains, Flags);
1571       }
1572     } else if (VA.isRegLoc()) {
1573       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1574         assert(VA.getLocVT() == MVT::i32 &&
1575                "unexpected calling convention register assignment");
1576         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1577                "unexpected use of 'returned'");
1578         isThisReturn = true;
1579       }
1580       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1581     } else if (isByVal) {
1582       assert(VA.isMemLoc());
1583       unsigned offset = 0;
1584
1585       // True if this byval aggregate will be split between registers
1586       // and memory.
1587       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1588       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1589
1590       if (CurByValIdx < ByValArgsCount) {
1591
1592         unsigned RegBegin, RegEnd;
1593         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1594
1595         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1596         unsigned int i, j;
1597         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1598           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1599           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1600           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1601                                      MachinePointerInfo(),
1602                                      false, false, false,
1603                                      DAG.InferPtrAlignment(AddArg));
1604           MemOpChains.push_back(Load.getValue(1));
1605           RegsToPass.push_back(std::make_pair(j, Load));
1606         }
1607
1608         // If parameter size outsides register area, "offset" value
1609         // helps us to calculate stack slot for remained part properly.
1610         offset = RegEnd - RegBegin;
1611
1612         CCInfo.nextInRegsParam();
1613       }
1614
1615       if (Flags.getByValSize() > 4*offset) {
1616         unsigned LocMemOffset = VA.getLocMemOffset();
1617         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1618         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1619                                   StkPtrOff);
1620         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1621         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1622         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1623                                            MVT::i32);
1624         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1625
1626         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1627         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1628         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1629                                           Ops));
1630       }
1631     } else if (!isSibCall) {
1632       assert(VA.isMemLoc());
1633
1634       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1635                                              dl, DAG, VA, Flags));
1636     }
1637   }
1638
1639   if (!MemOpChains.empty())
1640     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1641
1642   // Build a sequence of copy-to-reg nodes chained together with token chain
1643   // and flag operands which copy the outgoing args into the appropriate regs.
1644   SDValue InFlag;
1645   // Tail call byval lowering might overwrite argument registers so in case of
1646   // tail call optimization the copies to registers are lowered later.
1647   if (!isTailCall)
1648     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1649       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1650                                RegsToPass[i].second, InFlag);
1651       InFlag = Chain.getValue(1);
1652     }
1653
1654   // For tail calls lower the arguments to the 'real' stack slot.
1655   if (isTailCall) {
1656     // Force all the incoming stack arguments to be loaded from the stack
1657     // before any new outgoing arguments are stored to the stack, because the
1658     // outgoing stack slots may alias the incoming argument stack slots, and
1659     // the alias isn't otherwise explicit. This is slightly more conservative
1660     // than necessary, because it means that each store effectively depends
1661     // on every argument instead of just those arguments it would clobber.
1662
1663     // Do not flag preceding copytoreg stuff together with the following stuff.
1664     InFlag = SDValue();
1665     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1666       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1667                                RegsToPass[i].second, InFlag);
1668       InFlag = Chain.getValue(1);
1669     }
1670     InFlag = SDValue();
1671   }
1672
1673   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1674   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1675   // node so that legalize doesn't hack it.
1676   bool isDirect = false;
1677   bool isARMFunc = false;
1678   bool isLocalARMFunc = false;
1679   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1680
1681   if (EnableARMLongCalls) {
1682     assert((Subtarget->isTargetWindows() ||
1683             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1684            "long-calls with non-static relocation model!");
1685     // Handle a global address or an external symbol. If it's not one of
1686     // those, the target's already in a register, so we don't need to do
1687     // anything extra.
1688     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1689       const GlobalValue *GV = G->getGlobal();
1690       // Create a constant pool entry for the callee address
1691       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1692       ARMConstantPoolValue *CPV =
1693         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1694
1695       // Get the address of the callee into a register
1696       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1697       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1698       Callee = DAG.getLoad(getPointerTy(), dl,
1699                            DAG.getEntryNode(), CPAddr,
1700                            MachinePointerInfo::getConstantPool(),
1701                            false, false, false, 0);
1702     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1703       const char *Sym = S->getSymbol();
1704
1705       // Create a constant pool entry for the callee address
1706       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1707       ARMConstantPoolValue *CPV =
1708         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1709                                       ARMPCLabelIndex, 0);
1710       // Get the address of the callee into a register
1711       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1712       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1713       Callee = DAG.getLoad(getPointerTy(), dl,
1714                            DAG.getEntryNode(), CPAddr,
1715                            MachinePointerInfo::getConstantPool(),
1716                            false, false, false, 0);
1717     }
1718   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1719     const GlobalValue *GV = G->getGlobal();
1720     isDirect = true;
1721     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1722     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1723                    getTargetMachine().getRelocationModel() != Reloc::Static;
1724     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1725     // ARM call to a local ARM function is predicable.
1726     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1727     // tBX takes a register source operand.
1728     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1729       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1730       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1731                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1732                                                       0, ARMII::MO_NONLAZY));
1733       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1734                            MachinePointerInfo::getGOT(), false, false, true, 0);
1735     } else if (Subtarget->isTargetCOFF()) {
1736       assert(Subtarget->isTargetWindows() &&
1737              "Windows is the only supported COFF target");
1738       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1739                                  ? ARMII::MO_DLLIMPORT
1740                                  : ARMII::MO_NO_FLAG;
1741       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1742                                           TargetFlags);
1743       if (GV->hasDLLImportStorageClass())
1744         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1745                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1746                                          Callee), MachinePointerInfo::getGOT(),
1747                              false, false, false, 0);
1748     } else {
1749       // On ELF targets for PIC code, direct calls should go through the PLT
1750       unsigned OpFlags = 0;
1751       if (Subtarget->isTargetELF() &&
1752           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1753         OpFlags = ARMII::MO_PLT;
1754       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1755     }
1756   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1757     isDirect = true;
1758     bool isStub = Subtarget->isTargetMachO() &&
1759                   getTargetMachine().getRelocationModel() != Reloc::Static;
1760     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1761     // tBX takes a register source operand.
1762     const char *Sym = S->getSymbol();
1763     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1764       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1765       ARMConstantPoolValue *CPV =
1766         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1767                                       ARMPCLabelIndex, 4);
1768       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1769       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1770       Callee = DAG.getLoad(getPointerTy(), dl,
1771                            DAG.getEntryNode(), CPAddr,
1772                            MachinePointerInfo::getConstantPool(),
1773                            false, false, false, 0);
1774       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1775       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1776                            getPointerTy(), Callee, PICLabel);
1777     } else {
1778       unsigned OpFlags = 0;
1779       // On ELF targets for PIC code, direct calls should go through the PLT
1780       if (Subtarget->isTargetELF() &&
1781                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1782         OpFlags = ARMII::MO_PLT;
1783       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1784     }
1785   }
1786
1787   // FIXME: handle tail calls differently.
1788   unsigned CallOpc;
1789   bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1790       AttributeSet::FunctionIndex, Attribute::MinSize);
1791   if (Subtarget->isThumb()) {
1792     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1793       CallOpc = ARMISD::CALL_NOLINK;
1794     else
1795       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1796   } else {
1797     if (!isDirect && !Subtarget->hasV5TOps())
1798       CallOpc = ARMISD::CALL_NOLINK;
1799     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1800                // Emit regular call when code size is the priority
1801                !HasMinSizeAttr)
1802       // "mov lr, pc; b _foo" to avoid confusing the RSP
1803       CallOpc = ARMISD::CALL_NOLINK;
1804     else
1805       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1806   }
1807
1808   std::vector<SDValue> Ops;
1809   Ops.push_back(Chain);
1810   Ops.push_back(Callee);
1811
1812   // Add argument registers to the end of the list so that they are known live
1813   // into the call.
1814   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1815     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1816                                   RegsToPass[i].second.getValueType()));
1817
1818   // Add a register mask operand representing the call-preserved registers.
1819   if (!isTailCall) {
1820     const uint32_t *Mask;
1821     const TargetRegisterInfo *TRI =
1822         getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1823     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1824     if (isThisReturn) {
1825       // For 'this' returns, use the R0-preserving mask if applicable
1826       Mask = ARI->getThisReturnPreservedMask(CallConv);
1827       if (!Mask) {
1828         // Set isThisReturn to false if the calling convention is not one that
1829         // allows 'returned' to be modeled in this way, so LowerCallResult does
1830         // not try to pass 'this' straight through
1831         isThisReturn = false;
1832         Mask = ARI->getCallPreservedMask(CallConv);
1833       }
1834     } else
1835       Mask = ARI->getCallPreservedMask(CallConv);
1836
1837     assert(Mask && "Missing call preserved mask for calling convention");
1838     Ops.push_back(DAG.getRegisterMask(Mask));
1839   }
1840
1841   if (InFlag.getNode())
1842     Ops.push_back(InFlag);
1843
1844   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1845   if (isTailCall)
1846     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1847
1848   // Returns a chain and a flag for retval copy to use.
1849   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1850   InFlag = Chain.getValue(1);
1851
1852   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1853                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1854   if (!Ins.empty())
1855     InFlag = Chain.getValue(1);
1856
1857   // Handle result values, copying them out of physregs into vregs that we
1858   // return.
1859   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1860                          InVals, isThisReturn,
1861                          isThisReturn ? OutVals[0] : SDValue());
1862 }
1863
1864 /// HandleByVal - Every parameter *after* a byval parameter is passed
1865 /// on the stack.  Remember the next parameter register to allocate,
1866 /// and then confiscate the rest of the parameter registers to insure
1867 /// this.
1868 void
1869 ARMTargetLowering::HandleByVal(
1870     CCState *State, unsigned &size, unsigned Align) const {
1871   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1872   assert((State->getCallOrPrologue() == Prologue ||
1873           State->getCallOrPrologue() == Call) &&
1874          "unhandled ParmContext");
1875
1876   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1877     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1878       unsigned AlignInRegs = Align / 4;
1879       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1880       for (unsigned i = 0; i < Waste; ++i)
1881         reg = State->AllocateReg(GPRArgRegs, 4);
1882     }
1883     if (reg != 0) {
1884       unsigned excess = 4 * (ARM::R4 - reg);
1885
1886       // Special case when NSAA != SP and parameter size greater than size of
1887       // all remained GPR regs. In that case we can't split parameter, we must
1888       // send it to stack. We also must set NCRN to R4, so waste all
1889       // remained registers.
1890       const unsigned NSAAOffset = State->getNextStackOffset();
1891       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1892         while (State->AllocateReg(GPRArgRegs, 4))
1893           ;
1894         return;
1895       }
1896
1897       // First register for byval parameter is the first register that wasn't
1898       // allocated before this method call, so it would be "reg".
1899       // If parameter is small enough to be saved in range [reg, r4), then
1900       // the end (first after last) register would be reg + param-size-in-regs,
1901       // else parameter would be splitted between registers and stack,
1902       // end register would be r4 in this case.
1903       unsigned ByValRegBegin = reg;
1904       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1905       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1906       // Note, first register is allocated in the beginning of function already,
1907       // allocate remained amount of registers we need.
1908       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1909         State->AllocateReg(GPRArgRegs, 4);
1910       // A byval parameter that is split between registers and memory needs its
1911       // size truncated here.
1912       // In the case where the entire structure fits in registers, we set the
1913       // size in memory to zero.
1914       if (size < excess)
1915         size = 0;
1916       else
1917         size -= excess;
1918     }
1919   }
1920 }
1921
1922 /// MatchingStackOffset - Return true if the given stack call argument is
1923 /// already available in the same position (relatively) of the caller's
1924 /// incoming argument stack.
1925 static
1926 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1927                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1928                          const TargetInstrInfo *TII) {
1929   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1930   int FI = INT_MAX;
1931   if (Arg.getOpcode() == ISD::CopyFromReg) {
1932     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1933     if (!TargetRegisterInfo::isVirtualRegister(VR))
1934       return false;
1935     MachineInstr *Def = MRI->getVRegDef(VR);
1936     if (!Def)
1937       return false;
1938     if (!Flags.isByVal()) {
1939       if (!TII->isLoadFromStackSlot(Def, FI))
1940         return false;
1941     } else {
1942       return false;
1943     }
1944   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1945     if (Flags.isByVal())
1946       // ByVal argument is passed in as a pointer but it's now being
1947       // dereferenced. e.g.
1948       // define @foo(%struct.X* %A) {
1949       //   tail call @bar(%struct.X* byval %A)
1950       // }
1951       return false;
1952     SDValue Ptr = Ld->getBasePtr();
1953     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1954     if (!FINode)
1955       return false;
1956     FI = FINode->getIndex();
1957   } else
1958     return false;
1959
1960   assert(FI != INT_MAX);
1961   if (!MFI->isFixedObjectIndex(FI))
1962     return false;
1963   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1964 }
1965
1966 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1967 /// for tail call optimization. Targets which want to do tail call
1968 /// optimization should implement this function.
1969 bool
1970 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1971                                                      CallingConv::ID CalleeCC,
1972                                                      bool isVarArg,
1973                                                      bool isCalleeStructRet,
1974                                                      bool isCallerStructRet,
1975                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1976                                     const SmallVectorImpl<SDValue> &OutVals,
1977                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1978                                                      SelectionDAG& DAG) const {
1979   const Function *CallerF = DAG.getMachineFunction().getFunction();
1980   CallingConv::ID CallerCC = CallerF->getCallingConv();
1981   bool CCMatch = CallerCC == CalleeCC;
1982
1983   // Look for obvious safe cases to perform tail call optimization that do not
1984   // require ABI changes. This is what gcc calls sibcall.
1985
1986   // Do not sibcall optimize vararg calls unless the call site is not passing
1987   // any arguments.
1988   if (isVarArg && !Outs.empty())
1989     return false;
1990
1991   // Exception-handling functions need a special set of instructions to indicate
1992   // a return to the hardware. Tail-calling another function would probably
1993   // break this.
1994   if (CallerF->hasFnAttribute("interrupt"))
1995     return false;
1996
1997   // Also avoid sibcall optimization if either caller or callee uses struct
1998   // return semantics.
1999   if (isCalleeStructRet || isCallerStructRet)
2000     return false;
2001
2002   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
2003   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2004   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2005   // support in the assembler and linker to be used. This would need to be
2006   // fixed to fully support tail calls in Thumb1.
2007   //
2008   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2009   // LR.  This means if we need to reload LR, it takes an extra instructions,
2010   // which outweighs the value of the tail call; but here we don't know yet
2011   // whether LR is going to be used.  Probably the right approach is to
2012   // generate the tail call here and turn it back into CALL/RET in
2013   // emitEpilogue if LR is used.
2014
2015   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2016   // but we need to make sure there are enough registers; the only valid
2017   // registers are the 4 used for parameters.  We don't currently do this
2018   // case.
2019   if (Subtarget->isThumb1Only())
2020     return false;
2021
2022   // Externally-defined functions with weak linkage should not be
2023   // tail-called on ARM when the OS does not support dynamic
2024   // pre-emption of symbols, as the AAELF spec requires normal calls
2025   // to undefined weak functions to be replaced with a NOP or jump to the
2026   // next instruction. The behaviour of branch instructions in this
2027   // situation (as used for tail calls) is implementation-defined, so we
2028   // cannot rely on the linker replacing the tail call with a return.
2029   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2030     const GlobalValue *GV = G->getGlobal();
2031     const Triple TT(getTargetMachine().getTargetTriple());
2032     if (GV->hasExternalWeakLinkage() &&
2033         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2034       return false;
2035   }
2036
2037   // If the calling conventions do not match, then we'd better make sure the
2038   // results are returned in the same way as what the caller expects.
2039   if (!CCMatch) {
2040     SmallVector<CCValAssign, 16> RVLocs1;
2041     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2042                        *DAG.getContext(), Call);
2043     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2044
2045     SmallVector<CCValAssign, 16> RVLocs2;
2046     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2047                        *DAG.getContext(), Call);
2048     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2049
2050     if (RVLocs1.size() != RVLocs2.size())
2051       return false;
2052     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2053       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2054         return false;
2055       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2056         return false;
2057       if (RVLocs1[i].isRegLoc()) {
2058         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2059           return false;
2060       } else {
2061         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2062           return false;
2063       }
2064     }
2065   }
2066
2067   // If Caller's vararg or byval argument has been split between registers and
2068   // stack, do not perform tail call, since part of the argument is in caller's
2069   // local frame.
2070   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2071                                       getInfo<ARMFunctionInfo>();
2072   if (AFI_Caller->getArgRegsSaveSize())
2073     return false;
2074
2075   // If the callee takes no arguments then go on to check the results of the
2076   // call.
2077   if (!Outs.empty()) {
2078     // Check if stack adjustment is needed. For now, do not do this if any
2079     // argument is passed on the stack.
2080     SmallVector<CCValAssign, 16> ArgLocs;
2081     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2082                       *DAG.getContext(), Call);
2083     CCInfo.AnalyzeCallOperands(Outs,
2084                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2085     if (CCInfo.getNextStackOffset()) {
2086       MachineFunction &MF = DAG.getMachineFunction();
2087
2088       // Check if the arguments are already laid out in the right way as
2089       // the caller's fixed stack objects.
2090       MachineFrameInfo *MFI = MF.getFrameInfo();
2091       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2092       const TargetInstrInfo *TII =
2093           getTargetMachine().getSubtargetImpl()->getInstrInfo();
2094       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2095            i != e;
2096            ++i, ++realArgIdx) {
2097         CCValAssign &VA = ArgLocs[i];
2098         EVT RegVT = VA.getLocVT();
2099         SDValue Arg = OutVals[realArgIdx];
2100         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2101         if (VA.getLocInfo() == CCValAssign::Indirect)
2102           return false;
2103         if (VA.needsCustom()) {
2104           // f64 and vector types are split into multiple registers or
2105           // register/stack-slot combinations.  The types will not match
2106           // the registers; give up on memory f64 refs until we figure
2107           // out what to do about this.
2108           if (!VA.isRegLoc())
2109             return false;
2110           if (!ArgLocs[++i].isRegLoc())
2111             return false;
2112           if (RegVT == MVT::v2f64) {
2113             if (!ArgLocs[++i].isRegLoc())
2114               return false;
2115             if (!ArgLocs[++i].isRegLoc())
2116               return false;
2117           }
2118         } else if (!VA.isRegLoc()) {
2119           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2120                                    MFI, MRI, TII))
2121             return false;
2122         }
2123       }
2124     }
2125   }
2126
2127   return true;
2128 }
2129
2130 bool
2131 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2132                                   MachineFunction &MF, bool isVarArg,
2133                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2134                                   LLVMContext &Context) const {
2135   SmallVector<CCValAssign, 16> RVLocs;
2136   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2137   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2138                                                     isVarArg));
2139 }
2140
2141 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2142                                     SDLoc DL, SelectionDAG &DAG) {
2143   const MachineFunction &MF = DAG.getMachineFunction();
2144   const Function *F = MF.getFunction();
2145
2146   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2147
2148   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2149   // version of the "preferred return address". These offsets affect the return
2150   // instruction if this is a return from PL1 without hypervisor extensions.
2151   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2152   //    SWI:     0      "subs pc, lr, #0"
2153   //    ABORT:   +4     "subs pc, lr, #4"
2154   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2155   // UNDEF varies depending on where the exception came from ARM or Thumb
2156   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2157
2158   int64_t LROffset;
2159   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2160       IntKind == "ABORT")
2161     LROffset = 4;
2162   else if (IntKind == "SWI" || IntKind == "UNDEF")
2163     LROffset = 0;
2164   else
2165     report_fatal_error("Unsupported interrupt attribute. If present, value "
2166                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2167
2168   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2169
2170   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2171 }
2172
2173 SDValue
2174 ARMTargetLowering::LowerReturn(SDValue Chain,
2175                                CallingConv::ID CallConv, bool isVarArg,
2176                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2177                                const SmallVectorImpl<SDValue> &OutVals,
2178                                SDLoc dl, SelectionDAG &DAG) const {
2179
2180   // CCValAssign - represent the assignment of the return value to a location.
2181   SmallVector<CCValAssign, 16> RVLocs;
2182
2183   // CCState - Info about the registers and stack slots.
2184   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2185                     *DAG.getContext(), Call);
2186
2187   // Analyze outgoing return values.
2188   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2189                                                isVarArg));
2190
2191   SDValue Flag;
2192   SmallVector<SDValue, 4> RetOps;
2193   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2194   bool isLittleEndian = Subtarget->isLittle();
2195
2196   MachineFunction &MF = DAG.getMachineFunction();
2197   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2198   AFI->setReturnRegsCount(RVLocs.size());
2199
2200   // Copy the result values into the output registers.
2201   for (unsigned i = 0, realRVLocIdx = 0;
2202        i != RVLocs.size();
2203        ++i, ++realRVLocIdx) {
2204     CCValAssign &VA = RVLocs[i];
2205     assert(VA.isRegLoc() && "Can only return in registers!");
2206
2207     SDValue Arg = OutVals[realRVLocIdx];
2208
2209     switch (VA.getLocInfo()) {
2210     default: llvm_unreachable("Unknown loc info!");
2211     case CCValAssign::Full: break;
2212     case CCValAssign::BCvt:
2213       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2214       break;
2215     }
2216
2217     if (VA.needsCustom()) {
2218       if (VA.getLocVT() == MVT::v2f64) {
2219         // Extract the first half and return it in two registers.
2220         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2221                                    DAG.getConstant(0, MVT::i32));
2222         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2223                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2224
2225         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2226                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2227                                  Flag);
2228         Flag = Chain.getValue(1);
2229         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2230         VA = RVLocs[++i]; // skip ahead to next loc
2231         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2232                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2233                                  Flag);
2234         Flag = Chain.getValue(1);
2235         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2236         VA = RVLocs[++i]; // skip ahead to next loc
2237
2238         // Extract the 2nd half and fall through to handle it as an f64 value.
2239         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2240                           DAG.getConstant(1, MVT::i32));
2241       }
2242       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2243       // available.
2244       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2245                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2246       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2247                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2248                                Flag);
2249       Flag = Chain.getValue(1);
2250       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2251       VA = RVLocs[++i]; // skip ahead to next loc
2252       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2253                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2254                                Flag);
2255     } else
2256       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2257
2258     // Guarantee that all emitted copies are
2259     // stuck together, avoiding something bad.
2260     Flag = Chain.getValue(1);
2261     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2262   }
2263
2264   // Update chain and glue.
2265   RetOps[0] = Chain;
2266   if (Flag.getNode())
2267     RetOps.push_back(Flag);
2268
2269   // CPUs which aren't M-class use a special sequence to return from
2270   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2271   // though we use "subs pc, lr, #N").
2272   //
2273   // M-class CPUs actually use a normal return sequence with a special
2274   // (hardware-provided) value in LR, so the normal code path works.
2275   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2276       !Subtarget->isMClass()) {
2277     if (Subtarget->isThumb1Only())
2278       report_fatal_error("interrupt attribute is not supported in Thumb1");
2279     return LowerInterruptReturn(RetOps, dl, DAG);
2280   }
2281
2282   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2283 }
2284
2285 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2286   if (N->getNumValues() != 1)
2287     return false;
2288   if (!N->hasNUsesOfValue(1, 0))
2289     return false;
2290
2291   SDValue TCChain = Chain;
2292   SDNode *Copy = *N->use_begin();
2293   if (Copy->getOpcode() == ISD::CopyToReg) {
2294     // If the copy has a glue operand, we conservatively assume it isn't safe to
2295     // perform a tail call.
2296     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2297       return false;
2298     TCChain = Copy->getOperand(0);
2299   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2300     SDNode *VMov = Copy;
2301     // f64 returned in a pair of GPRs.
2302     SmallPtrSet<SDNode*, 2> Copies;
2303     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2304          UI != UE; ++UI) {
2305       if (UI->getOpcode() != ISD::CopyToReg)
2306         return false;
2307       Copies.insert(*UI);
2308     }
2309     if (Copies.size() > 2)
2310       return false;
2311
2312     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2313          UI != UE; ++UI) {
2314       SDValue UseChain = UI->getOperand(0);
2315       if (Copies.count(UseChain.getNode()))
2316         // Second CopyToReg
2317         Copy = *UI;
2318       else {
2319         // We are at the top of this chain.
2320         // If the copy has a glue operand, we conservatively assume it
2321         // isn't safe to perform a tail call.
2322         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2323           return false;
2324         // First CopyToReg
2325         TCChain = UseChain;
2326       }
2327     }
2328   } else if (Copy->getOpcode() == ISD::BITCAST) {
2329     // f32 returned in a single GPR.
2330     if (!Copy->hasOneUse())
2331       return false;
2332     Copy = *Copy->use_begin();
2333     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2334       return false;
2335     // If the copy has a glue operand, we conservatively assume it isn't safe to
2336     // perform a tail call.
2337     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2338       return false;
2339     TCChain = Copy->getOperand(0);
2340   } else {
2341     return false;
2342   }
2343
2344   bool HasRet = false;
2345   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2346        UI != UE; ++UI) {
2347     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2348         UI->getOpcode() != ARMISD::INTRET_FLAG)
2349       return false;
2350     HasRet = true;
2351   }
2352
2353   if (!HasRet)
2354     return false;
2355
2356   Chain = TCChain;
2357   return true;
2358 }
2359
2360 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2361   if (!Subtarget->supportsTailCall())
2362     return false;
2363
2364   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2365     return false;
2366
2367   return !Subtarget->isThumb1Only();
2368 }
2369
2370 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2371 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2372 // one of the above mentioned nodes. It has to be wrapped because otherwise
2373 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2374 // be used to form addressing mode. These wrapped nodes will be selected
2375 // into MOVi.
2376 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2377   EVT PtrVT = Op.getValueType();
2378   // FIXME there is no actual debug info here
2379   SDLoc dl(Op);
2380   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2381   SDValue Res;
2382   if (CP->isMachineConstantPoolEntry())
2383     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2384                                     CP->getAlignment());
2385   else
2386     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2387                                     CP->getAlignment());
2388   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2389 }
2390
2391 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2392   return MachineJumpTableInfo::EK_Inline;
2393 }
2394
2395 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2396                                              SelectionDAG &DAG) const {
2397   MachineFunction &MF = DAG.getMachineFunction();
2398   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2399   unsigned ARMPCLabelIndex = 0;
2400   SDLoc DL(Op);
2401   EVT PtrVT = getPointerTy();
2402   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2403   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2404   SDValue CPAddr;
2405   if (RelocM == Reloc::Static) {
2406     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2407   } else {
2408     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2409     ARMPCLabelIndex = AFI->createPICLabelUId();
2410     ARMConstantPoolValue *CPV =
2411       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2412                                       ARMCP::CPBlockAddress, PCAdj);
2413     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2414   }
2415   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2416   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2417                                MachinePointerInfo::getConstantPool(),
2418                                false, false, false, 0);
2419   if (RelocM == Reloc::Static)
2420     return Result;
2421   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2422   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2423 }
2424
2425 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2426 SDValue
2427 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2428                                                  SelectionDAG &DAG) const {
2429   SDLoc dl(GA);
2430   EVT PtrVT = getPointerTy();
2431   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2432   MachineFunction &MF = DAG.getMachineFunction();
2433   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2434   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2435   ARMConstantPoolValue *CPV =
2436     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2437                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2438   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2439   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2440   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2441                          MachinePointerInfo::getConstantPool(),
2442                          false, false, false, 0);
2443   SDValue Chain = Argument.getValue(1);
2444
2445   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2446   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2447
2448   // call __tls_get_addr.
2449   ArgListTy Args;
2450   ArgListEntry Entry;
2451   Entry.Node = Argument;
2452   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2453   Args.push_back(Entry);
2454
2455   // FIXME: is there useful debug info available here?
2456   TargetLowering::CallLoweringInfo CLI(DAG);
2457   CLI.setDebugLoc(dl).setChain(Chain)
2458     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2459                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2460                0);
2461
2462   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2463   return CallResult.first;
2464 }
2465
2466 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2467 // "local exec" model.
2468 SDValue
2469 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2470                                         SelectionDAG &DAG,
2471                                         TLSModel::Model model) const {
2472   const GlobalValue *GV = GA->getGlobal();
2473   SDLoc dl(GA);
2474   SDValue Offset;
2475   SDValue Chain = DAG.getEntryNode();
2476   EVT PtrVT = getPointerTy();
2477   // Get the Thread Pointer
2478   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2479
2480   if (model == TLSModel::InitialExec) {
2481     MachineFunction &MF = DAG.getMachineFunction();
2482     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2483     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2484     // Initial exec model.
2485     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2486     ARMConstantPoolValue *CPV =
2487       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2488                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2489                                       true);
2490     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2491     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2492     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2493                          MachinePointerInfo::getConstantPool(),
2494                          false, false, false, 0);
2495     Chain = Offset.getValue(1);
2496
2497     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2498     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2499
2500     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2501                          MachinePointerInfo::getConstantPool(),
2502                          false, false, false, 0);
2503   } else {
2504     // local exec model
2505     assert(model == TLSModel::LocalExec);
2506     ARMConstantPoolValue *CPV =
2507       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2508     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2509     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2510     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2511                          MachinePointerInfo::getConstantPool(),
2512                          false, false, false, 0);
2513   }
2514
2515   // The address of the thread local variable is the add of the thread
2516   // pointer with the offset of the variable.
2517   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2518 }
2519
2520 SDValue
2521 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2522   // TODO: implement the "local dynamic" model
2523   assert(Subtarget->isTargetELF() &&
2524          "TLS not implemented for non-ELF targets");
2525   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2526
2527   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2528
2529   switch (model) {
2530     case TLSModel::GeneralDynamic:
2531     case TLSModel::LocalDynamic:
2532       return LowerToTLSGeneralDynamicModel(GA, DAG);
2533     case TLSModel::InitialExec:
2534     case TLSModel::LocalExec:
2535       return LowerToTLSExecModels(GA, DAG, model);
2536   }
2537   llvm_unreachable("bogus TLS model");
2538 }
2539
2540 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2541                                                  SelectionDAG &DAG) const {
2542   EVT PtrVT = getPointerTy();
2543   SDLoc dl(Op);
2544   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2545   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2546     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2547     ARMConstantPoolValue *CPV =
2548       ARMConstantPoolConstant::Create(GV,
2549                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2550     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2551     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2552     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2553                                  CPAddr,
2554                                  MachinePointerInfo::getConstantPool(),
2555                                  false, false, false, 0);
2556     SDValue Chain = Result.getValue(1);
2557     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2558     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2559     if (!UseGOTOFF)
2560       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2561                            MachinePointerInfo::getGOT(),
2562                            false, false, false, 0);
2563     return Result;
2564   }
2565
2566   // If we have T2 ops, we can materialize the address directly via movt/movw
2567   // pair. This is always cheaper.
2568   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2569     ++NumMovwMovt;
2570     // FIXME: Once remat is capable of dealing with instructions with register
2571     // operands, expand this into two nodes.
2572     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2573                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2574   } else {
2575     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2576     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2577     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2578                        MachinePointerInfo::getConstantPool(),
2579                        false, false, false, 0);
2580   }
2581 }
2582
2583 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2584                                                     SelectionDAG &DAG) const {
2585   EVT PtrVT = getPointerTy();
2586   SDLoc dl(Op);
2587   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2588   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2589
2590   if (Subtarget->useMovt(DAG.getMachineFunction()))
2591     ++NumMovwMovt;
2592
2593   // FIXME: Once remat is capable of dealing with instructions with register
2594   // operands, expand this into multiple nodes
2595   unsigned Wrapper =
2596       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2597
2598   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2599   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2600
2601   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2602     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2603                          MachinePointerInfo::getGOT(), false, false, false, 0);
2604   return Result;
2605 }
2606
2607 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2608                                                      SelectionDAG &DAG) const {
2609   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2610   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2611          "Windows on ARM expects to use movw/movt");
2612
2613   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2614   const ARMII::TOF TargetFlags =
2615     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2616   EVT PtrVT = getPointerTy();
2617   SDValue Result;
2618   SDLoc DL(Op);
2619
2620   ++NumMovwMovt;
2621
2622   // FIXME: Once remat is capable of dealing with instructions with register
2623   // operands, expand this into two nodes.
2624   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2625                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2626                                                   TargetFlags));
2627   if (GV->hasDLLImportStorageClass())
2628     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2629                          MachinePointerInfo::getGOT(), false, false, false, 0);
2630   return Result;
2631 }
2632
2633 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2634                                                     SelectionDAG &DAG) const {
2635   assert(Subtarget->isTargetELF() &&
2636          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2637   MachineFunction &MF = DAG.getMachineFunction();
2638   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2639   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2640   EVT PtrVT = getPointerTy();
2641   SDLoc dl(Op);
2642   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2643   ARMConstantPoolValue *CPV =
2644     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2645                                   ARMPCLabelIndex, PCAdj);
2646   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2647   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2648   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2649                                MachinePointerInfo::getConstantPool(),
2650                                false, false, false, 0);
2651   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2652   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2653 }
2654
2655 SDValue
2656 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2657   SDLoc dl(Op);
2658   SDValue Val = DAG.getConstant(0, MVT::i32);
2659   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2660                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2661                      Op.getOperand(1), Val);
2662 }
2663
2664 SDValue
2665 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2666   SDLoc dl(Op);
2667   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2668                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2669 }
2670
2671 SDValue
2672 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2673                                           const ARMSubtarget *Subtarget) const {
2674   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2675   SDLoc dl(Op);
2676   switch (IntNo) {
2677   default: return SDValue();    // Don't custom lower most intrinsics.
2678   case Intrinsic::arm_rbit: {
2679     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2680            "RBIT intrinsic must have i32 type!");
2681     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2682   }
2683   case Intrinsic::arm_thread_pointer: {
2684     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2685     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2686   }
2687   case Intrinsic::eh_sjlj_lsda: {
2688     MachineFunction &MF = DAG.getMachineFunction();
2689     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2690     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2691     EVT PtrVT = getPointerTy();
2692     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2693     SDValue CPAddr;
2694     unsigned PCAdj = (RelocM != Reloc::PIC_)
2695       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2696     ARMConstantPoolValue *CPV =
2697       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2698                                       ARMCP::CPLSDA, PCAdj);
2699     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2700     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2701     SDValue Result =
2702       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2703                   MachinePointerInfo::getConstantPool(),
2704                   false, false, false, 0);
2705
2706     if (RelocM == Reloc::PIC_) {
2707       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2708       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2709     }
2710     return Result;
2711   }
2712   case Intrinsic::arm_neon_vmulls:
2713   case Intrinsic::arm_neon_vmullu: {
2714     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2715       ? ARMISD::VMULLs : ARMISD::VMULLu;
2716     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2717                        Op.getOperand(1), Op.getOperand(2));
2718   }
2719   }
2720 }
2721
2722 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2723                                  const ARMSubtarget *Subtarget) {
2724   // FIXME: handle "fence singlethread" more efficiently.
2725   SDLoc dl(Op);
2726   if (!Subtarget->hasDataBarrier()) {
2727     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2728     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2729     // here.
2730     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2731            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2732     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2733                        DAG.getConstant(0, MVT::i32));
2734   }
2735
2736   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2737   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2738   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2739   if (Subtarget->isMClass()) {
2740     // Only a full system barrier exists in the M-class architectures.
2741     Domain = ARM_MB::SY;
2742   } else if (Subtarget->isSwift() && Ord == Release) {
2743     // Swift happens to implement ISHST barriers in a way that's compatible with
2744     // Release semantics but weaker than ISH so we'd be fools not to use
2745     // it. Beware: other processors probably don't!
2746     Domain = ARM_MB::ISHST;
2747   }
2748
2749   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2750                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2751                      DAG.getConstant(Domain, MVT::i32));
2752 }
2753
2754 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2755                              const ARMSubtarget *Subtarget) {
2756   // ARM pre v5TE and Thumb1 does not have preload instructions.
2757   if (!(Subtarget->isThumb2() ||
2758         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2759     // Just preserve the chain.
2760     return Op.getOperand(0);
2761
2762   SDLoc dl(Op);
2763   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2764   if (!isRead &&
2765       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2766     // ARMv7 with MP extension has PLDW.
2767     return Op.getOperand(0);
2768
2769   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2770   if (Subtarget->isThumb()) {
2771     // Invert the bits.
2772     isRead = ~isRead & 1;
2773     isData = ~isData & 1;
2774   }
2775
2776   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2777                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2778                      DAG.getConstant(isData, MVT::i32));
2779 }
2780
2781 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2782   MachineFunction &MF = DAG.getMachineFunction();
2783   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2784
2785   // vastart just stores the address of the VarArgsFrameIndex slot into the
2786   // memory location argument.
2787   SDLoc dl(Op);
2788   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2789   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2790   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2791   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2792                       MachinePointerInfo(SV), false, false, 0);
2793 }
2794
2795 SDValue
2796 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2797                                         SDValue &Root, SelectionDAG &DAG,
2798                                         SDLoc dl) const {
2799   MachineFunction &MF = DAG.getMachineFunction();
2800   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2801
2802   const TargetRegisterClass *RC;
2803   if (AFI->isThumb1OnlyFunction())
2804     RC = &ARM::tGPRRegClass;
2805   else
2806     RC = &ARM::GPRRegClass;
2807
2808   // Transform the arguments stored in physical registers into virtual ones.
2809   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2810   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2811
2812   SDValue ArgValue2;
2813   if (NextVA.isMemLoc()) {
2814     MachineFrameInfo *MFI = MF.getFrameInfo();
2815     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2816
2817     // Create load node to retrieve arguments from the stack.
2818     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2819     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2820                             MachinePointerInfo::getFixedStack(FI),
2821                             false, false, false, 0);
2822   } else {
2823     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2824     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2825   }
2826   if (!Subtarget->isLittle())
2827     std::swap (ArgValue, ArgValue2);
2828   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2829 }
2830
2831 void
2832 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2833                                   unsigned InRegsParamRecordIdx,
2834                                   unsigned ArgSize,
2835                                   unsigned &ArgRegsSize,
2836                                   unsigned &ArgRegsSaveSize)
2837   const {
2838   unsigned NumGPRs;
2839   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2840     unsigned RBegin, REnd;
2841     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2842     NumGPRs = REnd - RBegin;
2843   } else {
2844     unsigned int firstUnalloced;
2845     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2846                                                 sizeof(GPRArgRegs) /
2847                                                 sizeof(GPRArgRegs[0]));
2848     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2849   }
2850
2851   unsigned Align = MF.getTarget()
2852                        .getSubtargetImpl()
2853                        ->getFrameLowering()
2854                        ->getStackAlignment();
2855   ArgRegsSize = NumGPRs * 4;
2856
2857   // If parameter is split between stack and GPRs...
2858   if (NumGPRs && Align > 4 &&
2859       (ArgRegsSize < ArgSize ||
2860         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2861     // Add padding for part of param recovered from GPRs.  For example,
2862     // if Align == 8, its last byte must be at address K*8 - 1.
2863     // We need to do it, since remained (stack) part of parameter has
2864     // stack alignment, and we need to "attach" "GPRs head" without gaps
2865     // to it:
2866     // Stack:
2867     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2868     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2869     //
2870     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2871     unsigned Padding =
2872         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2873     ArgRegsSaveSize = ArgRegsSize + Padding;
2874   } else
2875     // We don't need to extend regs save size for byval parameters if they
2876     // are passed via GPRs only.
2877     ArgRegsSaveSize = ArgRegsSize;
2878 }
2879
2880 // The remaining GPRs hold either the beginning of variable-argument
2881 // data, or the beginning of an aggregate passed by value (usually
2882 // byval).  Either way, we allocate stack slots adjacent to the data
2883 // provided by our caller, and store the unallocated registers there.
2884 // If this is a variadic function, the va_list pointer will begin with
2885 // these values; otherwise, this reassembles a (byval) structure that
2886 // was split between registers and memory.
2887 // Return: The frame index registers were stored into.
2888 int
2889 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2890                                   SDLoc dl, SDValue &Chain,
2891                                   const Value *OrigArg,
2892                                   unsigned InRegsParamRecordIdx,
2893                                   unsigned OffsetFromOrigArg,
2894                                   unsigned ArgOffset,
2895                                   unsigned ArgSize,
2896                                   bool ForceMutable,
2897                                   unsigned ByValStoreOffset,
2898                                   unsigned TotalArgRegsSaveSize) const {
2899
2900   // Currently, two use-cases possible:
2901   // Case #1. Non-var-args function, and we meet first byval parameter.
2902   //          Setup first unallocated register as first byval register;
2903   //          eat all remained registers
2904   //          (these two actions are performed by HandleByVal method).
2905   //          Then, here, we initialize stack frame with
2906   //          "store-reg" instructions.
2907   // Case #2. Var-args function, that doesn't contain byval parameters.
2908   //          The same: eat all remained unallocated registers,
2909   //          initialize stack frame.
2910
2911   MachineFunction &MF = DAG.getMachineFunction();
2912   MachineFrameInfo *MFI = MF.getFrameInfo();
2913   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2914   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2915   unsigned RBegin, REnd;
2916   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2917     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2918     firstRegToSaveIndex = RBegin - ARM::R0;
2919     lastRegToSaveIndex = REnd - ARM::R0;
2920   } else {
2921     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2922       (GPRArgRegs, array_lengthof(GPRArgRegs));
2923     lastRegToSaveIndex = 4;
2924   }
2925
2926   unsigned ArgRegsSize, ArgRegsSaveSize;
2927   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2928                  ArgRegsSize, ArgRegsSaveSize);
2929
2930   // Store any by-val regs to their spots on the stack so that they may be
2931   // loaded by deferencing the result of formal parameter pointer or va_next.
2932   // Note: once stack area for byval/varargs registers
2933   // was initialized, it can't be initialized again.
2934   if (ArgRegsSaveSize) {
2935     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2936
2937     if (Padding) {
2938       assert(AFI->getStoredByValParamsPadding() == 0 &&
2939              "The only parameter may be padded.");
2940       AFI->setStoredByValParamsPadding(Padding);
2941     }
2942
2943     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2944                                             Padding +
2945                                               ByValStoreOffset -
2946                                               (int64_t)TotalArgRegsSaveSize,
2947                                             false);
2948     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2949     if (Padding) {
2950        MFI->CreateFixedObject(Padding,
2951                               ArgOffset + ByValStoreOffset -
2952                                 (int64_t)ArgRegsSaveSize,
2953                               false);
2954     }
2955
2956     SmallVector<SDValue, 4> MemOps;
2957     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2958          ++firstRegToSaveIndex, ++i) {
2959       const TargetRegisterClass *RC;
2960       if (AFI->isThumb1OnlyFunction())
2961         RC = &ARM::tGPRRegClass;
2962       else
2963         RC = &ARM::GPRRegClass;
2964
2965       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2966       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2967       SDValue Store =
2968         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2969                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2970                      false, false, 0);
2971       MemOps.push_back(Store);
2972       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2973                         DAG.getConstant(4, getPointerTy()));
2974     }
2975
2976     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2977
2978     if (!MemOps.empty())
2979       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2980     return FrameIndex;
2981   } else {
2982     if (ArgSize == 0) {
2983       // We cannot allocate a zero-byte object for the first variadic argument,
2984       // so just make up a size.
2985       ArgSize = 4;
2986     }
2987     // This will point to the next argument passed via stack.
2988     return MFI->CreateFixedObject(
2989       ArgSize, ArgOffset, !ForceMutable);
2990   }
2991 }
2992
2993 // Setup stack frame, the va_list pointer will start from.
2994 void
2995 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2996                                         SDLoc dl, SDValue &Chain,
2997                                         unsigned ArgOffset,
2998                                         unsigned TotalArgRegsSaveSize,
2999                                         bool ForceMutable) const {
3000   MachineFunction &MF = DAG.getMachineFunction();
3001   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3002
3003   // Try to store any remaining integer argument regs
3004   // to their spots on the stack so that they may be loaded by deferencing
3005   // the result of va_next.
3006   // If there is no regs to be stored, just point address after last
3007   // argument passed via stack.
3008   int FrameIndex =
3009     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3010                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
3011                    0, TotalArgRegsSaveSize);
3012
3013   AFI->setVarArgsFrameIndex(FrameIndex);
3014 }
3015
3016 SDValue
3017 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3018                                         CallingConv::ID CallConv, bool isVarArg,
3019                                         const SmallVectorImpl<ISD::InputArg>
3020                                           &Ins,
3021                                         SDLoc dl, SelectionDAG &DAG,
3022                                         SmallVectorImpl<SDValue> &InVals)
3023                                           const {
3024   MachineFunction &MF = DAG.getMachineFunction();
3025   MachineFrameInfo *MFI = MF.getFrameInfo();
3026
3027   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3028
3029   // Assign locations to all of the incoming arguments.
3030   SmallVector<CCValAssign, 16> ArgLocs;
3031   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3032                     *DAG.getContext(), Prologue);
3033   CCInfo.AnalyzeFormalArguments(Ins,
3034                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3035                                                   isVarArg));
3036
3037   SmallVector<SDValue, 16> ArgValues;
3038   int lastInsIndex = -1;
3039   SDValue ArgValue;
3040   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3041   unsigned CurArgIdx = 0;
3042
3043   // Initially ArgRegsSaveSize is zero.
3044   // Then we increase this value each time we meet byval parameter.
3045   // We also increase this value in case of varargs function.
3046   AFI->setArgRegsSaveSize(0);
3047
3048   unsigned ByValStoreOffset = 0;
3049   unsigned TotalArgRegsSaveSize = 0;
3050   unsigned ArgRegsSaveSizeMaxAlign = 4;
3051
3052   // Calculate the amount of stack space that we need to allocate to store
3053   // byval and variadic arguments that are passed in registers.
3054   // We need to know this before we allocate the first byval or variadic
3055   // argument, as they will be allocated a stack slot below the CFA (Canonical
3056   // Frame Address, the stack pointer at entry to the function).
3057   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3058     CCValAssign &VA = ArgLocs[i];
3059     if (VA.isMemLoc()) {
3060       int index = VA.getValNo();
3061       if (index != lastInsIndex) {
3062         ISD::ArgFlagsTy Flags = Ins[index].Flags;
3063         if (Flags.isByVal()) {
3064           unsigned ExtraArgRegsSize;
3065           unsigned ExtraArgRegsSaveSize;
3066           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProcessed(),
3067                          Flags.getByValSize(),
3068                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
3069
3070           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3071           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3072               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3073           CCInfo.nextInRegsParam();
3074         }
3075         lastInsIndex = index;
3076       }
3077     }
3078   }
3079   CCInfo.rewindByValRegsInfo();
3080   lastInsIndex = -1;
3081   if (isVarArg && MFI->hasVAStart()) {
3082     unsigned ExtraArgRegsSize;
3083     unsigned ExtraArgRegsSaveSize;
3084     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3085                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
3086     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3087   }
3088   // If the arg regs save area contains N-byte aligned values, the
3089   // bottom of it must be at least N-byte aligned.
3090   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3091   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3092
3093   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3094     CCValAssign &VA = ArgLocs[i];
3095     if (Ins[VA.getValNo()].isOrigArg()) {
3096       std::advance(CurOrigArg,
3097                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3098       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3099     }
3100     // Arguments stored in registers.
3101     if (VA.isRegLoc()) {
3102       EVT RegVT = VA.getLocVT();
3103
3104       if (VA.needsCustom()) {
3105         // f64 and vector types are split up into multiple registers or
3106         // combinations of registers and stack slots.
3107         if (VA.getLocVT() == MVT::v2f64) {
3108           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3109                                                    Chain, DAG, dl);
3110           VA = ArgLocs[++i]; // skip ahead to next loc
3111           SDValue ArgValue2;
3112           if (VA.isMemLoc()) {
3113             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3114             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3115             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3116                                     MachinePointerInfo::getFixedStack(FI),
3117                                     false, false, false, 0);
3118           } else {
3119             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3120                                              Chain, DAG, dl);
3121           }
3122           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3123           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3124                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3125           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3126                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3127         } else
3128           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3129
3130       } else {
3131         const TargetRegisterClass *RC;
3132
3133         if (RegVT == MVT::f32)
3134           RC = &ARM::SPRRegClass;
3135         else if (RegVT == MVT::f64)
3136           RC = &ARM::DPRRegClass;
3137         else if (RegVT == MVT::v2f64)
3138           RC = &ARM::QPRRegClass;
3139         else if (RegVT == MVT::i32)
3140           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3141                                            : &ARM::GPRRegClass;
3142         else
3143           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3144
3145         // Transform the arguments in physical registers into virtual ones.
3146         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3147         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3148       }
3149
3150       // If this is an 8 or 16-bit value, it is really passed promoted
3151       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3152       // truncate to the right size.
3153       switch (VA.getLocInfo()) {
3154       default: llvm_unreachable("Unknown loc info!");
3155       case CCValAssign::Full: break;
3156       case CCValAssign::BCvt:
3157         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3158         break;
3159       case CCValAssign::SExt:
3160         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3161                                DAG.getValueType(VA.getValVT()));
3162         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3163         break;
3164       case CCValAssign::ZExt:
3165         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3166                                DAG.getValueType(VA.getValVT()));
3167         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3168         break;
3169       }
3170
3171       InVals.push_back(ArgValue);
3172
3173     } else { // VA.isRegLoc()
3174
3175       // sanity check
3176       assert(VA.isMemLoc());
3177       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3178
3179       int index = VA.getValNo();
3180
3181       // Some Ins[] entries become multiple ArgLoc[] entries.
3182       // Process them only once.
3183       if (index != lastInsIndex)
3184         {
3185           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3186           // FIXME: For now, all byval parameter objects are marked mutable.
3187           // This can be changed with more analysis.
3188           // In case of tail call optimization mark all arguments mutable.
3189           // Since they could be overwritten by lowering of arguments in case of
3190           // a tail call.
3191           if (Flags.isByVal()) {
3192             assert(Ins[index].isOrigArg() &&
3193                    "Byval arguments cannot be implicit");
3194             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3195
3196             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3197             int FrameIndex = StoreByValRegs(
3198                 CCInfo, DAG, dl, Chain, CurOrigArg,
3199                 CurByValIndex,
3200                 Ins[VA.getValNo()].PartOffset,
3201                 VA.getLocMemOffset(),
3202                 Flags.getByValSize(),
3203                 true /*force mutable frames*/,
3204                 ByValStoreOffset,
3205                 TotalArgRegsSaveSize);
3206             ByValStoreOffset += Flags.getByValSize();
3207             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3208             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3209             CCInfo.nextInRegsParam();
3210           } else {
3211             unsigned FIOffset = VA.getLocMemOffset();
3212             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3213                                             FIOffset, true);
3214
3215             // Create load nodes to retrieve arguments from the stack.
3216             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3217             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3218                                          MachinePointerInfo::getFixedStack(FI),
3219                                          false, false, false, 0));
3220           }
3221           lastInsIndex = index;
3222         }
3223     }
3224   }
3225
3226   // varargs
3227   if (isVarArg && MFI->hasVAStart())
3228     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3229                          CCInfo.getNextStackOffset(),
3230                          TotalArgRegsSaveSize);
3231
3232   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3233
3234   return Chain;
3235 }
3236
3237 /// isFloatingPointZero - Return true if this is +0.0.
3238 static bool isFloatingPointZero(SDValue Op) {
3239   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3240     return CFP->getValueAPF().isPosZero();
3241   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3242     // Maybe this has already been legalized into the constant pool?
3243     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3244       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3245       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3246         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3247           return CFP->getValueAPF().isPosZero();
3248     }
3249   } else if (Op->getOpcode() == ISD::BITCAST &&
3250              Op->getValueType(0) == MVT::f64) {
3251     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3252     // created by LowerConstantFP().
3253     SDValue BitcastOp = Op->getOperand(0);
3254     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3255       SDValue MoveOp = BitcastOp->getOperand(0);
3256       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3257           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3258         return true;
3259       }
3260     }
3261   }
3262   return false;
3263 }
3264
3265 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3266 /// the given operands.
3267 SDValue
3268 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3269                              SDValue &ARMcc, SelectionDAG &DAG,
3270                              SDLoc dl) const {
3271   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3272     unsigned C = RHSC->getZExtValue();
3273     if (!isLegalICmpImmediate(C)) {
3274       // Constant does not fit, try adjusting it by one?
3275       switch (CC) {
3276       default: break;
3277       case ISD::SETLT:
3278       case ISD::SETGE:
3279         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3280           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3281           RHS = DAG.getConstant(C-1, MVT::i32);
3282         }
3283         break;
3284       case ISD::SETULT:
3285       case ISD::SETUGE:
3286         if (C != 0 && isLegalICmpImmediate(C-1)) {
3287           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3288           RHS = DAG.getConstant(C-1, MVT::i32);
3289         }
3290         break;
3291       case ISD::SETLE:
3292       case ISD::SETGT:
3293         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3294           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3295           RHS = DAG.getConstant(C+1, MVT::i32);
3296         }
3297         break;
3298       case ISD::SETULE:
3299       case ISD::SETUGT:
3300         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3301           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3302           RHS = DAG.getConstant(C+1, MVT::i32);
3303         }
3304         break;
3305       }
3306     }
3307   }
3308
3309   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3310   ARMISD::NodeType CompareType;
3311   switch (CondCode) {
3312   default:
3313     CompareType = ARMISD::CMP;
3314     break;
3315   case ARMCC::EQ:
3316   case ARMCC::NE:
3317     // Uses only Z Flag
3318     CompareType = ARMISD::CMPZ;
3319     break;
3320   }
3321   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3322   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3323 }
3324
3325 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3326 SDValue
3327 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3328                              SDLoc dl) const {
3329   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3330   SDValue Cmp;
3331   if (!isFloatingPointZero(RHS))
3332     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3333   else
3334     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3335   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3336 }
3337
3338 /// duplicateCmp - Glue values can have only one use, so this function
3339 /// duplicates a comparison node.
3340 SDValue
3341 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3342   unsigned Opc = Cmp.getOpcode();
3343   SDLoc DL(Cmp);
3344   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3345     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3346
3347   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3348   Cmp = Cmp.getOperand(0);
3349   Opc = Cmp.getOpcode();
3350   if (Opc == ARMISD::CMPFP)
3351     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3352   else {
3353     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3354     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3355   }
3356   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3357 }
3358
3359 std::pair<SDValue, SDValue>
3360 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3361                                  SDValue &ARMcc) const {
3362   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3363
3364   SDValue Value, OverflowCmp;
3365   SDValue LHS = Op.getOperand(0);
3366   SDValue RHS = Op.getOperand(1);
3367
3368
3369   // FIXME: We are currently always generating CMPs because we don't support
3370   // generating CMN through the backend. This is not as good as the natural
3371   // CMP case because it causes a register dependency and cannot be folded
3372   // later.
3373
3374   switch (Op.getOpcode()) {
3375   default:
3376     llvm_unreachable("Unknown overflow instruction!");
3377   case ISD::SADDO:
3378     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3379     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3380     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3381     break;
3382   case ISD::UADDO:
3383     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3384     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3385     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3386     break;
3387   case ISD::SSUBO:
3388     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3389     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3390     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3391     break;
3392   case ISD::USUBO:
3393     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3394     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3395     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3396     break;
3397   } // switch (...)
3398
3399   return std::make_pair(Value, OverflowCmp);
3400 }
3401
3402
3403 SDValue
3404 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3405   // Let legalize expand this if it isn't a legal type yet.
3406   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3407     return SDValue();
3408
3409   SDValue Value, OverflowCmp;
3410   SDValue ARMcc;
3411   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3412   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3413   // We use 0 and 1 as false and true values.
3414   SDValue TVal = DAG.getConstant(1, MVT::i32);
3415   SDValue FVal = DAG.getConstant(0, MVT::i32);
3416   EVT VT = Op.getValueType();
3417
3418   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3419                                  ARMcc, CCR, OverflowCmp);
3420
3421   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3422   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3423 }
3424
3425
3426 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3427   SDValue Cond = Op.getOperand(0);
3428   SDValue SelectTrue = Op.getOperand(1);
3429   SDValue SelectFalse = Op.getOperand(2);
3430   SDLoc dl(Op);
3431   unsigned Opc = Cond.getOpcode();
3432
3433   if (Cond.getResNo() == 1 &&
3434       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3435        Opc == ISD::USUBO)) {
3436     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3437       return SDValue();
3438
3439     SDValue Value, OverflowCmp;
3440     SDValue ARMcc;
3441     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3442     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3443     EVT VT = Op.getValueType();
3444
3445     return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3446                    OverflowCmp, DAG);
3447   }
3448
3449   // Convert:
3450   //
3451   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3452   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3453   //
3454   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3455     const ConstantSDNode *CMOVTrue =
3456       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3457     const ConstantSDNode *CMOVFalse =
3458       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3459
3460     if (CMOVTrue && CMOVFalse) {
3461       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3462       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3463
3464       SDValue True;
3465       SDValue False;
3466       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3467         True = SelectTrue;
3468         False = SelectFalse;
3469       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3470         True = SelectFalse;
3471         False = SelectTrue;
3472       }
3473
3474       if (True.getNode() && False.getNode()) {
3475         EVT VT = Op.getValueType();
3476         SDValue ARMcc = Cond.getOperand(2);
3477         SDValue CCR = Cond.getOperand(3);
3478         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3479         assert(True.getValueType() == VT);
3480         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3481       }
3482     }
3483   }
3484
3485   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3486   // undefined bits before doing a full-word comparison with zero.
3487   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3488                      DAG.getConstant(1, Cond.getValueType()));
3489
3490   return DAG.getSelectCC(dl, Cond,
3491                          DAG.getConstant(0, Cond.getValueType()),
3492                          SelectTrue, SelectFalse, ISD::SETNE);
3493 }
3494
3495 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3496   if (CC == ISD::SETNE)
3497     return ISD::SETEQ;
3498   return ISD::getSetCCInverse(CC, true);
3499 }
3500
3501 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3502                                  bool &swpCmpOps, bool &swpVselOps) {
3503   // Start by selecting the GE condition code for opcodes that return true for
3504   // 'equality'
3505   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3506       CC == ISD::SETULE)
3507     CondCode = ARMCC::GE;
3508
3509   // and GT for opcodes that return false for 'equality'.
3510   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3511            CC == ISD::SETULT)
3512     CondCode = ARMCC::GT;
3513
3514   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3515   // to swap the compare operands.
3516   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3517       CC == ISD::SETULT)
3518     swpCmpOps = true;
3519
3520   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3521   // If we have an unordered opcode, we need to swap the operands to the VSEL
3522   // instruction (effectively negating the condition).
3523   //
3524   // This also has the effect of swapping which one of 'less' or 'greater'
3525   // returns true, so we also swap the compare operands. It also switches
3526   // whether we return true for 'equality', so we compensate by picking the
3527   // opposite condition code to our original choice.
3528   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3529       CC == ISD::SETUGT) {
3530     swpCmpOps = !swpCmpOps;
3531     swpVselOps = !swpVselOps;
3532     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3533   }
3534
3535   // 'ordered' is 'anything but unordered', so use the VS condition code and
3536   // swap the VSEL operands.
3537   if (CC == ISD::SETO) {
3538     CondCode = ARMCC::VS;
3539     swpVselOps = true;
3540   }
3541
3542   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3543   // code and swap the VSEL operands.
3544   if (CC == ISD::SETUNE) {
3545     CondCode = ARMCC::EQ;
3546     swpVselOps = true;
3547   }
3548 }
3549
3550 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3551                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3552                                    SDValue Cmp, SelectionDAG &DAG) const {
3553   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3554     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3555                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3556     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3557                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3558
3559     SDValue TrueLow = TrueVal.getValue(0);
3560     SDValue TrueHigh = TrueVal.getValue(1);
3561     SDValue FalseLow = FalseVal.getValue(0);
3562     SDValue FalseHigh = FalseVal.getValue(1);
3563
3564     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3565                               ARMcc, CCR, Cmp);
3566     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3567                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3568
3569     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3570   } else {
3571     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3572                        Cmp);
3573   }
3574 }
3575
3576 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3577   EVT VT = Op.getValueType();
3578   SDValue LHS = Op.getOperand(0);
3579   SDValue RHS = Op.getOperand(1);
3580   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3581   SDValue TrueVal = Op.getOperand(2);
3582   SDValue FalseVal = Op.getOperand(3);
3583   SDLoc dl(Op);
3584
3585   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3586     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3587                                                     dl);
3588
3589     // If softenSetCCOperands only returned one value, we should compare it to
3590     // zero.
3591     if (!RHS.getNode()) {
3592       RHS = DAG.getConstant(0, LHS.getValueType());
3593       CC = ISD::SETNE;
3594     }
3595   }
3596
3597   if (LHS.getValueType() == MVT::i32) {
3598     // Try to generate VSEL on ARMv8.
3599     // The VSEL instruction can't use all the usual ARM condition
3600     // codes: it only has two bits to select the condition code, so it's
3601     // constrained to use only GE, GT, VS and EQ.
3602     //
3603     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3604     // swap the operands of the previous compare instruction (effectively
3605     // inverting the compare condition, swapping 'less' and 'greater') and
3606     // sometimes need to swap the operands to the VSEL (which inverts the
3607     // condition in the sense of firing whenever the previous condition didn't)
3608     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3609                                       TrueVal.getValueType() == MVT::f64)) {
3610       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3611       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3612           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3613         CC = getInverseCCForVSEL(CC);
3614         std::swap(TrueVal, FalseVal);
3615       }
3616     }
3617
3618     SDValue ARMcc;
3619     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3620     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3621     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3622   }
3623
3624   ARMCC::CondCodes CondCode, CondCode2;
3625   FPCCToARMCC(CC, CondCode, CondCode2);
3626
3627   // Try to generate VSEL on ARMv8.
3628   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3629                                     TrueVal.getValueType() == MVT::f64)) {
3630     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3631     // same operands, as follows:
3632     //   c = fcmp [ogt, olt, ugt, ult] a, b
3633     //   select c, a, b
3634     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3635     // handled differently than the original code sequence.
3636     if (getTargetMachine().Options.UnsafeFPMath) {
3637       if (LHS == TrueVal && RHS == FalseVal) {
3638         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3639           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3640         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3641           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3642       } else if (LHS == FalseVal && RHS == TrueVal) {
3643         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3644           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3645         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3646           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3647       }
3648     }
3649
3650     bool swpCmpOps = false;
3651     bool swpVselOps = false;
3652     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3653
3654     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3655         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3656       if (swpCmpOps)
3657         std::swap(LHS, RHS);
3658       if (swpVselOps)
3659         std::swap(TrueVal, FalseVal);
3660     }
3661   }
3662
3663   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3664   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3665   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3666   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3667   if (CondCode2 != ARMCC::AL) {
3668     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3669     // FIXME: Needs another CMP because flag can have but one use.
3670     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3671     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3672   }
3673   return Result;
3674 }
3675
3676 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3677 /// to morph to an integer compare sequence.
3678 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3679                            const ARMSubtarget *Subtarget) {
3680   SDNode *N = Op.getNode();
3681   if (!N->hasOneUse())
3682     // Otherwise it requires moving the value from fp to integer registers.
3683     return false;
3684   if (!N->getNumValues())
3685     return false;
3686   EVT VT = Op.getValueType();
3687   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3688     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3689     // vmrs are very slow, e.g. cortex-a8.
3690     return false;
3691
3692   if (isFloatingPointZero(Op)) {
3693     SeenZero = true;
3694     return true;
3695   }
3696   return ISD::isNormalLoad(N);
3697 }
3698
3699 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3700   if (isFloatingPointZero(Op))
3701     return DAG.getConstant(0, MVT::i32);
3702
3703   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3704     return DAG.getLoad(MVT::i32, SDLoc(Op),
3705                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3706                        Ld->isVolatile(), Ld->isNonTemporal(),
3707                        Ld->isInvariant(), Ld->getAlignment());
3708
3709   llvm_unreachable("Unknown VFP cmp argument!");
3710 }
3711
3712 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3713                            SDValue &RetVal1, SDValue &RetVal2) {
3714   if (isFloatingPointZero(Op)) {
3715     RetVal1 = DAG.getConstant(0, MVT::i32);
3716     RetVal2 = DAG.getConstant(0, MVT::i32);
3717     return;
3718   }
3719
3720   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3721     SDValue Ptr = Ld->getBasePtr();
3722     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3723                           Ld->getChain(), Ptr,
3724                           Ld->getPointerInfo(),
3725                           Ld->isVolatile(), Ld->isNonTemporal(),
3726                           Ld->isInvariant(), Ld->getAlignment());
3727
3728     EVT PtrType = Ptr.getValueType();
3729     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3730     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3731                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3732     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3733                           Ld->getChain(), NewPtr,
3734                           Ld->getPointerInfo().getWithOffset(4),
3735                           Ld->isVolatile(), Ld->isNonTemporal(),
3736                           Ld->isInvariant(), NewAlign);
3737     return;
3738   }
3739
3740   llvm_unreachable("Unknown VFP cmp argument!");
3741 }
3742
3743 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3744 /// f32 and even f64 comparisons to integer ones.
3745 SDValue
3746 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3747   SDValue Chain = Op.getOperand(0);
3748   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3749   SDValue LHS = Op.getOperand(2);
3750   SDValue RHS = Op.getOperand(3);
3751   SDValue Dest = Op.getOperand(4);
3752   SDLoc dl(Op);
3753
3754   bool LHSSeenZero = false;
3755   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3756   bool RHSSeenZero = false;
3757   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3758   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3759     // If unsafe fp math optimization is enabled and there are no other uses of
3760     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3761     // to an integer comparison.
3762     if (CC == ISD::SETOEQ)
3763       CC = ISD::SETEQ;
3764     else if (CC == ISD::SETUNE)
3765       CC = ISD::SETNE;
3766
3767     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3768     SDValue ARMcc;
3769     if (LHS.getValueType() == MVT::f32) {
3770       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3771                         bitcastf32Toi32(LHS, DAG), Mask);
3772       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3773                         bitcastf32Toi32(RHS, DAG), Mask);
3774       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3775       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3776       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3777                          Chain, Dest, ARMcc, CCR, Cmp);
3778     }
3779
3780     SDValue LHS1, LHS2;
3781     SDValue RHS1, RHS2;
3782     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3783     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3784     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3785     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3786     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3787     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3788     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3789     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3790     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3791   }
3792
3793   return SDValue();
3794 }
3795
3796 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3797   SDValue Chain = Op.getOperand(0);
3798   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3799   SDValue LHS = Op.getOperand(2);
3800   SDValue RHS = Op.getOperand(3);
3801   SDValue Dest = Op.getOperand(4);
3802   SDLoc dl(Op);
3803
3804   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3805     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3806                                                     dl);
3807
3808     // If softenSetCCOperands only returned one value, we should compare it to
3809     // zero.
3810     if (!RHS.getNode()) {
3811       RHS = DAG.getConstant(0, LHS.getValueType());
3812       CC = ISD::SETNE;
3813     }
3814   }
3815
3816   if (LHS.getValueType() == MVT::i32) {
3817     SDValue ARMcc;
3818     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3819     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3820     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3821                        Chain, Dest, ARMcc, CCR, Cmp);
3822   }
3823
3824   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3825
3826   if (getTargetMachine().Options.UnsafeFPMath &&
3827       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3828        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3829     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3830     if (Result.getNode())
3831       return Result;
3832   }
3833
3834   ARMCC::CondCodes CondCode, CondCode2;
3835   FPCCToARMCC(CC, CondCode, CondCode2);
3836
3837   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3838   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3839   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3840   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3841   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3842   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3843   if (CondCode2 != ARMCC::AL) {
3844     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3845     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3846     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3847   }
3848   return Res;
3849 }
3850
3851 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3852   SDValue Chain = Op.getOperand(0);
3853   SDValue Table = Op.getOperand(1);
3854   SDValue Index = Op.getOperand(2);
3855   SDLoc dl(Op);
3856
3857   EVT PTy = getPointerTy();
3858   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3859   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3860   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3861   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3862   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3863   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3864   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3865   if (Subtarget->isThumb2()) {
3866     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3867     // which does another jump to the destination. This also makes it easier
3868     // to translate it to TBB / TBH later.
3869     // FIXME: This might not work if the function is extremely large.
3870     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3871                        Addr, Op.getOperand(2), JTI, UId);
3872   }
3873   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3874     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3875                        MachinePointerInfo::getJumpTable(),
3876                        false, false, false, 0);
3877     Chain = Addr.getValue(1);
3878     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3879     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3880   } else {
3881     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3882                        MachinePointerInfo::getJumpTable(),
3883                        false, false, false, 0);
3884     Chain = Addr.getValue(1);
3885     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3886   }
3887 }
3888
3889 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3890   EVT VT = Op.getValueType();
3891   SDLoc dl(Op);
3892
3893   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3894     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3895       return Op;
3896     return DAG.UnrollVectorOp(Op.getNode());
3897   }
3898
3899   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3900          "Invalid type for custom lowering!");
3901   if (VT != MVT::v4i16)
3902     return DAG.UnrollVectorOp(Op.getNode());
3903
3904   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3905   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3906 }
3907
3908 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3909   EVT VT = Op.getValueType();
3910   if (VT.isVector())
3911     return LowerVectorFP_TO_INT(Op, DAG);
3912
3913   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3914     RTLIB::Libcall LC;
3915     if (Op.getOpcode() == ISD::FP_TO_SINT)
3916       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3917                               Op.getValueType());
3918     else
3919       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3920                               Op.getValueType());
3921     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3922                        /*isSigned*/ false, SDLoc(Op)).first;
3923   }
3924
3925   SDLoc dl(Op);
3926   unsigned Opc;
3927
3928   switch (Op.getOpcode()) {
3929   default: llvm_unreachable("Invalid opcode!");
3930   case ISD::FP_TO_SINT:
3931     Opc = ARMISD::FTOSI;
3932     break;
3933   case ISD::FP_TO_UINT:
3934     Opc = ARMISD::FTOUI;
3935     break;
3936   }
3937   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3938   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3939 }
3940
3941 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3942   EVT VT = Op.getValueType();
3943   SDLoc dl(Op);
3944
3945   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3946     if (VT.getVectorElementType() == MVT::f32)
3947       return Op;
3948     return DAG.UnrollVectorOp(Op.getNode());
3949   }
3950
3951   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3952          "Invalid type for custom lowering!");
3953   if (VT != MVT::v4f32)
3954     return DAG.UnrollVectorOp(Op.getNode());
3955
3956   unsigned CastOpc;
3957   unsigned Opc;
3958   switch (Op.getOpcode()) {
3959   default: llvm_unreachable("Invalid opcode!");
3960   case ISD::SINT_TO_FP:
3961     CastOpc = ISD::SIGN_EXTEND;
3962     Opc = ISD::SINT_TO_FP;
3963     break;
3964   case ISD::UINT_TO_FP:
3965     CastOpc = ISD::ZERO_EXTEND;
3966     Opc = ISD::UINT_TO_FP;
3967     break;
3968   }
3969
3970   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3971   return DAG.getNode(Opc, dl, VT, Op);
3972 }
3973
3974 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3975   EVT VT = Op.getValueType();
3976   if (VT.isVector())
3977     return LowerVectorINT_TO_FP(Op, DAG);
3978
3979   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3980     RTLIB::Libcall LC;
3981     if (Op.getOpcode() == ISD::SINT_TO_FP)
3982       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3983                               Op.getValueType());
3984     else
3985       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3986                               Op.getValueType());
3987     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3988                        /*isSigned*/ false, SDLoc(Op)).first;
3989   }
3990
3991   SDLoc dl(Op);
3992   unsigned Opc;
3993
3994   switch (Op.getOpcode()) {
3995   default: llvm_unreachable("Invalid opcode!");
3996   case ISD::SINT_TO_FP:
3997     Opc = ARMISD::SITOF;
3998     break;
3999   case ISD::UINT_TO_FP:
4000     Opc = ARMISD::UITOF;
4001     break;
4002   }
4003
4004   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
4005   return DAG.getNode(Opc, dl, VT, Op);
4006 }
4007
4008 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4009   // Implement fcopysign with a fabs and a conditional fneg.
4010   SDValue Tmp0 = Op.getOperand(0);
4011   SDValue Tmp1 = Op.getOperand(1);
4012   SDLoc dl(Op);
4013   EVT VT = Op.getValueType();
4014   EVT SrcVT = Tmp1.getValueType();
4015   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4016     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4017   bool UseNEON = !InGPR && Subtarget->hasNEON();
4018
4019   if (UseNEON) {
4020     // Use VBSL to copy the sign bit.
4021     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4022     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4023                                DAG.getTargetConstant(EncodedVal, MVT::i32));
4024     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4025     if (VT == MVT::f64)
4026       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4027                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4028                          DAG.getConstant(32, MVT::i32));
4029     else /*if (VT == MVT::f32)*/
4030       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4031     if (SrcVT == MVT::f32) {
4032       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4033       if (VT == MVT::f64)
4034         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4035                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4036                            DAG.getConstant(32, MVT::i32));
4037     } else if (VT == MVT::f32)
4038       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4039                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4040                          DAG.getConstant(32, MVT::i32));
4041     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4042     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4043
4044     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4045                                             MVT::i32);
4046     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4047     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4048                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4049
4050     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4051                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4052                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4053     if (VT == MVT::f32) {
4054       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4055       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4056                         DAG.getConstant(0, MVT::i32));
4057     } else {
4058       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4059     }
4060
4061     return Res;
4062   }
4063
4064   // Bitcast operand 1 to i32.
4065   if (SrcVT == MVT::f64)
4066     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4067                        Tmp1).getValue(1);
4068   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4069
4070   // Or in the signbit with integer operations.
4071   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4072   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4073   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4074   if (VT == MVT::f32) {
4075     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4076                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4077     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4078                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4079   }
4080
4081   // f64: Or the high part with signbit and then combine two parts.
4082   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4083                      Tmp0);
4084   SDValue Lo = Tmp0.getValue(0);
4085   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4086   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4087   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4088 }
4089
4090 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4091   MachineFunction &MF = DAG.getMachineFunction();
4092   MachineFrameInfo *MFI = MF.getFrameInfo();
4093   MFI->setReturnAddressIsTaken(true);
4094
4095   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4096     return SDValue();
4097
4098   EVT VT = Op.getValueType();
4099   SDLoc dl(Op);
4100   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4101   if (Depth) {
4102     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4103     SDValue Offset = DAG.getConstant(4, MVT::i32);
4104     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4105                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4106                        MachinePointerInfo(), false, false, false, 0);
4107   }
4108
4109   // Return LR, which contains the return address. Mark it an implicit live-in.
4110   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4111   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4112 }
4113
4114 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4115   const ARMBaseRegisterInfo &ARI =
4116     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4117   MachineFunction &MF = DAG.getMachineFunction();
4118   MachineFrameInfo *MFI = MF.getFrameInfo();
4119   MFI->setFrameAddressIsTaken(true);
4120
4121   EVT VT = Op.getValueType();
4122   SDLoc dl(Op);  // FIXME probably not meaningful
4123   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4124   unsigned FrameReg = ARI.getFrameRegister(MF);
4125   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4126   while (Depth--)
4127     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4128                             MachinePointerInfo(),
4129                             false, false, false, 0);
4130   return FrameAddr;
4131 }
4132
4133 // FIXME? Maybe this could be a TableGen attribute on some registers and
4134 // this table could be generated automatically from RegInfo.
4135 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4136                                               EVT VT) const {
4137   unsigned Reg = StringSwitch<unsigned>(RegName)
4138                        .Case("sp", ARM::SP)
4139                        .Default(0);
4140   if (Reg)
4141     return Reg;
4142   report_fatal_error("Invalid register name global variable");
4143 }
4144
4145 /// ExpandBITCAST - If the target supports VFP, this function is called to
4146 /// expand a bit convert where either the source or destination type is i64 to
4147 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4148 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4149 /// vectors), since the legalizer won't know what to do with that.
4150 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4151   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4152   SDLoc dl(N);
4153   SDValue Op = N->getOperand(0);
4154
4155   // This function is only supposed to be called for i64 types, either as the
4156   // source or destination of the bit convert.
4157   EVT SrcVT = Op.getValueType();
4158   EVT DstVT = N->getValueType(0);
4159   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4160          "ExpandBITCAST called for non-i64 type");
4161
4162   // Turn i64->f64 into VMOVDRR.
4163   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4164     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4165                              DAG.getConstant(0, MVT::i32));
4166     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4167                              DAG.getConstant(1, MVT::i32));
4168     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4169                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4170   }
4171
4172   // Turn f64->i64 into VMOVRRD.
4173   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4174     SDValue Cvt;
4175     if (TLI.isBigEndian() && SrcVT.isVector() &&
4176         SrcVT.getVectorNumElements() > 1)
4177       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4178                         DAG.getVTList(MVT::i32, MVT::i32),
4179                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4180     else
4181       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4182                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4183     // Merge the pieces into a single i64 value.
4184     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4185   }
4186
4187   return SDValue();
4188 }
4189
4190 /// getZeroVector - Returns a vector of specified type with all zero elements.
4191 /// Zero vectors are used to represent vector negation and in those cases
4192 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4193 /// not support i64 elements, so sometimes the zero vectors will need to be
4194 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4195 /// zero vector.
4196 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4197   assert(VT.isVector() && "Expected a vector type");
4198   // The canonical modified immediate encoding of a zero vector is....0!
4199   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4200   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4201   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4202   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4203 }
4204
4205 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4206 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4207 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4208                                                 SelectionDAG &DAG) const {
4209   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4210   EVT VT = Op.getValueType();
4211   unsigned VTBits = VT.getSizeInBits();
4212   SDLoc dl(Op);
4213   SDValue ShOpLo = Op.getOperand(0);
4214   SDValue ShOpHi = Op.getOperand(1);
4215   SDValue ShAmt  = Op.getOperand(2);
4216   SDValue ARMcc;
4217   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4218
4219   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4220
4221   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4222                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4223   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4224   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4225                                    DAG.getConstant(VTBits, MVT::i32));
4226   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4227   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4228   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4229
4230   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4231   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4232                           ARMcc, DAG, dl);
4233   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4234   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4235                            CCR, Cmp);
4236
4237   SDValue Ops[2] = { Lo, Hi };
4238   return DAG.getMergeValues(Ops, dl);
4239 }
4240
4241 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4242 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4243 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4244                                                SelectionDAG &DAG) const {
4245   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4246   EVT VT = Op.getValueType();
4247   unsigned VTBits = VT.getSizeInBits();
4248   SDLoc dl(Op);
4249   SDValue ShOpLo = Op.getOperand(0);
4250   SDValue ShOpHi = Op.getOperand(1);
4251   SDValue ShAmt  = Op.getOperand(2);
4252   SDValue ARMcc;
4253
4254   assert(Op.getOpcode() == ISD::SHL_PARTS);
4255   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4256                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4257   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4258   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4259                                    DAG.getConstant(VTBits, MVT::i32));
4260   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4261   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4262
4263   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4264   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4265   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4266                           ARMcc, DAG, dl);
4267   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4268   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4269                            CCR, Cmp);
4270
4271   SDValue Ops[2] = { Lo, Hi };
4272   return DAG.getMergeValues(Ops, dl);
4273 }
4274
4275 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4276                                             SelectionDAG &DAG) const {
4277   // The rounding mode is in bits 23:22 of the FPSCR.
4278   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4279   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4280   // so that the shift + and get folded into a bitfield extract.
4281   SDLoc dl(Op);
4282   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4283                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4284                                               MVT::i32));
4285   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4286                                   DAG.getConstant(1U << 22, MVT::i32));
4287   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4288                               DAG.getConstant(22, MVT::i32));
4289   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4290                      DAG.getConstant(3, MVT::i32));
4291 }
4292
4293 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4294                          const ARMSubtarget *ST) {
4295   EVT VT = N->getValueType(0);
4296   SDLoc dl(N);
4297
4298   if (!ST->hasV6T2Ops())
4299     return SDValue();
4300
4301   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4302   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4303 }
4304
4305 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4306 /// for each 16-bit element from operand, repeated.  The basic idea is to
4307 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4308 ///
4309 /// Trace for v4i16:
4310 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4311 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4312 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4313 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4314 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4315 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4316 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4317 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4318 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4319   EVT VT = N->getValueType(0);
4320   SDLoc DL(N);
4321
4322   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4323   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4324   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4325   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4326   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4327   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4328 }
4329
4330 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4331 /// bit-count for each 16-bit element from the operand.  We need slightly
4332 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4333 /// 64/128-bit registers.
4334 ///
4335 /// Trace for v4i16:
4336 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4337 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4338 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4339 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4340 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4341   EVT VT = N->getValueType(0);
4342   SDLoc DL(N);
4343
4344   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4345   if (VT.is64BitVector()) {
4346     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4347     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4348                        DAG.getIntPtrConstant(0));
4349   } else {
4350     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4351                                     BitCounts, DAG.getIntPtrConstant(0));
4352     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4353   }
4354 }
4355
4356 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4357 /// bit-count for each 32-bit element from the operand.  The idea here is
4358 /// to split the vector into 16-bit elements, leverage the 16-bit count
4359 /// routine, and then combine the results.
4360 ///
4361 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4362 /// input    = [v0    v1    ] (vi: 32-bit elements)
4363 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4364 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4365 /// vrev: N0 = [k1 k0 k3 k2 ]
4366 ///            [k0 k1 k2 k3 ]
4367 ///       N1 =+[k1 k0 k3 k2 ]
4368 ///            [k0 k2 k1 k3 ]
4369 ///       N2 =+[k1 k3 k0 k2 ]
4370 ///            [k0    k2    k1    k3    ]
4371 /// Extended =+[k1    k3    k0    k2    ]
4372 ///            [k0    k2    ]
4373 /// Extracted=+[k1    k3    ]
4374 ///
4375 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4376   EVT VT = N->getValueType(0);
4377   SDLoc DL(N);
4378
4379   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4380
4381   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4382   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4383   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4384   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4385   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4386
4387   if (VT.is64BitVector()) {
4388     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4389     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4390                        DAG.getIntPtrConstant(0));
4391   } else {
4392     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4393                                     DAG.getIntPtrConstant(0));
4394     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4395   }
4396 }
4397
4398 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4399                           const ARMSubtarget *ST) {
4400   EVT VT = N->getValueType(0);
4401
4402   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4403   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4404           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4405          "Unexpected type for custom ctpop lowering");
4406
4407   if (VT.getVectorElementType() == MVT::i32)
4408     return lowerCTPOP32BitElements(N, DAG);
4409   else
4410     return lowerCTPOP16BitElements(N, DAG);
4411 }
4412
4413 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4414                           const ARMSubtarget *ST) {
4415   EVT VT = N->getValueType(0);
4416   SDLoc dl(N);
4417
4418   if (!VT.isVector())
4419     return SDValue();
4420
4421   // Lower vector shifts on NEON to use VSHL.
4422   assert(ST->hasNEON() && "unexpected vector shift");
4423
4424   // Left shifts translate directly to the vshiftu intrinsic.
4425   if (N->getOpcode() == ISD::SHL)
4426     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4427                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4428                        N->getOperand(0), N->getOperand(1));
4429
4430   assert((N->getOpcode() == ISD::SRA ||
4431           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4432
4433   // NEON uses the same intrinsics for both left and right shifts.  For
4434   // right shifts, the shift amounts are negative, so negate the vector of
4435   // shift amounts.
4436   EVT ShiftVT = N->getOperand(1).getValueType();
4437   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4438                                      getZeroVector(ShiftVT, DAG, dl),
4439                                      N->getOperand(1));
4440   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4441                              Intrinsic::arm_neon_vshifts :
4442                              Intrinsic::arm_neon_vshiftu);
4443   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4444                      DAG.getConstant(vshiftInt, MVT::i32),
4445                      N->getOperand(0), NegatedCount);
4446 }
4447
4448 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4449                                 const ARMSubtarget *ST) {
4450   EVT VT = N->getValueType(0);
4451   SDLoc dl(N);
4452
4453   // We can get here for a node like i32 = ISD::SHL i32, i64
4454   if (VT != MVT::i64)
4455     return SDValue();
4456
4457   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4458          "Unknown shift to lower!");
4459
4460   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4461   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4462       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4463     return SDValue();
4464
4465   // If we are in thumb mode, we don't have RRX.
4466   if (ST->isThumb1Only()) return SDValue();
4467
4468   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4469   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4470                            DAG.getConstant(0, MVT::i32));
4471   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4472                            DAG.getConstant(1, MVT::i32));
4473
4474   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4475   // captures the result into a carry flag.
4476   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4477   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4478
4479   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4480   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4481
4482   // Merge the pieces into a single i64 value.
4483  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4484 }
4485
4486 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4487   SDValue TmpOp0, TmpOp1;
4488   bool Invert = false;
4489   bool Swap = false;
4490   unsigned Opc = 0;
4491
4492   SDValue Op0 = Op.getOperand(0);
4493   SDValue Op1 = Op.getOperand(1);
4494   SDValue CC = Op.getOperand(2);
4495   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4496   EVT VT = Op.getValueType();
4497   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4498   SDLoc dl(Op);
4499
4500   if (Op1.getValueType().isFloatingPoint()) {
4501     switch (SetCCOpcode) {
4502     default: llvm_unreachable("Illegal FP comparison");
4503     case ISD::SETUNE:
4504     case ISD::SETNE:  Invert = true; // Fallthrough
4505     case ISD::SETOEQ:
4506     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4507     case ISD::SETOLT:
4508     case ISD::SETLT: Swap = true; // Fallthrough
4509     case ISD::SETOGT:
4510     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4511     case ISD::SETOLE:
4512     case ISD::SETLE:  Swap = true; // Fallthrough
4513     case ISD::SETOGE:
4514     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4515     case ISD::SETUGE: Swap = true; // Fallthrough
4516     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4517     case ISD::SETUGT: Swap = true; // Fallthrough
4518     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4519     case ISD::SETUEQ: Invert = true; // Fallthrough
4520     case ISD::SETONE:
4521       // Expand this to (OLT | OGT).
4522       TmpOp0 = Op0;
4523       TmpOp1 = Op1;
4524       Opc = ISD::OR;
4525       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4526       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4527       break;
4528     case ISD::SETUO: Invert = true; // Fallthrough
4529     case ISD::SETO:
4530       // Expand this to (OLT | OGE).
4531       TmpOp0 = Op0;
4532       TmpOp1 = Op1;
4533       Opc = ISD::OR;
4534       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4535       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4536       break;
4537     }
4538   } else {
4539     // Integer comparisons.
4540     switch (SetCCOpcode) {
4541     default: llvm_unreachable("Illegal integer comparison");
4542     case ISD::SETNE:  Invert = true;
4543     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4544     case ISD::SETLT:  Swap = true;
4545     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4546     case ISD::SETLE:  Swap = true;
4547     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4548     case ISD::SETULT: Swap = true;
4549     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4550     case ISD::SETULE: Swap = true;
4551     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4552     }
4553
4554     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4555     if (Opc == ARMISD::VCEQ) {
4556
4557       SDValue AndOp;
4558       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4559         AndOp = Op0;
4560       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4561         AndOp = Op1;
4562
4563       // Ignore bitconvert.
4564       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4565         AndOp = AndOp.getOperand(0);
4566
4567       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4568         Opc = ARMISD::VTST;
4569         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4570         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4571         Invert = !Invert;
4572       }
4573     }
4574   }
4575
4576   if (Swap)
4577     std::swap(Op0, Op1);
4578
4579   // If one of the operands is a constant vector zero, attempt to fold the
4580   // comparison to a specialized compare-against-zero form.
4581   SDValue SingleOp;
4582   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4583     SingleOp = Op0;
4584   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4585     if (Opc == ARMISD::VCGE)
4586       Opc = ARMISD::VCLEZ;
4587     else if (Opc == ARMISD::VCGT)
4588       Opc = ARMISD::VCLTZ;
4589     SingleOp = Op1;
4590   }
4591
4592   SDValue Result;
4593   if (SingleOp.getNode()) {
4594     switch (Opc) {
4595     case ARMISD::VCEQ:
4596       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4597     case ARMISD::VCGE:
4598       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4599     case ARMISD::VCLEZ:
4600       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4601     case ARMISD::VCGT:
4602       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4603     case ARMISD::VCLTZ:
4604       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4605     default:
4606       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4607     }
4608   } else {
4609      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4610   }
4611
4612   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4613
4614   if (Invert)
4615     Result = DAG.getNOT(dl, Result, VT);
4616
4617   return Result;
4618 }
4619
4620 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4621 /// valid vector constant for a NEON instruction with a "modified immediate"
4622 /// operand (e.g., VMOV).  If so, return the encoded value.
4623 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4624                                  unsigned SplatBitSize, SelectionDAG &DAG,
4625                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4626   unsigned OpCmode, Imm;
4627
4628   // SplatBitSize is set to the smallest size that splats the vector, so a
4629   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4630   // immediate instructions others than VMOV do not support the 8-bit encoding
4631   // of a zero vector, and the default encoding of zero is supposed to be the
4632   // 32-bit version.
4633   if (SplatBits == 0)
4634     SplatBitSize = 32;
4635
4636   switch (SplatBitSize) {
4637   case 8:
4638     if (type != VMOVModImm)
4639       return SDValue();
4640     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4641     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4642     OpCmode = 0xe;
4643     Imm = SplatBits;
4644     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4645     break;
4646
4647   case 16:
4648     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4649     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4650     if ((SplatBits & ~0xff) == 0) {
4651       // Value = 0x00nn: Op=x, Cmode=100x.
4652       OpCmode = 0x8;
4653       Imm = SplatBits;
4654       break;
4655     }
4656     if ((SplatBits & ~0xff00) == 0) {
4657       // Value = 0xnn00: Op=x, Cmode=101x.
4658       OpCmode = 0xa;
4659       Imm = SplatBits >> 8;
4660       break;
4661     }
4662     return SDValue();
4663
4664   case 32:
4665     // NEON's 32-bit VMOV supports splat values where:
4666     // * only one byte is nonzero, or
4667     // * the least significant byte is 0xff and the second byte is nonzero, or
4668     // * the least significant 2 bytes are 0xff and the third is nonzero.
4669     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4670     if ((SplatBits & ~0xff) == 0) {
4671       // Value = 0x000000nn: Op=x, Cmode=000x.
4672       OpCmode = 0;
4673       Imm = SplatBits;
4674       break;
4675     }
4676     if ((SplatBits & ~0xff00) == 0) {
4677       // Value = 0x0000nn00: Op=x, Cmode=001x.
4678       OpCmode = 0x2;
4679       Imm = SplatBits >> 8;
4680       break;
4681     }
4682     if ((SplatBits & ~0xff0000) == 0) {
4683       // Value = 0x00nn0000: Op=x, Cmode=010x.
4684       OpCmode = 0x4;
4685       Imm = SplatBits >> 16;
4686       break;
4687     }
4688     if ((SplatBits & ~0xff000000) == 0) {
4689       // Value = 0xnn000000: Op=x, Cmode=011x.
4690       OpCmode = 0x6;
4691       Imm = SplatBits >> 24;
4692       break;
4693     }
4694
4695     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4696     if (type == OtherModImm) return SDValue();
4697
4698     if ((SplatBits & ~0xffff) == 0 &&
4699         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4700       // Value = 0x0000nnff: Op=x, Cmode=1100.
4701       OpCmode = 0xc;
4702       Imm = SplatBits >> 8;
4703       break;
4704     }
4705
4706     if ((SplatBits & ~0xffffff) == 0 &&
4707         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4708       // Value = 0x00nnffff: Op=x, Cmode=1101.
4709       OpCmode = 0xd;
4710       Imm = SplatBits >> 16;
4711       break;
4712     }
4713
4714     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4715     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4716     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4717     // and fall through here to test for a valid 64-bit splat.  But, then the
4718     // caller would also need to check and handle the change in size.
4719     return SDValue();
4720
4721   case 64: {
4722     if (type != VMOVModImm)
4723       return SDValue();
4724     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4725     uint64_t BitMask = 0xff;
4726     uint64_t Val = 0;
4727     unsigned ImmMask = 1;
4728     Imm = 0;
4729     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4730       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4731         Val |= BitMask;
4732         Imm |= ImmMask;
4733       } else if ((SplatBits & BitMask) != 0) {
4734         return SDValue();
4735       }
4736       BitMask <<= 8;
4737       ImmMask <<= 1;
4738     }
4739
4740     if (DAG.getTargetLoweringInfo().isBigEndian())
4741       // swap higher and lower 32 bit word
4742       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4743
4744     // Op=1, Cmode=1110.
4745     OpCmode = 0x1e;
4746     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4747     break;
4748   }
4749
4750   default:
4751     llvm_unreachable("unexpected size for isNEONModifiedImm");
4752   }
4753
4754   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4755   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4756 }
4757
4758 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4759                                            const ARMSubtarget *ST) const {
4760   if (!ST->hasVFP3())
4761     return SDValue();
4762
4763   bool IsDouble = Op.getValueType() == MVT::f64;
4764   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4765
4766   // Use the default (constant pool) lowering for double constants when we have
4767   // an SP-only FPU
4768   if (IsDouble && Subtarget->isFPOnlySP())
4769     return SDValue();
4770
4771   // Try splatting with a VMOV.f32...
4772   APFloat FPVal = CFP->getValueAPF();
4773   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4774
4775   if (ImmVal != -1) {
4776     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4777       // We have code in place to select a valid ConstantFP already, no need to
4778       // do any mangling.
4779       return Op;
4780     }
4781
4782     // It's a float and we are trying to use NEON operations where
4783     // possible. Lower it to a splat followed by an extract.
4784     SDLoc DL(Op);
4785     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4786     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4787                                       NewVal);
4788     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4789                        DAG.getConstant(0, MVT::i32));
4790   }
4791
4792   // The rest of our options are NEON only, make sure that's allowed before
4793   // proceeding..
4794   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4795     return SDValue();
4796
4797   EVT VMovVT;
4798   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4799
4800   // It wouldn't really be worth bothering for doubles except for one very
4801   // important value, which does happen to match: 0.0. So make sure we don't do
4802   // anything stupid.
4803   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4804     return SDValue();
4805
4806   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4807   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4808                                      false, VMOVModImm);
4809   if (NewVal != SDValue()) {
4810     SDLoc DL(Op);
4811     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4812                                       NewVal);
4813     if (IsDouble)
4814       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4815
4816     // It's a float: cast and extract a vector element.
4817     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4818                                        VecConstant);
4819     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4820                        DAG.getConstant(0, MVT::i32));
4821   }
4822
4823   // Finally, try a VMVN.i32
4824   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4825                              false, VMVNModImm);
4826   if (NewVal != SDValue()) {
4827     SDLoc DL(Op);
4828     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4829
4830     if (IsDouble)
4831       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4832
4833     // It's a float: cast and extract a vector element.
4834     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4835                                        VecConstant);
4836     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4837                        DAG.getConstant(0, MVT::i32));
4838   }
4839
4840   return SDValue();
4841 }
4842
4843 // check if an VEXT instruction can handle the shuffle mask when the
4844 // vector sources of the shuffle are the same.
4845 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4846   unsigned NumElts = VT.getVectorNumElements();
4847
4848   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4849   if (M[0] < 0)
4850     return false;
4851
4852   Imm = M[0];
4853
4854   // If this is a VEXT shuffle, the immediate value is the index of the first
4855   // element.  The other shuffle indices must be the successive elements after
4856   // the first one.
4857   unsigned ExpectedElt = Imm;
4858   for (unsigned i = 1; i < NumElts; ++i) {
4859     // Increment the expected index.  If it wraps around, just follow it
4860     // back to index zero and keep going.
4861     ++ExpectedElt;
4862     if (ExpectedElt == NumElts)
4863       ExpectedElt = 0;
4864
4865     if (M[i] < 0) continue; // ignore UNDEF indices
4866     if (ExpectedElt != static_cast<unsigned>(M[i]))
4867       return false;
4868   }
4869
4870   return true;
4871 }
4872
4873
4874 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4875                        bool &ReverseVEXT, unsigned &Imm) {
4876   unsigned NumElts = VT.getVectorNumElements();
4877   ReverseVEXT = false;
4878
4879   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4880   if (M[0] < 0)
4881     return false;
4882
4883   Imm = M[0];
4884
4885   // If this is a VEXT shuffle, the immediate value is the index of the first
4886   // element.  The other shuffle indices must be the successive elements after
4887   // the first one.
4888   unsigned ExpectedElt = Imm;
4889   for (unsigned i = 1; i < NumElts; ++i) {
4890     // Increment the expected index.  If it wraps around, it may still be
4891     // a VEXT but the source vectors must be swapped.
4892     ExpectedElt += 1;
4893     if (ExpectedElt == NumElts * 2) {
4894       ExpectedElt = 0;
4895       ReverseVEXT = true;
4896     }
4897
4898     if (M[i] < 0) continue; // ignore UNDEF indices
4899     if (ExpectedElt != static_cast<unsigned>(M[i]))
4900       return false;
4901   }
4902
4903   // Adjust the index value if the source operands will be swapped.
4904   if (ReverseVEXT)
4905     Imm -= NumElts;
4906
4907   return true;
4908 }
4909
4910 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4911 /// instruction with the specified blocksize.  (The order of the elements
4912 /// within each block of the vector is reversed.)
4913 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4914   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4915          "Only possible block sizes for VREV are: 16, 32, 64");
4916
4917   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4918   if (EltSz == 64)
4919     return false;
4920
4921   unsigned NumElts = VT.getVectorNumElements();
4922   unsigned BlockElts = M[0] + 1;
4923   // If the first shuffle index is UNDEF, be optimistic.
4924   if (M[0] < 0)
4925     BlockElts = BlockSize / EltSz;
4926
4927   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4928     return false;
4929
4930   for (unsigned i = 0; i < NumElts; ++i) {
4931     if (M[i] < 0) continue; // ignore UNDEF indices
4932     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4933       return false;
4934   }
4935
4936   return true;
4937 }
4938
4939 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4940   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4941   // range, then 0 is placed into the resulting vector. So pretty much any mask
4942   // of 8 elements can work here.
4943   return VT == MVT::v8i8 && M.size() == 8;
4944 }
4945
4946 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4947   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4948   if (EltSz == 64)
4949     return false;
4950
4951   unsigned NumElts = VT.getVectorNumElements();
4952   WhichResult = (M[0] == 0 ? 0 : 1);
4953   for (unsigned i = 0; i < NumElts; i += 2) {
4954     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4955         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4956       return false;
4957   }
4958   return true;
4959 }
4960
4961 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4962 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4963 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4964 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4965   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4966   if (EltSz == 64)
4967     return false;
4968
4969   unsigned NumElts = VT.getVectorNumElements();
4970   WhichResult = (M[0] == 0 ? 0 : 1);
4971   for (unsigned i = 0; i < NumElts; i += 2) {
4972     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4973         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4974       return false;
4975   }
4976   return true;
4977 }
4978
4979 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4980   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4981   if (EltSz == 64)
4982     return false;
4983
4984   unsigned NumElts = VT.getVectorNumElements();
4985   WhichResult = (M[0] == 0 ? 0 : 1);
4986   for (unsigned i = 0; i != NumElts; ++i) {
4987     if (M[i] < 0) continue; // ignore UNDEF indices
4988     if ((unsigned) M[i] != 2 * i + WhichResult)
4989       return false;
4990   }
4991
4992   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4993   if (VT.is64BitVector() && EltSz == 32)
4994     return false;
4995
4996   return true;
4997 }
4998
4999 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5000 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5001 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5002 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5003   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5004   if (EltSz == 64)
5005     return false;
5006
5007   unsigned Half = VT.getVectorNumElements() / 2;
5008   WhichResult = (M[0] == 0 ? 0 : 1);
5009   for (unsigned j = 0; j != 2; ++j) {
5010     unsigned Idx = WhichResult;
5011     for (unsigned i = 0; i != Half; ++i) {
5012       int MIdx = M[i + j * Half];
5013       if (MIdx >= 0 && (unsigned) MIdx != Idx)
5014         return false;
5015       Idx += 2;
5016     }
5017   }
5018
5019   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5020   if (VT.is64BitVector() && EltSz == 32)
5021     return false;
5022
5023   return true;
5024 }
5025
5026 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5027   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5028   if (EltSz == 64)
5029     return false;
5030
5031   unsigned NumElts = VT.getVectorNumElements();
5032   WhichResult = (M[0] == 0 ? 0 : 1);
5033   unsigned Idx = WhichResult * NumElts / 2;
5034   for (unsigned i = 0; i != NumElts; i += 2) {
5035     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5036         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5037       return false;
5038     Idx += 1;
5039   }
5040
5041   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5042   if (VT.is64BitVector() && EltSz == 32)
5043     return false;
5044
5045   return true;
5046 }
5047
5048 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5049 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5050 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5051 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5052   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5053   if (EltSz == 64)
5054     return false;
5055
5056   unsigned NumElts = VT.getVectorNumElements();
5057   WhichResult = (M[0] == 0 ? 0 : 1);
5058   unsigned Idx = WhichResult * NumElts / 2;
5059   for (unsigned i = 0; i != NumElts; i += 2) {
5060     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5061         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5062       return false;
5063     Idx += 1;
5064   }
5065
5066   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5067   if (VT.is64BitVector() && EltSz == 32)
5068     return false;
5069
5070   return true;
5071 }
5072
5073 /// \return true if this is a reverse operation on an vector.
5074 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5075   unsigned NumElts = VT.getVectorNumElements();
5076   // Make sure the mask has the right size.
5077   if (NumElts != M.size())
5078       return false;
5079
5080   // Look for <15, ..., 3, -1, 1, 0>.
5081   for (unsigned i = 0; i != NumElts; ++i)
5082     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5083       return false;
5084
5085   return true;
5086 }
5087
5088 // If N is an integer constant that can be moved into a register in one
5089 // instruction, return an SDValue of such a constant (will become a MOV
5090 // instruction).  Otherwise return null.
5091 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5092                                      const ARMSubtarget *ST, SDLoc dl) {
5093   uint64_t Val;
5094   if (!isa<ConstantSDNode>(N))
5095     return SDValue();
5096   Val = cast<ConstantSDNode>(N)->getZExtValue();
5097
5098   if (ST->isThumb1Only()) {
5099     if (Val <= 255 || ~Val <= 255)
5100       return DAG.getConstant(Val, MVT::i32);
5101   } else {
5102     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5103       return DAG.getConstant(Val, MVT::i32);
5104   }
5105   return SDValue();
5106 }
5107
5108 // If this is a case we can't handle, return null and let the default
5109 // expansion code take care of it.
5110 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5111                                              const ARMSubtarget *ST) const {
5112   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5113   SDLoc dl(Op);
5114   EVT VT = Op.getValueType();
5115
5116   APInt SplatBits, SplatUndef;
5117   unsigned SplatBitSize;
5118   bool HasAnyUndefs;
5119   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5120     if (SplatBitSize <= 64) {
5121       // Check if an immediate VMOV works.
5122       EVT VmovVT;
5123       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5124                                       SplatUndef.getZExtValue(), SplatBitSize,
5125                                       DAG, VmovVT, VT.is128BitVector(),
5126                                       VMOVModImm);
5127       if (Val.getNode()) {
5128         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5129         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5130       }
5131
5132       // Try an immediate VMVN.
5133       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5134       Val = isNEONModifiedImm(NegatedImm,
5135                                       SplatUndef.getZExtValue(), SplatBitSize,
5136                                       DAG, VmovVT, VT.is128BitVector(),
5137                                       VMVNModImm);
5138       if (Val.getNode()) {
5139         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5140         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5141       }
5142
5143       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5144       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5145         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5146         if (ImmVal != -1) {
5147           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5148           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5149         }
5150       }
5151     }
5152   }
5153
5154   // Scan through the operands to see if only one value is used.
5155   //
5156   // As an optimisation, even if more than one value is used it may be more
5157   // profitable to splat with one value then change some lanes.
5158   //
5159   // Heuristically we decide to do this if the vector has a "dominant" value,
5160   // defined as splatted to more than half of the lanes.
5161   unsigned NumElts = VT.getVectorNumElements();
5162   bool isOnlyLowElement = true;
5163   bool usesOnlyOneValue = true;
5164   bool hasDominantValue = false;
5165   bool isConstant = true;
5166
5167   // Map of the number of times a particular SDValue appears in the
5168   // element list.
5169   DenseMap<SDValue, unsigned> ValueCounts;
5170   SDValue Value;
5171   for (unsigned i = 0; i < NumElts; ++i) {
5172     SDValue V = Op.getOperand(i);
5173     if (V.getOpcode() == ISD::UNDEF)
5174       continue;
5175     if (i > 0)
5176       isOnlyLowElement = false;
5177     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5178       isConstant = false;
5179
5180     ValueCounts.insert(std::make_pair(V, 0));
5181     unsigned &Count = ValueCounts[V];
5182
5183     // Is this value dominant? (takes up more than half of the lanes)
5184     if (++Count > (NumElts / 2)) {
5185       hasDominantValue = true;
5186       Value = V;
5187     }
5188   }
5189   if (ValueCounts.size() != 1)
5190     usesOnlyOneValue = false;
5191   if (!Value.getNode() && ValueCounts.size() > 0)
5192     Value = ValueCounts.begin()->first;
5193
5194   if (ValueCounts.size() == 0)
5195     return DAG.getUNDEF(VT);
5196
5197   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5198   // Keep going if we are hitting this case.
5199   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5200     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5201
5202   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5203
5204   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5205   // i32 and try again.
5206   if (hasDominantValue && EltSize <= 32) {
5207     if (!isConstant) {
5208       SDValue N;
5209
5210       // If we are VDUPing a value that comes directly from a vector, that will
5211       // cause an unnecessary move to and from a GPR, where instead we could
5212       // just use VDUPLANE. We can only do this if the lane being extracted
5213       // is at a constant index, as the VDUP from lane instructions only have
5214       // constant-index forms.
5215       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5216           isa<ConstantSDNode>(Value->getOperand(1))) {
5217         // We need to create a new undef vector to use for the VDUPLANE if the
5218         // size of the vector from which we get the value is different than the
5219         // size of the vector that we need to create. We will insert the element
5220         // such that the register coalescer will remove unnecessary copies.
5221         if (VT != Value->getOperand(0).getValueType()) {
5222           ConstantSDNode *constIndex;
5223           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5224           assert(constIndex && "The index is not a constant!");
5225           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5226                              VT.getVectorNumElements();
5227           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5228                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5229                         Value, DAG.getConstant(index, MVT::i32)),
5230                            DAG.getConstant(index, MVT::i32));
5231         } else
5232           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5233                         Value->getOperand(0), Value->getOperand(1));
5234       } else
5235         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5236
5237       if (!usesOnlyOneValue) {
5238         // The dominant value was splatted as 'N', but we now have to insert
5239         // all differing elements.
5240         for (unsigned I = 0; I < NumElts; ++I) {
5241           if (Op.getOperand(I) == Value)
5242             continue;
5243           SmallVector<SDValue, 3> Ops;
5244           Ops.push_back(N);
5245           Ops.push_back(Op.getOperand(I));
5246           Ops.push_back(DAG.getConstant(I, MVT::i32));
5247           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5248         }
5249       }
5250       return N;
5251     }
5252     if (VT.getVectorElementType().isFloatingPoint()) {
5253       SmallVector<SDValue, 8> Ops;
5254       for (unsigned i = 0; i < NumElts; ++i)
5255         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5256                                   Op.getOperand(i)));
5257       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5258       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5259       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5260       if (Val.getNode())
5261         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5262     }
5263     if (usesOnlyOneValue) {
5264       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5265       if (isConstant && Val.getNode())
5266         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5267     }
5268   }
5269
5270   // If all elements are constants and the case above didn't get hit, fall back
5271   // to the default expansion, which will generate a load from the constant
5272   // pool.
5273   if (isConstant)
5274     return SDValue();
5275
5276   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5277   if (NumElts >= 4) {
5278     SDValue shuffle = ReconstructShuffle(Op, DAG);
5279     if (shuffle != SDValue())
5280       return shuffle;
5281   }
5282
5283   // Vectors with 32- or 64-bit elements can be built by directly assigning
5284   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5285   // will be legalized.
5286   if (EltSize >= 32) {
5287     // Do the expansion with floating-point types, since that is what the VFP
5288     // registers are defined to use, and since i64 is not legal.
5289     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5290     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5291     SmallVector<SDValue, 8> Ops;
5292     for (unsigned i = 0; i < NumElts; ++i)
5293       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5294     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5295     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5296   }
5297
5298   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5299   // know the default expansion would otherwise fall back on something even
5300   // worse. For a vector with one or two non-undef values, that's
5301   // scalar_to_vector for the elements followed by a shuffle (provided the
5302   // shuffle is valid for the target) and materialization element by element
5303   // on the stack followed by a load for everything else.
5304   if (!isConstant && !usesOnlyOneValue) {
5305     SDValue Vec = DAG.getUNDEF(VT);
5306     for (unsigned i = 0 ; i < NumElts; ++i) {
5307       SDValue V = Op.getOperand(i);
5308       if (V.getOpcode() == ISD::UNDEF)
5309         continue;
5310       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5311       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5312     }
5313     return Vec;
5314   }
5315
5316   return SDValue();
5317 }
5318
5319 // Gather data to see if the operation can be modelled as a
5320 // shuffle in combination with VEXTs.
5321 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5322                                               SelectionDAG &DAG) const {
5323   SDLoc dl(Op);
5324   EVT VT = Op.getValueType();
5325   unsigned NumElts = VT.getVectorNumElements();
5326
5327   SmallVector<SDValue, 2> SourceVecs;
5328   SmallVector<unsigned, 2> MinElts;
5329   SmallVector<unsigned, 2> MaxElts;
5330
5331   for (unsigned i = 0; i < NumElts; ++i) {
5332     SDValue V = Op.getOperand(i);
5333     if (V.getOpcode() == ISD::UNDEF)
5334       continue;
5335     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5336       // A shuffle can only come from building a vector from various
5337       // elements of other vectors.
5338       return SDValue();
5339     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5340                VT.getVectorElementType()) {
5341       // This code doesn't know how to handle shuffles where the vector
5342       // element types do not match (this happens because type legalization
5343       // promotes the return type of EXTRACT_VECTOR_ELT).
5344       // FIXME: It might be appropriate to extend this code to handle
5345       // mismatched types.
5346       return SDValue();
5347     }
5348
5349     // Record this extraction against the appropriate vector if possible...
5350     SDValue SourceVec = V.getOperand(0);
5351     // If the element number isn't a constant, we can't effectively
5352     // analyze what's going on.
5353     if (!isa<ConstantSDNode>(V.getOperand(1)))
5354       return SDValue();
5355     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5356     bool FoundSource = false;
5357     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5358       if (SourceVecs[j] == SourceVec) {
5359         if (MinElts[j] > EltNo)
5360           MinElts[j] = EltNo;
5361         if (MaxElts[j] < EltNo)
5362           MaxElts[j] = EltNo;
5363         FoundSource = true;
5364         break;
5365       }
5366     }
5367
5368     // Or record a new source if not...
5369     if (!FoundSource) {
5370       SourceVecs.push_back(SourceVec);
5371       MinElts.push_back(EltNo);
5372       MaxElts.push_back(EltNo);
5373     }
5374   }
5375
5376   // Currently only do something sane when at most two source vectors
5377   // involved.
5378   if (SourceVecs.size() > 2)
5379     return SDValue();
5380
5381   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5382   int VEXTOffsets[2] = {0, 0};
5383
5384   // This loop extracts the usage patterns of the source vectors
5385   // and prepares appropriate SDValues for a shuffle if possible.
5386   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5387     if (SourceVecs[i].getValueType() == VT) {
5388       // No VEXT necessary
5389       ShuffleSrcs[i] = SourceVecs[i];
5390       VEXTOffsets[i] = 0;
5391       continue;
5392     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5393       // It probably isn't worth padding out a smaller vector just to
5394       // break it down again in a shuffle.
5395       return SDValue();
5396     }
5397
5398     // Since only 64-bit and 128-bit vectors are legal on ARM and
5399     // we've eliminated the other cases...
5400     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5401            "unexpected vector sizes in ReconstructShuffle");
5402
5403     if (MaxElts[i] - MinElts[i] >= NumElts) {
5404       // Span too large for a VEXT to cope
5405       return SDValue();
5406     }
5407
5408     if (MinElts[i] >= NumElts) {
5409       // The extraction can just take the second half
5410       VEXTOffsets[i] = NumElts;
5411       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5412                                    SourceVecs[i],
5413                                    DAG.getIntPtrConstant(NumElts));
5414     } else if (MaxElts[i] < NumElts) {
5415       // The extraction can just take the first half
5416       VEXTOffsets[i] = 0;
5417       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5418                                    SourceVecs[i],
5419                                    DAG.getIntPtrConstant(0));
5420     } else {
5421       // An actual VEXT is needed
5422       VEXTOffsets[i] = MinElts[i];
5423       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5424                                      SourceVecs[i],
5425                                      DAG.getIntPtrConstant(0));
5426       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5427                                      SourceVecs[i],
5428                                      DAG.getIntPtrConstant(NumElts));
5429       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5430                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5431     }
5432   }
5433
5434   SmallVector<int, 8> Mask;
5435
5436   for (unsigned i = 0; i < NumElts; ++i) {
5437     SDValue Entry = Op.getOperand(i);
5438     if (Entry.getOpcode() == ISD::UNDEF) {
5439       Mask.push_back(-1);
5440       continue;
5441     }
5442
5443     SDValue ExtractVec = Entry.getOperand(0);
5444     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5445                                           .getOperand(1))->getSExtValue();
5446     if (ExtractVec == SourceVecs[0]) {
5447       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5448     } else {
5449       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5450     }
5451   }
5452
5453   // Final check before we try to produce nonsense...
5454   if (isShuffleMaskLegal(Mask, VT))
5455     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5456                                 &Mask[0]);
5457
5458   return SDValue();
5459 }
5460
5461 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5462 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5463 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5464 /// are assumed to be legal.
5465 bool
5466 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5467                                       EVT VT) const {
5468   if (VT.getVectorNumElements() == 4 &&
5469       (VT.is128BitVector() || VT.is64BitVector())) {
5470     unsigned PFIndexes[4];
5471     for (unsigned i = 0; i != 4; ++i) {
5472       if (M[i] < 0)
5473         PFIndexes[i] = 8;
5474       else
5475         PFIndexes[i] = M[i];
5476     }
5477
5478     // Compute the index in the perfect shuffle table.
5479     unsigned PFTableIndex =
5480       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5481     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5482     unsigned Cost = (PFEntry >> 30);
5483
5484     if (Cost <= 4)
5485       return true;
5486   }
5487
5488   bool ReverseVEXT;
5489   unsigned Imm, WhichResult;
5490
5491   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5492   return (EltSize >= 32 ||
5493           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5494           isVREVMask(M, VT, 64) ||
5495           isVREVMask(M, VT, 32) ||
5496           isVREVMask(M, VT, 16) ||
5497           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5498           isVTBLMask(M, VT) ||
5499           isVTRNMask(M, VT, WhichResult) ||
5500           isVUZPMask(M, VT, WhichResult) ||
5501           isVZIPMask(M, VT, WhichResult) ||
5502           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5503           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5504           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5505           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5506 }
5507
5508 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5509 /// the specified operations to build the shuffle.
5510 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5511                                       SDValue RHS, SelectionDAG &DAG,
5512                                       SDLoc dl) {
5513   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5514   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5515   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5516
5517   enum {
5518     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5519     OP_VREV,
5520     OP_VDUP0,
5521     OP_VDUP1,
5522     OP_VDUP2,
5523     OP_VDUP3,
5524     OP_VEXT1,
5525     OP_VEXT2,
5526     OP_VEXT3,
5527     OP_VUZPL, // VUZP, left result
5528     OP_VUZPR, // VUZP, right result
5529     OP_VZIPL, // VZIP, left result
5530     OP_VZIPR, // VZIP, right result
5531     OP_VTRNL, // VTRN, left result
5532     OP_VTRNR  // VTRN, right result
5533   };
5534
5535   if (OpNum == OP_COPY) {
5536     if (LHSID == (1*9+2)*9+3) return LHS;
5537     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5538     return RHS;
5539   }
5540
5541   SDValue OpLHS, OpRHS;
5542   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5543   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5544   EVT VT = OpLHS.getValueType();
5545
5546   switch (OpNum) {
5547   default: llvm_unreachable("Unknown shuffle opcode!");
5548   case OP_VREV:
5549     // VREV divides the vector in half and swaps within the half.
5550     if (VT.getVectorElementType() == MVT::i32 ||
5551         VT.getVectorElementType() == MVT::f32)
5552       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5553     // vrev <4 x i16> -> VREV32
5554     if (VT.getVectorElementType() == MVT::i16)
5555       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5556     // vrev <4 x i8> -> VREV16
5557     assert(VT.getVectorElementType() == MVT::i8);
5558     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5559   case OP_VDUP0:
5560   case OP_VDUP1:
5561   case OP_VDUP2:
5562   case OP_VDUP3:
5563     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5564                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5565   case OP_VEXT1:
5566   case OP_VEXT2:
5567   case OP_VEXT3:
5568     return DAG.getNode(ARMISD::VEXT, dl, VT,
5569                        OpLHS, OpRHS,
5570                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5571   case OP_VUZPL:
5572   case OP_VUZPR:
5573     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5574                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5575   case OP_VZIPL:
5576   case OP_VZIPR:
5577     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5578                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5579   case OP_VTRNL:
5580   case OP_VTRNR:
5581     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5582                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5583   }
5584 }
5585
5586 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5587                                        ArrayRef<int> ShuffleMask,
5588                                        SelectionDAG &DAG) {
5589   // Check to see if we can use the VTBL instruction.
5590   SDValue V1 = Op.getOperand(0);
5591   SDValue V2 = Op.getOperand(1);
5592   SDLoc DL(Op);
5593
5594   SmallVector<SDValue, 8> VTBLMask;
5595   for (ArrayRef<int>::iterator
5596          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5597     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5598
5599   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5600     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5601                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5602
5603   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5604                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5605 }
5606
5607 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5608                                                       SelectionDAG &DAG) {
5609   SDLoc DL(Op);
5610   SDValue OpLHS = Op.getOperand(0);
5611   EVT VT = OpLHS.getValueType();
5612
5613   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5614          "Expect an v8i16/v16i8 type");
5615   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5616   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5617   // extract the first 8 bytes into the top double word and the last 8 bytes
5618   // into the bottom double word. The v8i16 case is similar.
5619   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5620   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5621                      DAG.getConstant(ExtractNum, MVT::i32));
5622 }
5623
5624 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5625   SDValue V1 = Op.getOperand(0);
5626   SDValue V2 = Op.getOperand(1);
5627   SDLoc dl(Op);
5628   EVT VT = Op.getValueType();
5629   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5630
5631   // Convert shuffles that are directly supported on NEON to target-specific
5632   // DAG nodes, instead of keeping them as shuffles and matching them again
5633   // during code selection.  This is more efficient and avoids the possibility
5634   // of inconsistencies between legalization and selection.
5635   // FIXME: floating-point vectors should be canonicalized to integer vectors
5636   // of the same time so that they get CSEd properly.
5637   ArrayRef<int> ShuffleMask = SVN->getMask();
5638
5639   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5640   if (EltSize <= 32) {
5641     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5642       int Lane = SVN->getSplatIndex();
5643       // If this is undef splat, generate it via "just" vdup, if possible.
5644       if (Lane == -1) Lane = 0;
5645
5646       // Test if V1 is a SCALAR_TO_VECTOR.
5647       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5648         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5649       }
5650       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5651       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5652       // reaches it).
5653       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5654           !isa<ConstantSDNode>(V1.getOperand(0))) {
5655         bool IsScalarToVector = true;
5656         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5657           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5658             IsScalarToVector = false;
5659             break;
5660           }
5661         if (IsScalarToVector)
5662           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5663       }
5664       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5665                          DAG.getConstant(Lane, MVT::i32));
5666     }
5667
5668     bool ReverseVEXT;
5669     unsigned Imm;
5670     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5671       if (ReverseVEXT)
5672         std::swap(V1, V2);
5673       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5674                          DAG.getConstant(Imm, MVT::i32));
5675     }
5676
5677     if (isVREVMask(ShuffleMask, VT, 64))
5678       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5679     if (isVREVMask(ShuffleMask, VT, 32))
5680       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5681     if (isVREVMask(ShuffleMask, VT, 16))
5682       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5683
5684     if (V2->getOpcode() == ISD::UNDEF &&
5685         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5686       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5687                          DAG.getConstant(Imm, MVT::i32));
5688     }
5689
5690     // Check for Neon shuffles that modify both input vectors in place.
5691     // If both results are used, i.e., if there are two shuffles with the same
5692     // source operands and with masks corresponding to both results of one of
5693     // these operations, DAG memoization will ensure that a single node is
5694     // used for both shuffles.
5695     unsigned WhichResult;
5696     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5697       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5698                          V1, V2).getValue(WhichResult);
5699     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5700       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5701                          V1, V2).getValue(WhichResult);
5702     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5703       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5704                          V1, V2).getValue(WhichResult);
5705
5706     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5707       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5708                          V1, V1).getValue(WhichResult);
5709     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5710       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5711                          V1, V1).getValue(WhichResult);
5712     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5713       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5714                          V1, V1).getValue(WhichResult);
5715   }
5716
5717   // If the shuffle is not directly supported and it has 4 elements, use
5718   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5719   unsigned NumElts = VT.getVectorNumElements();
5720   if (NumElts == 4) {
5721     unsigned PFIndexes[4];
5722     for (unsigned i = 0; i != 4; ++i) {
5723       if (ShuffleMask[i] < 0)
5724         PFIndexes[i] = 8;
5725       else
5726         PFIndexes[i] = ShuffleMask[i];
5727     }
5728
5729     // Compute the index in the perfect shuffle table.
5730     unsigned PFTableIndex =
5731       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5732     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5733     unsigned Cost = (PFEntry >> 30);
5734
5735     if (Cost <= 4)
5736       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5737   }
5738
5739   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5740   if (EltSize >= 32) {
5741     // Do the expansion with floating-point types, since that is what the VFP
5742     // registers are defined to use, and since i64 is not legal.
5743     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5744     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5745     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5746     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5747     SmallVector<SDValue, 8> Ops;
5748     for (unsigned i = 0; i < NumElts; ++i) {
5749       if (ShuffleMask[i] < 0)
5750         Ops.push_back(DAG.getUNDEF(EltVT));
5751       else
5752         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5753                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5754                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5755                                                   MVT::i32)));
5756     }
5757     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5758     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5759   }
5760
5761   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5762     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5763
5764   if (VT == MVT::v8i8) {
5765     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5766     if (NewOp.getNode())
5767       return NewOp;
5768   }
5769
5770   return SDValue();
5771 }
5772
5773 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5774   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5775   SDValue Lane = Op.getOperand(2);
5776   if (!isa<ConstantSDNode>(Lane))
5777     return SDValue();
5778
5779   return Op;
5780 }
5781
5782 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5783   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5784   SDValue Lane = Op.getOperand(1);
5785   if (!isa<ConstantSDNode>(Lane))
5786     return SDValue();
5787
5788   SDValue Vec = Op.getOperand(0);
5789   if (Op.getValueType() == MVT::i32 &&
5790       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5791     SDLoc dl(Op);
5792     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5793   }
5794
5795   return Op;
5796 }
5797
5798 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5799   // The only time a CONCAT_VECTORS operation can have legal types is when
5800   // two 64-bit vectors are concatenated to a 128-bit vector.
5801   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5802          "unexpected CONCAT_VECTORS");
5803   SDLoc dl(Op);
5804   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5805   SDValue Op0 = Op.getOperand(0);
5806   SDValue Op1 = Op.getOperand(1);
5807   if (Op0.getOpcode() != ISD::UNDEF)
5808     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5809                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5810                       DAG.getIntPtrConstant(0));
5811   if (Op1.getOpcode() != ISD::UNDEF)
5812     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5813                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5814                       DAG.getIntPtrConstant(1));
5815   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5816 }
5817
5818 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5819 /// element has been zero/sign-extended, depending on the isSigned parameter,
5820 /// from an integer type half its size.
5821 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5822                                    bool isSigned) {
5823   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5824   EVT VT = N->getValueType(0);
5825   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5826     SDNode *BVN = N->getOperand(0).getNode();
5827     if (BVN->getValueType(0) != MVT::v4i32 ||
5828         BVN->getOpcode() != ISD::BUILD_VECTOR)
5829       return false;
5830     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5831     unsigned HiElt = 1 - LoElt;
5832     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5833     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5834     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5835     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5836     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5837       return false;
5838     if (isSigned) {
5839       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5840           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5841         return true;
5842     } else {
5843       if (Hi0->isNullValue() && Hi1->isNullValue())
5844         return true;
5845     }
5846     return false;
5847   }
5848
5849   if (N->getOpcode() != ISD::BUILD_VECTOR)
5850     return false;
5851
5852   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5853     SDNode *Elt = N->getOperand(i).getNode();
5854     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5855       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5856       unsigned HalfSize = EltSize / 2;
5857       if (isSigned) {
5858         if (!isIntN(HalfSize, C->getSExtValue()))
5859           return false;
5860       } else {
5861         if (!isUIntN(HalfSize, C->getZExtValue()))
5862           return false;
5863       }
5864       continue;
5865     }
5866     return false;
5867   }
5868
5869   return true;
5870 }
5871
5872 /// isSignExtended - Check if a node is a vector value that is sign-extended
5873 /// or a constant BUILD_VECTOR with sign-extended elements.
5874 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5875   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5876     return true;
5877   if (isExtendedBUILD_VECTOR(N, DAG, true))
5878     return true;
5879   return false;
5880 }
5881
5882 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5883 /// or a constant BUILD_VECTOR with zero-extended elements.
5884 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5885   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5886     return true;
5887   if (isExtendedBUILD_VECTOR(N, DAG, false))
5888     return true;
5889   return false;
5890 }
5891
5892 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5893   if (OrigVT.getSizeInBits() >= 64)
5894     return OrigVT;
5895
5896   assert(OrigVT.isSimple() && "Expecting a simple value type");
5897
5898   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5899   switch (OrigSimpleTy) {
5900   default: llvm_unreachable("Unexpected Vector Type");
5901   case MVT::v2i8:
5902   case MVT::v2i16:
5903      return MVT::v2i32;
5904   case MVT::v4i8:
5905     return  MVT::v4i16;
5906   }
5907 }
5908
5909 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5910 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5911 /// We insert the required extension here to get the vector to fill a D register.
5912 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5913                                             const EVT &OrigTy,
5914                                             const EVT &ExtTy,
5915                                             unsigned ExtOpcode) {
5916   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5917   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5918   // 64-bits we need to insert a new extension so that it will be 64-bits.
5919   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5920   if (OrigTy.getSizeInBits() >= 64)
5921     return N;
5922
5923   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5924   EVT NewVT = getExtensionTo64Bits(OrigTy);
5925
5926   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5927 }
5928
5929 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5930 /// does not do any sign/zero extension. If the original vector is less
5931 /// than 64 bits, an appropriate extension will be added after the load to
5932 /// reach a total size of 64 bits. We have to add the extension separately
5933 /// because ARM does not have a sign/zero extending load for vectors.
5934 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5935   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5936
5937   // The load already has the right type.
5938   if (ExtendedTy == LD->getMemoryVT())
5939     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5940                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5941                 LD->isNonTemporal(), LD->isInvariant(),
5942                 LD->getAlignment());
5943
5944   // We need to create a zextload/sextload. We cannot just create a load
5945   // followed by a zext/zext node because LowerMUL is also run during normal
5946   // operation legalization where we can't create illegal types.
5947   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5948                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5949                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5950                         LD->isNonTemporal(), LD->getAlignment());
5951 }
5952
5953 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5954 /// extending load, or BUILD_VECTOR with extended elements, return the
5955 /// unextended value. The unextended vector should be 64 bits so that it can
5956 /// be used as an operand to a VMULL instruction. If the original vector size
5957 /// before extension is less than 64 bits we add a an extension to resize
5958 /// the vector to 64 bits.
5959 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5960   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5961     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5962                                         N->getOperand(0)->getValueType(0),
5963                                         N->getValueType(0),
5964                                         N->getOpcode());
5965
5966   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5967     return SkipLoadExtensionForVMULL(LD, DAG);
5968
5969   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5970   // have been legalized as a BITCAST from v4i32.
5971   if (N->getOpcode() == ISD::BITCAST) {
5972     SDNode *BVN = N->getOperand(0).getNode();
5973     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5974            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5975     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5976     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5977                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5978   }
5979   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5980   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5981   EVT VT = N->getValueType(0);
5982   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5983   unsigned NumElts = VT.getVectorNumElements();
5984   MVT TruncVT = MVT::getIntegerVT(EltSize);
5985   SmallVector<SDValue, 8> Ops;
5986   for (unsigned i = 0; i != NumElts; ++i) {
5987     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5988     const APInt &CInt = C->getAPIntValue();
5989     // Element types smaller than 32 bits are not legal, so use i32 elements.
5990     // The values are implicitly truncated so sext vs. zext doesn't matter.
5991     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5992   }
5993   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5994                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5995 }
5996
5997 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5998   unsigned Opcode = N->getOpcode();
5999   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6000     SDNode *N0 = N->getOperand(0).getNode();
6001     SDNode *N1 = N->getOperand(1).getNode();
6002     return N0->hasOneUse() && N1->hasOneUse() &&
6003       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6004   }
6005   return false;
6006 }
6007
6008 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6009   unsigned Opcode = N->getOpcode();
6010   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6011     SDNode *N0 = N->getOperand(0).getNode();
6012     SDNode *N1 = N->getOperand(1).getNode();
6013     return N0->hasOneUse() && N1->hasOneUse() &&
6014       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6015   }
6016   return false;
6017 }
6018
6019 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6020   // Multiplications are only custom-lowered for 128-bit vectors so that
6021   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6022   EVT VT = Op.getValueType();
6023   assert(VT.is128BitVector() && VT.isInteger() &&
6024          "unexpected type for custom-lowering ISD::MUL");
6025   SDNode *N0 = Op.getOperand(0).getNode();
6026   SDNode *N1 = Op.getOperand(1).getNode();
6027   unsigned NewOpc = 0;
6028   bool isMLA = false;
6029   bool isN0SExt = isSignExtended(N0, DAG);
6030   bool isN1SExt = isSignExtended(N1, DAG);
6031   if (isN0SExt && isN1SExt)
6032     NewOpc = ARMISD::VMULLs;
6033   else {
6034     bool isN0ZExt = isZeroExtended(N0, DAG);
6035     bool isN1ZExt = isZeroExtended(N1, DAG);
6036     if (isN0ZExt && isN1ZExt)
6037       NewOpc = ARMISD::VMULLu;
6038     else if (isN1SExt || isN1ZExt) {
6039       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6040       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6041       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6042         NewOpc = ARMISD::VMULLs;
6043         isMLA = true;
6044       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6045         NewOpc = ARMISD::VMULLu;
6046         isMLA = true;
6047       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6048         std::swap(N0, N1);
6049         NewOpc = ARMISD::VMULLu;
6050         isMLA = true;
6051       }
6052     }
6053
6054     if (!NewOpc) {
6055       if (VT == MVT::v2i64)
6056         // Fall through to expand this.  It is not legal.
6057         return SDValue();
6058       else
6059         // Other vector multiplications are legal.
6060         return Op;
6061     }
6062   }
6063
6064   // Legalize to a VMULL instruction.
6065   SDLoc DL(Op);
6066   SDValue Op0;
6067   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6068   if (!isMLA) {
6069     Op0 = SkipExtensionForVMULL(N0, DAG);
6070     assert(Op0.getValueType().is64BitVector() &&
6071            Op1.getValueType().is64BitVector() &&
6072            "unexpected types for extended operands to VMULL");
6073     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6074   }
6075
6076   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6077   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6078   //   vmull q0, d4, d6
6079   //   vmlal q0, d5, d6
6080   // is faster than
6081   //   vaddl q0, d4, d5
6082   //   vmovl q1, d6
6083   //   vmul  q0, q0, q1
6084   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6085   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6086   EVT Op1VT = Op1.getValueType();
6087   return DAG.getNode(N0->getOpcode(), DL, VT,
6088                      DAG.getNode(NewOpc, DL, VT,
6089                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6090                      DAG.getNode(NewOpc, DL, VT,
6091                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6092 }
6093
6094 static SDValue
6095 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6096   // Convert to float
6097   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6098   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6099   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6100   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6101   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6102   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6103   // Get reciprocal estimate.
6104   // float4 recip = vrecpeq_f32(yf);
6105   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6106                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
6107   // Because char has a smaller range than uchar, we can actually get away
6108   // without any newton steps.  This requires that we use a weird bias
6109   // of 0xb000, however (again, this has been exhaustively tested).
6110   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6111   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6112   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6113   Y = DAG.getConstant(0xb000, MVT::i32);
6114   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6115   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6116   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6117   // Convert back to short.
6118   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6119   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6120   return X;
6121 }
6122
6123 static SDValue
6124 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6125   SDValue N2;
6126   // Convert to float.
6127   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6128   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6129   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6130   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6131   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6132   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6133
6134   // Use reciprocal estimate and one refinement step.
6135   // float4 recip = vrecpeq_f32(yf);
6136   // recip *= vrecpsq_f32(yf, recip);
6137   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6138                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6139   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6140                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6141                    N1, N2);
6142   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6143   // Because short has a smaller range than ushort, we can actually get away
6144   // with only a single newton step.  This requires that we use a weird bias
6145   // of 89, however (again, this has been exhaustively tested).
6146   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6147   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6148   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6149   N1 = DAG.getConstant(0x89, MVT::i32);
6150   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6151   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6152   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6153   // Convert back to integer and return.
6154   // return vmovn_s32(vcvt_s32_f32(result));
6155   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6156   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6157   return N0;
6158 }
6159
6160 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6161   EVT VT = Op.getValueType();
6162   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6163          "unexpected type for custom-lowering ISD::SDIV");
6164
6165   SDLoc dl(Op);
6166   SDValue N0 = Op.getOperand(0);
6167   SDValue N1 = Op.getOperand(1);
6168   SDValue N2, N3;
6169
6170   if (VT == MVT::v8i8) {
6171     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6172     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6173
6174     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6175                      DAG.getIntPtrConstant(4));
6176     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6177                      DAG.getIntPtrConstant(4));
6178     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6179                      DAG.getIntPtrConstant(0));
6180     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6181                      DAG.getIntPtrConstant(0));
6182
6183     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6184     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6185
6186     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6187     N0 = LowerCONCAT_VECTORS(N0, DAG);
6188
6189     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6190     return N0;
6191   }
6192   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6193 }
6194
6195 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6196   EVT VT = Op.getValueType();
6197   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6198          "unexpected type for custom-lowering ISD::UDIV");
6199
6200   SDLoc dl(Op);
6201   SDValue N0 = Op.getOperand(0);
6202   SDValue N1 = Op.getOperand(1);
6203   SDValue N2, N3;
6204
6205   if (VT == MVT::v8i8) {
6206     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6207     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6208
6209     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6210                      DAG.getIntPtrConstant(4));
6211     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6212                      DAG.getIntPtrConstant(4));
6213     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6214                      DAG.getIntPtrConstant(0));
6215     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6216                      DAG.getIntPtrConstant(0));
6217
6218     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6219     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6220
6221     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6222     N0 = LowerCONCAT_VECTORS(N0, DAG);
6223
6224     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6225                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6226                      N0);
6227     return N0;
6228   }
6229
6230   // v4i16 sdiv ... Convert to float.
6231   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6232   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6233   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6234   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6235   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6236   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6237
6238   // Use reciprocal estimate and two refinement steps.
6239   // float4 recip = vrecpeq_f32(yf);
6240   // recip *= vrecpsq_f32(yf, recip);
6241   // recip *= vrecpsq_f32(yf, recip);
6242   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6243                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6244   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6245                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6246                    BN1, N2);
6247   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6248   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6249                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6250                    BN1, N2);
6251   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6252   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6253   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6254   // and that it will never cause us to return an answer too large).
6255   // float4 result = as_float4(as_int4(xf*recip) + 2);
6256   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6257   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6258   N1 = DAG.getConstant(2, MVT::i32);
6259   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6260   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6261   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6262   // Convert back to integer and return.
6263   // return vmovn_u32(vcvt_s32_f32(result));
6264   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6265   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6266   return N0;
6267 }
6268
6269 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6270   EVT VT = Op.getNode()->getValueType(0);
6271   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6272
6273   unsigned Opc;
6274   bool ExtraOp = false;
6275   switch (Op.getOpcode()) {
6276   default: llvm_unreachable("Invalid code");
6277   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6278   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6279   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6280   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6281   }
6282
6283   if (!ExtraOp)
6284     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6285                        Op.getOperand(1));
6286   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6287                      Op.getOperand(1), Op.getOperand(2));
6288 }
6289
6290 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6291   assert(Subtarget->isTargetDarwin());
6292
6293   // For iOS, we want to call an alternative entry point: __sincos_stret,
6294   // return values are passed via sret.
6295   SDLoc dl(Op);
6296   SDValue Arg = Op.getOperand(0);
6297   EVT ArgVT = Arg.getValueType();
6298   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6299
6300   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6301   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6302
6303   // Pair of floats / doubles used to pass the result.
6304   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6305
6306   // Create stack object for sret.
6307   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6308   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6309   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6310   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6311
6312   ArgListTy Args;
6313   ArgListEntry Entry;
6314
6315   Entry.Node = SRet;
6316   Entry.Ty = RetTy->getPointerTo();
6317   Entry.isSExt = false;
6318   Entry.isZExt = false;
6319   Entry.isSRet = true;
6320   Args.push_back(Entry);
6321
6322   Entry.Node = Arg;
6323   Entry.Ty = ArgTy;
6324   Entry.isSExt = false;
6325   Entry.isZExt = false;
6326   Args.push_back(Entry);
6327
6328   const char *LibcallName  = (ArgVT == MVT::f64)
6329   ? "__sincos_stret" : "__sincosf_stret";
6330   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6331
6332   TargetLowering::CallLoweringInfo CLI(DAG);
6333   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6334     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6335                std::move(Args), 0)
6336     .setDiscardResult();
6337
6338   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6339
6340   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6341                                 MachinePointerInfo(), false, false, false, 0);
6342
6343   // Address of cos field.
6344   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6345                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6346   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6347                                 MachinePointerInfo(), false, false, false, 0);
6348
6349   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6350   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6351                      LoadSin.getValue(0), LoadCos.getValue(0));
6352 }
6353
6354 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6355   // Monotonic load/store is legal for all targets
6356   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6357     return Op;
6358
6359   // Acquire/Release load/store is not legal for targets without a
6360   // dmb or equivalent available.
6361   return SDValue();
6362 }
6363
6364 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6365                                     SmallVectorImpl<SDValue> &Results,
6366                                     SelectionDAG &DAG,
6367                                     const ARMSubtarget *Subtarget) {
6368   SDLoc DL(N);
6369   SDValue Cycles32, OutChain;
6370
6371   if (Subtarget->hasPerfMon()) {
6372     // Under Power Management extensions, the cycle-count is:
6373     //    mrc p15, #0, <Rt>, c9, c13, #0
6374     SDValue Ops[] = { N->getOperand(0), // Chain
6375                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6376                       DAG.getConstant(15, MVT::i32),
6377                       DAG.getConstant(0, MVT::i32),
6378                       DAG.getConstant(9, MVT::i32),
6379                       DAG.getConstant(13, MVT::i32),
6380                       DAG.getConstant(0, MVT::i32)
6381     };
6382
6383     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6384                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6385     OutChain = Cycles32.getValue(1);
6386   } else {
6387     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6388     // there are older ARM CPUs that have implementation-specific ways of
6389     // obtaining this information (FIXME!).
6390     Cycles32 = DAG.getConstant(0, MVT::i32);
6391     OutChain = DAG.getEntryNode();
6392   }
6393
6394
6395   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6396                                  Cycles32, DAG.getConstant(0, MVT::i32));
6397   Results.push_back(Cycles64);
6398   Results.push_back(OutChain);
6399 }
6400
6401 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6402   switch (Op.getOpcode()) {
6403   default: llvm_unreachable("Don't know how to custom lower this!");
6404   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6405   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6406   case ISD::GlobalAddress:
6407     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6408     default: llvm_unreachable("unknown object format");
6409     case Triple::COFF:
6410       return LowerGlobalAddressWindows(Op, DAG);
6411     case Triple::ELF:
6412       return LowerGlobalAddressELF(Op, DAG);
6413     case Triple::MachO:
6414       return LowerGlobalAddressDarwin(Op, DAG);
6415     }
6416   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6417   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6418   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6419   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6420   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6421   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6422   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6423   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6424   case ISD::SINT_TO_FP:
6425   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6426   case ISD::FP_TO_SINT:
6427   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6428   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6429   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6430   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6431   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6432   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6433   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6434   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6435                                                                Subtarget);
6436   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6437   case ISD::SHL:
6438   case ISD::SRL:
6439   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6440   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6441   case ISD::SRL_PARTS:
6442   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6443   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6444   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6445   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6446   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6447   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6448   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6449   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6450   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6451   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6452   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6453   case ISD::MUL:           return LowerMUL(Op, DAG);
6454   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6455   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6456   case ISD::ADDC:
6457   case ISD::ADDE:
6458   case ISD::SUBC:
6459   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6460   case ISD::SADDO:
6461   case ISD::UADDO:
6462   case ISD::SSUBO:
6463   case ISD::USUBO:
6464     return LowerXALUO(Op, DAG);
6465   case ISD::ATOMIC_LOAD:
6466   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6467   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6468   case ISD::SDIVREM:
6469   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6470   case ISD::DYNAMIC_STACKALLOC:
6471     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6472       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6473     llvm_unreachable("Don't know how to custom lower this!");
6474   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6475   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6476   }
6477 }
6478
6479 /// ReplaceNodeResults - Replace the results of node with an illegal result
6480 /// type with new values built out of custom code.
6481 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6482                                            SmallVectorImpl<SDValue>&Results,
6483                                            SelectionDAG &DAG) const {
6484   SDValue Res;
6485   switch (N->getOpcode()) {
6486   default:
6487     llvm_unreachable("Don't know how to custom expand this!");
6488   case ISD::BITCAST:
6489     Res = ExpandBITCAST(N, DAG);
6490     break;
6491   case ISD::SRL:
6492   case ISD::SRA:
6493     Res = Expand64BitShift(N, DAG, Subtarget);
6494     break;
6495   case ISD::READCYCLECOUNTER:
6496     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6497     return;
6498   }
6499   if (Res.getNode())
6500     Results.push_back(Res);
6501 }
6502
6503 //===----------------------------------------------------------------------===//
6504 //                           ARM Scheduler Hooks
6505 //===----------------------------------------------------------------------===//
6506
6507 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6508 /// registers the function context.
6509 void ARMTargetLowering::
6510 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6511                        MachineBasicBlock *DispatchBB, int FI) const {
6512   const TargetInstrInfo *TII =
6513       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6514   DebugLoc dl = MI->getDebugLoc();
6515   MachineFunction *MF = MBB->getParent();
6516   MachineRegisterInfo *MRI = &MF->getRegInfo();
6517   MachineConstantPool *MCP = MF->getConstantPool();
6518   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6519   const Function *F = MF->getFunction();
6520
6521   bool isThumb = Subtarget->isThumb();
6522   bool isThumb2 = Subtarget->isThumb2();
6523
6524   unsigned PCLabelId = AFI->createPICLabelUId();
6525   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6526   ARMConstantPoolValue *CPV =
6527     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6528   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6529
6530   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6531                                            : &ARM::GPRRegClass;
6532
6533   // Grab constant pool and fixed stack memory operands.
6534   MachineMemOperand *CPMMO =
6535     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6536                              MachineMemOperand::MOLoad, 4, 4);
6537
6538   MachineMemOperand *FIMMOSt =
6539     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6540                              MachineMemOperand::MOStore, 4, 4);
6541
6542   // Load the address of the dispatch MBB into the jump buffer.
6543   if (isThumb2) {
6544     // Incoming value: jbuf
6545     //   ldr.n  r5, LCPI1_1
6546     //   orr    r5, r5, #1
6547     //   add    r5, pc
6548     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6549     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6550     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6551                    .addConstantPoolIndex(CPI)
6552                    .addMemOperand(CPMMO));
6553     // Set the low bit because of thumb mode.
6554     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6555     AddDefaultCC(
6556       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6557                      .addReg(NewVReg1, RegState::Kill)
6558                      .addImm(0x01)));
6559     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6560     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6561       .addReg(NewVReg2, RegState::Kill)
6562       .addImm(PCLabelId);
6563     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6564                    .addReg(NewVReg3, RegState::Kill)
6565                    .addFrameIndex(FI)
6566                    .addImm(36)  // &jbuf[1] :: pc
6567                    .addMemOperand(FIMMOSt));
6568   } else if (isThumb) {
6569     // Incoming value: jbuf
6570     //   ldr.n  r1, LCPI1_4
6571     //   add    r1, pc
6572     //   mov    r2, #1
6573     //   orrs   r1, r2
6574     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6575     //   str    r1, [r2]
6576     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6577     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6578                    .addConstantPoolIndex(CPI)
6579                    .addMemOperand(CPMMO));
6580     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6581     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6582       .addReg(NewVReg1, RegState::Kill)
6583       .addImm(PCLabelId);
6584     // Set the low bit because of thumb mode.
6585     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6586     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6587                    .addReg(ARM::CPSR, RegState::Define)
6588                    .addImm(1));
6589     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6590     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6591                    .addReg(ARM::CPSR, RegState::Define)
6592                    .addReg(NewVReg2, RegState::Kill)
6593                    .addReg(NewVReg3, RegState::Kill));
6594     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6595     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6596             .addFrameIndex(FI)
6597             .addImm(36); // &jbuf[1] :: pc
6598     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6599                    .addReg(NewVReg4, RegState::Kill)
6600                    .addReg(NewVReg5, RegState::Kill)
6601                    .addImm(0)
6602                    .addMemOperand(FIMMOSt));
6603   } else {
6604     // Incoming value: jbuf
6605     //   ldr  r1, LCPI1_1
6606     //   add  r1, pc, r1
6607     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6608     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6609     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6610                    .addConstantPoolIndex(CPI)
6611                    .addImm(0)
6612                    .addMemOperand(CPMMO));
6613     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6614     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6615                    .addReg(NewVReg1, RegState::Kill)
6616                    .addImm(PCLabelId));
6617     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6618                    .addReg(NewVReg2, RegState::Kill)
6619                    .addFrameIndex(FI)
6620                    .addImm(36)  // &jbuf[1] :: pc
6621                    .addMemOperand(FIMMOSt));
6622   }
6623 }
6624
6625 MachineBasicBlock *ARMTargetLowering::
6626 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6627   const TargetInstrInfo *TII =
6628       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6629   DebugLoc dl = MI->getDebugLoc();
6630   MachineFunction *MF = MBB->getParent();
6631   MachineRegisterInfo *MRI = &MF->getRegInfo();
6632   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6633   MachineFrameInfo *MFI = MF->getFrameInfo();
6634   int FI = MFI->getFunctionContextIndex();
6635
6636   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6637                                                         : &ARM::GPRnopcRegClass;
6638
6639   // Get a mapping of the call site numbers to all of the landing pads they're
6640   // associated with.
6641   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6642   unsigned MaxCSNum = 0;
6643   MachineModuleInfo &MMI = MF->getMMI();
6644   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6645        ++BB) {
6646     if (!BB->isLandingPad()) continue;
6647
6648     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6649     // pad.
6650     for (MachineBasicBlock::iterator
6651            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6652       if (!II->isEHLabel()) continue;
6653
6654       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6655       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6656
6657       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6658       for (SmallVectorImpl<unsigned>::iterator
6659              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6660            CSI != CSE; ++CSI) {
6661         CallSiteNumToLPad[*CSI].push_back(BB);
6662         MaxCSNum = std::max(MaxCSNum, *CSI);
6663       }
6664       break;
6665     }
6666   }
6667
6668   // Get an ordered list of the machine basic blocks for the jump table.
6669   std::vector<MachineBasicBlock*> LPadList;
6670   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6671   LPadList.reserve(CallSiteNumToLPad.size());
6672   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6673     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6674     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6675            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6676       LPadList.push_back(*II);
6677       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6678     }
6679   }
6680
6681   assert(!LPadList.empty() &&
6682          "No landing pad destinations for the dispatch jump table!");
6683
6684   // Create the jump table and associated information.
6685   MachineJumpTableInfo *JTI =
6686     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6687   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6688   unsigned UId = AFI->createJumpTableUId();
6689   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6690
6691   // Create the MBBs for the dispatch code.
6692
6693   // Shove the dispatch's address into the return slot in the function context.
6694   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6695   DispatchBB->setIsLandingPad();
6696
6697   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6698   unsigned trap_opcode;
6699   if (Subtarget->isThumb())
6700     trap_opcode = ARM::tTRAP;
6701   else
6702     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6703
6704   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6705   DispatchBB->addSuccessor(TrapBB);
6706
6707   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6708   DispatchBB->addSuccessor(DispContBB);
6709
6710   // Insert and MBBs.
6711   MF->insert(MF->end(), DispatchBB);
6712   MF->insert(MF->end(), DispContBB);
6713   MF->insert(MF->end(), TrapBB);
6714
6715   // Insert code into the entry block that creates and registers the function
6716   // context.
6717   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6718
6719   MachineMemOperand *FIMMOLd =
6720     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6721                              MachineMemOperand::MOLoad |
6722                              MachineMemOperand::MOVolatile, 4, 4);
6723
6724   MachineInstrBuilder MIB;
6725   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6726
6727   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6728   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6729
6730   // Add a register mask with no preserved registers.  This results in all
6731   // registers being marked as clobbered.
6732   MIB.addRegMask(RI.getNoPreservedMask());
6733
6734   unsigned NumLPads = LPadList.size();
6735   if (Subtarget->isThumb2()) {
6736     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6737     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6738                    .addFrameIndex(FI)
6739                    .addImm(4)
6740                    .addMemOperand(FIMMOLd));
6741
6742     if (NumLPads < 256) {
6743       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6744                      .addReg(NewVReg1)
6745                      .addImm(LPadList.size()));
6746     } else {
6747       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6748       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6749                      .addImm(NumLPads & 0xFFFF));
6750
6751       unsigned VReg2 = VReg1;
6752       if ((NumLPads & 0xFFFF0000) != 0) {
6753         VReg2 = MRI->createVirtualRegister(TRC);
6754         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6755                        .addReg(VReg1)
6756                        .addImm(NumLPads >> 16));
6757       }
6758
6759       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6760                      .addReg(NewVReg1)
6761                      .addReg(VReg2));
6762     }
6763
6764     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6765       .addMBB(TrapBB)
6766       .addImm(ARMCC::HI)
6767       .addReg(ARM::CPSR);
6768
6769     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6770     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6771                    .addJumpTableIndex(MJTI)
6772                    .addImm(UId));
6773
6774     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6775     AddDefaultCC(
6776       AddDefaultPred(
6777         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6778         .addReg(NewVReg3, RegState::Kill)
6779         .addReg(NewVReg1)
6780         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6781
6782     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6783       .addReg(NewVReg4, RegState::Kill)
6784       .addReg(NewVReg1)
6785       .addJumpTableIndex(MJTI)
6786       .addImm(UId);
6787   } else if (Subtarget->isThumb()) {
6788     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6789     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6790                    .addFrameIndex(FI)
6791                    .addImm(1)
6792                    .addMemOperand(FIMMOLd));
6793
6794     if (NumLPads < 256) {
6795       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6796                      .addReg(NewVReg1)
6797                      .addImm(NumLPads));
6798     } else {
6799       MachineConstantPool *ConstantPool = MF->getConstantPool();
6800       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6801       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6802
6803       // MachineConstantPool wants an explicit alignment.
6804       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6805       if (Align == 0)
6806         Align = getDataLayout()->getTypeAllocSize(C->getType());
6807       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6808
6809       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6810       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6811                      .addReg(VReg1, RegState::Define)
6812                      .addConstantPoolIndex(Idx));
6813       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6814                      .addReg(NewVReg1)
6815                      .addReg(VReg1));
6816     }
6817
6818     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6819       .addMBB(TrapBB)
6820       .addImm(ARMCC::HI)
6821       .addReg(ARM::CPSR);
6822
6823     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6824     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6825                    .addReg(ARM::CPSR, RegState::Define)
6826                    .addReg(NewVReg1)
6827                    .addImm(2));
6828
6829     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6830     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6831                    .addJumpTableIndex(MJTI)
6832                    .addImm(UId));
6833
6834     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6835     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6836                    .addReg(ARM::CPSR, RegState::Define)
6837                    .addReg(NewVReg2, RegState::Kill)
6838                    .addReg(NewVReg3));
6839
6840     MachineMemOperand *JTMMOLd =
6841       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6842                                MachineMemOperand::MOLoad, 4, 4);
6843
6844     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6845     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6846                    .addReg(NewVReg4, RegState::Kill)
6847                    .addImm(0)
6848                    .addMemOperand(JTMMOLd));
6849
6850     unsigned NewVReg6 = NewVReg5;
6851     if (RelocM == Reloc::PIC_) {
6852       NewVReg6 = MRI->createVirtualRegister(TRC);
6853       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6854                      .addReg(ARM::CPSR, RegState::Define)
6855                      .addReg(NewVReg5, RegState::Kill)
6856                      .addReg(NewVReg3));
6857     }
6858
6859     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6860       .addReg(NewVReg6, RegState::Kill)
6861       .addJumpTableIndex(MJTI)
6862       .addImm(UId);
6863   } else {
6864     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6865     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6866                    .addFrameIndex(FI)
6867                    .addImm(4)
6868                    .addMemOperand(FIMMOLd));
6869
6870     if (NumLPads < 256) {
6871       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6872                      .addReg(NewVReg1)
6873                      .addImm(NumLPads));
6874     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6875       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6876       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6877                      .addImm(NumLPads & 0xFFFF));
6878
6879       unsigned VReg2 = VReg1;
6880       if ((NumLPads & 0xFFFF0000) != 0) {
6881         VReg2 = MRI->createVirtualRegister(TRC);
6882         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6883                        .addReg(VReg1)
6884                        .addImm(NumLPads >> 16));
6885       }
6886
6887       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6888                      .addReg(NewVReg1)
6889                      .addReg(VReg2));
6890     } else {
6891       MachineConstantPool *ConstantPool = MF->getConstantPool();
6892       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6893       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6894
6895       // MachineConstantPool wants an explicit alignment.
6896       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6897       if (Align == 0)
6898         Align = getDataLayout()->getTypeAllocSize(C->getType());
6899       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6900
6901       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6902       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6903                      .addReg(VReg1, RegState::Define)
6904                      .addConstantPoolIndex(Idx)
6905                      .addImm(0));
6906       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6907                      .addReg(NewVReg1)
6908                      .addReg(VReg1, RegState::Kill));
6909     }
6910
6911     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6912       .addMBB(TrapBB)
6913       .addImm(ARMCC::HI)
6914       .addReg(ARM::CPSR);
6915
6916     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6917     AddDefaultCC(
6918       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6919                      .addReg(NewVReg1)
6920                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6921     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6922     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6923                    .addJumpTableIndex(MJTI)
6924                    .addImm(UId));
6925
6926     MachineMemOperand *JTMMOLd =
6927       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6928                                MachineMemOperand::MOLoad, 4, 4);
6929     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6930     AddDefaultPred(
6931       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6932       .addReg(NewVReg3, RegState::Kill)
6933       .addReg(NewVReg4)
6934       .addImm(0)
6935       .addMemOperand(JTMMOLd));
6936
6937     if (RelocM == Reloc::PIC_) {
6938       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6939         .addReg(NewVReg5, RegState::Kill)
6940         .addReg(NewVReg4)
6941         .addJumpTableIndex(MJTI)
6942         .addImm(UId);
6943     } else {
6944       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6945         .addReg(NewVReg5, RegState::Kill)
6946         .addJumpTableIndex(MJTI)
6947         .addImm(UId);
6948     }
6949   }
6950
6951   // Add the jump table entries as successors to the MBB.
6952   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6953   for (std::vector<MachineBasicBlock*>::iterator
6954          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6955     MachineBasicBlock *CurMBB = *I;
6956     if (SeenMBBs.insert(CurMBB).second)
6957       DispContBB->addSuccessor(CurMBB);
6958   }
6959
6960   // N.B. the order the invoke BBs are processed in doesn't matter here.
6961   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6962   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6963   for (MachineBasicBlock *BB : InvokeBBs) {
6964
6965     // Remove the landing pad successor from the invoke block and replace it
6966     // with the new dispatch block.
6967     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6968                                                   BB->succ_end());
6969     while (!Successors.empty()) {
6970       MachineBasicBlock *SMBB = Successors.pop_back_val();
6971       if (SMBB->isLandingPad()) {
6972         BB->removeSuccessor(SMBB);
6973         MBBLPads.push_back(SMBB);
6974       }
6975     }
6976
6977     BB->addSuccessor(DispatchBB);
6978
6979     // Find the invoke call and mark all of the callee-saved registers as
6980     // 'implicit defined' so that they're spilled. This prevents code from
6981     // moving instructions to before the EH block, where they will never be
6982     // executed.
6983     for (MachineBasicBlock::reverse_iterator
6984            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6985       if (!II->isCall()) continue;
6986
6987       DenseMap<unsigned, bool> DefRegs;
6988       for (MachineInstr::mop_iterator
6989              OI = II->operands_begin(), OE = II->operands_end();
6990            OI != OE; ++OI) {
6991         if (!OI->isReg()) continue;
6992         DefRegs[OI->getReg()] = true;
6993       }
6994
6995       MachineInstrBuilder MIB(*MF, &*II);
6996
6997       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6998         unsigned Reg = SavedRegs[i];
6999         if (Subtarget->isThumb2() &&
7000             !ARM::tGPRRegClass.contains(Reg) &&
7001             !ARM::hGPRRegClass.contains(Reg))
7002           continue;
7003         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7004           continue;
7005         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7006           continue;
7007         if (!DefRegs[Reg])
7008           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7009       }
7010
7011       break;
7012     }
7013   }
7014
7015   // Mark all former landing pads as non-landing pads. The dispatch is the only
7016   // landing pad now.
7017   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7018          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7019     (*I)->setIsLandingPad(false);
7020
7021   // The instruction is gone now.
7022   MI->eraseFromParent();
7023
7024   return MBB;
7025 }
7026
7027 static
7028 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7029   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7030        E = MBB->succ_end(); I != E; ++I)
7031     if (*I != Succ)
7032       return *I;
7033   llvm_unreachable("Expecting a BB with two successors!");
7034 }
7035
7036 /// Return the load opcode for a given load size. If load size >= 8,
7037 /// neon opcode will be returned.
7038 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7039   if (LdSize >= 8)
7040     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7041                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7042   if (IsThumb1)
7043     return LdSize == 4 ? ARM::tLDRi
7044                        : LdSize == 2 ? ARM::tLDRHi
7045                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7046   if (IsThumb2)
7047     return LdSize == 4 ? ARM::t2LDR_POST
7048                        : LdSize == 2 ? ARM::t2LDRH_POST
7049                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7050   return LdSize == 4 ? ARM::LDR_POST_IMM
7051                      : LdSize == 2 ? ARM::LDRH_POST
7052                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7053 }
7054
7055 /// Return the store opcode for a given store size. If store size >= 8,
7056 /// neon opcode will be returned.
7057 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7058   if (StSize >= 8)
7059     return StSize == 16 ? ARM::VST1q32wb_fixed
7060                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7061   if (IsThumb1)
7062     return StSize == 4 ? ARM::tSTRi
7063                        : StSize == 2 ? ARM::tSTRHi
7064                                      : StSize == 1 ? ARM::tSTRBi : 0;
7065   if (IsThumb2)
7066     return StSize == 4 ? ARM::t2STR_POST
7067                        : StSize == 2 ? ARM::t2STRH_POST
7068                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7069   return StSize == 4 ? ARM::STR_POST_IMM
7070                      : StSize == 2 ? ARM::STRH_POST
7071                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7072 }
7073
7074 /// Emit a post-increment load operation with given size. The instructions
7075 /// will be added to BB at Pos.
7076 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7077                        const TargetInstrInfo *TII, DebugLoc dl,
7078                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7079                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7080   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7081   assert(LdOpc != 0 && "Should have a load opcode");
7082   if (LdSize >= 8) {
7083     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7084                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7085                        .addImm(0));
7086   } else if (IsThumb1) {
7087     // load + update AddrIn
7088     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7089                        .addReg(AddrIn).addImm(0));
7090     MachineInstrBuilder MIB =
7091         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7092     MIB = AddDefaultT1CC(MIB);
7093     MIB.addReg(AddrIn).addImm(LdSize);
7094     AddDefaultPred(MIB);
7095   } else if (IsThumb2) {
7096     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7097                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7098                        .addImm(LdSize));
7099   } else { // arm
7100     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7101                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7102                        .addReg(0).addImm(LdSize));
7103   }
7104 }
7105
7106 /// Emit a post-increment store operation with given size. The instructions
7107 /// will be added to BB at Pos.
7108 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7109                        const TargetInstrInfo *TII, DebugLoc dl,
7110                        unsigned StSize, unsigned Data, unsigned AddrIn,
7111                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7112   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7113   assert(StOpc != 0 && "Should have a store opcode");
7114   if (StSize >= 8) {
7115     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7116                        .addReg(AddrIn).addImm(0).addReg(Data));
7117   } else if (IsThumb1) {
7118     // store + update AddrIn
7119     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7120                        .addReg(AddrIn).addImm(0));
7121     MachineInstrBuilder MIB =
7122         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7123     MIB = AddDefaultT1CC(MIB);
7124     MIB.addReg(AddrIn).addImm(StSize);
7125     AddDefaultPred(MIB);
7126   } else if (IsThumb2) {
7127     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7128                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7129   } else { // arm
7130     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7131                        .addReg(Data).addReg(AddrIn).addReg(0)
7132                        .addImm(StSize));
7133   }
7134 }
7135
7136 MachineBasicBlock *
7137 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7138                                    MachineBasicBlock *BB) const {
7139   // This pseudo instruction has 3 operands: dst, src, size
7140   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7141   // Otherwise, we will generate unrolled scalar copies.
7142   const TargetInstrInfo *TII =
7143       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7144   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7145   MachineFunction::iterator It = BB;
7146   ++It;
7147
7148   unsigned dest = MI->getOperand(0).getReg();
7149   unsigned src = MI->getOperand(1).getReg();
7150   unsigned SizeVal = MI->getOperand(2).getImm();
7151   unsigned Align = MI->getOperand(3).getImm();
7152   DebugLoc dl = MI->getDebugLoc();
7153
7154   MachineFunction *MF = BB->getParent();
7155   MachineRegisterInfo &MRI = MF->getRegInfo();
7156   unsigned UnitSize = 0;
7157   const TargetRegisterClass *TRC = nullptr;
7158   const TargetRegisterClass *VecTRC = nullptr;
7159
7160   bool IsThumb1 = Subtarget->isThumb1Only();
7161   bool IsThumb2 = Subtarget->isThumb2();
7162
7163   if (Align & 1) {
7164     UnitSize = 1;
7165   } else if (Align & 2) {
7166     UnitSize = 2;
7167   } else {
7168     // Check whether we can use NEON instructions.
7169     if (!MF->getFunction()->getAttributes().
7170           hasAttribute(AttributeSet::FunctionIndex,
7171                        Attribute::NoImplicitFloat) &&
7172         Subtarget->hasNEON()) {
7173       if ((Align % 16 == 0) && SizeVal >= 16)
7174         UnitSize = 16;
7175       else if ((Align % 8 == 0) && SizeVal >= 8)
7176         UnitSize = 8;
7177     }
7178     // Can't use NEON instructions.
7179     if (UnitSize == 0)
7180       UnitSize = 4;
7181   }
7182
7183   // Select the correct opcode and register class for unit size load/store
7184   bool IsNeon = UnitSize >= 8;
7185   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7186   if (IsNeon)
7187     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7188                             : UnitSize == 8 ? &ARM::DPRRegClass
7189                                             : nullptr;
7190
7191   unsigned BytesLeft = SizeVal % UnitSize;
7192   unsigned LoopSize = SizeVal - BytesLeft;
7193
7194   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7195     // Use LDR and STR to copy.
7196     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7197     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7198     unsigned srcIn = src;
7199     unsigned destIn = dest;
7200     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7201       unsigned srcOut = MRI.createVirtualRegister(TRC);
7202       unsigned destOut = MRI.createVirtualRegister(TRC);
7203       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7204       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7205                  IsThumb1, IsThumb2);
7206       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7207                  IsThumb1, IsThumb2);
7208       srcIn = srcOut;
7209       destIn = destOut;
7210     }
7211
7212     // Handle the leftover bytes with LDRB and STRB.
7213     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7214     // [destOut] = STRB_POST(scratch, destIn, 1)
7215     for (unsigned i = 0; i < BytesLeft; i++) {
7216       unsigned srcOut = MRI.createVirtualRegister(TRC);
7217       unsigned destOut = MRI.createVirtualRegister(TRC);
7218       unsigned scratch = MRI.createVirtualRegister(TRC);
7219       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7220                  IsThumb1, IsThumb2);
7221       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7222                  IsThumb1, IsThumb2);
7223       srcIn = srcOut;
7224       destIn = destOut;
7225     }
7226     MI->eraseFromParent();   // The instruction is gone now.
7227     return BB;
7228   }
7229
7230   // Expand the pseudo op to a loop.
7231   // thisMBB:
7232   //   ...
7233   //   movw varEnd, # --> with thumb2
7234   //   movt varEnd, #
7235   //   ldrcp varEnd, idx --> without thumb2
7236   //   fallthrough --> loopMBB
7237   // loopMBB:
7238   //   PHI varPhi, varEnd, varLoop
7239   //   PHI srcPhi, src, srcLoop
7240   //   PHI destPhi, dst, destLoop
7241   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7242   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7243   //   subs varLoop, varPhi, #UnitSize
7244   //   bne loopMBB
7245   //   fallthrough --> exitMBB
7246   // exitMBB:
7247   //   epilogue to handle left-over bytes
7248   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7249   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7250   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7251   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7252   MF->insert(It, loopMBB);
7253   MF->insert(It, exitMBB);
7254
7255   // Transfer the remainder of BB and its successor edges to exitMBB.
7256   exitMBB->splice(exitMBB->begin(), BB,
7257                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7258   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7259
7260   // Load an immediate to varEnd.
7261   unsigned varEnd = MRI.createVirtualRegister(TRC);
7262   if (IsThumb2) {
7263     unsigned Vtmp = varEnd;
7264     if ((LoopSize & 0xFFFF0000) != 0)
7265       Vtmp = MRI.createVirtualRegister(TRC);
7266     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7267                        .addImm(LoopSize & 0xFFFF));
7268
7269     if ((LoopSize & 0xFFFF0000) != 0)
7270       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7271                          .addReg(Vtmp).addImm(LoopSize >> 16));
7272   } else {
7273     MachineConstantPool *ConstantPool = MF->getConstantPool();
7274     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7275     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7276
7277     // MachineConstantPool wants an explicit alignment.
7278     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7279     if (Align == 0)
7280       Align = getDataLayout()->getTypeAllocSize(C->getType());
7281     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7282
7283     if (IsThumb1)
7284       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7285           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7286     else
7287       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7288           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7289   }
7290   BB->addSuccessor(loopMBB);
7291
7292   // Generate the loop body:
7293   //   varPhi = PHI(varLoop, varEnd)
7294   //   srcPhi = PHI(srcLoop, src)
7295   //   destPhi = PHI(destLoop, dst)
7296   MachineBasicBlock *entryBB = BB;
7297   BB = loopMBB;
7298   unsigned varLoop = MRI.createVirtualRegister(TRC);
7299   unsigned varPhi = MRI.createVirtualRegister(TRC);
7300   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7301   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7302   unsigned destLoop = MRI.createVirtualRegister(TRC);
7303   unsigned destPhi = MRI.createVirtualRegister(TRC);
7304
7305   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7306     .addReg(varLoop).addMBB(loopMBB)
7307     .addReg(varEnd).addMBB(entryBB);
7308   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7309     .addReg(srcLoop).addMBB(loopMBB)
7310     .addReg(src).addMBB(entryBB);
7311   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7312     .addReg(destLoop).addMBB(loopMBB)
7313     .addReg(dest).addMBB(entryBB);
7314
7315   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7316   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7317   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7318   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7319              IsThumb1, IsThumb2);
7320   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7321              IsThumb1, IsThumb2);
7322
7323   // Decrement loop variable by UnitSize.
7324   if (IsThumb1) {
7325     MachineInstrBuilder MIB =
7326         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7327     MIB = AddDefaultT1CC(MIB);
7328     MIB.addReg(varPhi).addImm(UnitSize);
7329     AddDefaultPred(MIB);
7330   } else {
7331     MachineInstrBuilder MIB =
7332         BuildMI(*BB, BB->end(), dl,
7333                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7334     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7335     MIB->getOperand(5).setReg(ARM::CPSR);
7336     MIB->getOperand(5).setIsDef(true);
7337   }
7338   BuildMI(*BB, BB->end(), dl,
7339           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7340       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7341
7342   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7343   BB->addSuccessor(loopMBB);
7344   BB->addSuccessor(exitMBB);
7345
7346   // Add epilogue to handle BytesLeft.
7347   BB = exitMBB;
7348   MachineInstr *StartOfExit = exitMBB->begin();
7349
7350   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7351   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7352   unsigned srcIn = srcLoop;
7353   unsigned destIn = destLoop;
7354   for (unsigned i = 0; i < BytesLeft; i++) {
7355     unsigned srcOut = MRI.createVirtualRegister(TRC);
7356     unsigned destOut = MRI.createVirtualRegister(TRC);
7357     unsigned scratch = MRI.createVirtualRegister(TRC);
7358     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7359                IsThumb1, IsThumb2);
7360     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7361                IsThumb1, IsThumb2);
7362     srcIn = srcOut;
7363     destIn = destOut;
7364   }
7365
7366   MI->eraseFromParent();   // The instruction is gone now.
7367   return BB;
7368 }
7369
7370 MachineBasicBlock *
7371 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7372                                        MachineBasicBlock *MBB) const {
7373   const TargetMachine &TM = getTargetMachine();
7374   const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7375   DebugLoc DL = MI->getDebugLoc();
7376
7377   assert(Subtarget->isTargetWindows() &&
7378          "__chkstk is only supported on Windows");
7379   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7380
7381   // __chkstk takes the number of words to allocate on the stack in R4, and
7382   // returns the stack adjustment in number of bytes in R4.  This will not
7383   // clober any other registers (other than the obvious lr).
7384   //
7385   // Although, technically, IP should be considered a register which may be
7386   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7387   // thumb-2 environment, so there is no interworking required.  As a result, we
7388   // do not expect a veneer to be emitted by the linker, clobbering IP.
7389   //
7390   // Each module receives its own copy of __chkstk, so no import thunk is
7391   // required, again, ensuring that IP is not clobbered.
7392   //
7393   // Finally, although some linkers may theoretically provide a trampoline for
7394   // out of range calls (which is quite common due to a 32M range limitation of
7395   // branches for Thumb), we can generate the long-call version via
7396   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7397   // IP.
7398
7399   switch (TM.getCodeModel()) {
7400   case CodeModel::Small:
7401   case CodeModel::Medium:
7402   case CodeModel::Default:
7403   case CodeModel::Kernel:
7404     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7405       .addImm((unsigned)ARMCC::AL).addReg(0)
7406       .addExternalSymbol("__chkstk")
7407       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7408       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7409       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7410     break;
7411   case CodeModel::Large:
7412   case CodeModel::JITDefault: {
7413     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7414     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7415
7416     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7417       .addExternalSymbol("__chkstk");
7418     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7419       .addImm((unsigned)ARMCC::AL).addReg(0)
7420       .addReg(Reg, RegState::Kill)
7421       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7422       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7423       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7424     break;
7425   }
7426   }
7427
7428   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7429                                       ARM::SP)
7430                               .addReg(ARM::SP).addReg(ARM::R4)));
7431
7432   MI->eraseFromParent();
7433   return MBB;
7434 }
7435
7436 MachineBasicBlock *
7437 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7438                                                MachineBasicBlock *BB) const {
7439   const TargetInstrInfo *TII =
7440       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7441   DebugLoc dl = MI->getDebugLoc();
7442   bool isThumb2 = Subtarget->isThumb2();
7443   switch (MI->getOpcode()) {
7444   default: {
7445     MI->dump();
7446     llvm_unreachable("Unexpected instr type to insert");
7447   }
7448   // The Thumb2 pre-indexed stores have the same MI operands, they just
7449   // define them differently in the .td files from the isel patterns, so
7450   // they need pseudos.
7451   case ARM::t2STR_preidx:
7452     MI->setDesc(TII->get(ARM::t2STR_PRE));
7453     return BB;
7454   case ARM::t2STRB_preidx:
7455     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7456     return BB;
7457   case ARM::t2STRH_preidx:
7458     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7459     return BB;
7460
7461   case ARM::STRi_preidx:
7462   case ARM::STRBi_preidx: {
7463     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7464       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7465     // Decode the offset.
7466     unsigned Offset = MI->getOperand(4).getImm();
7467     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7468     Offset = ARM_AM::getAM2Offset(Offset);
7469     if (isSub)
7470       Offset = -Offset;
7471
7472     MachineMemOperand *MMO = *MI->memoperands_begin();
7473     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7474       .addOperand(MI->getOperand(0))  // Rn_wb
7475       .addOperand(MI->getOperand(1))  // Rt
7476       .addOperand(MI->getOperand(2))  // Rn
7477       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7478       .addOperand(MI->getOperand(5))  // pred
7479       .addOperand(MI->getOperand(6))
7480       .addMemOperand(MMO);
7481     MI->eraseFromParent();
7482     return BB;
7483   }
7484   case ARM::STRr_preidx:
7485   case ARM::STRBr_preidx:
7486   case ARM::STRH_preidx: {
7487     unsigned NewOpc;
7488     switch (MI->getOpcode()) {
7489     default: llvm_unreachable("unexpected opcode!");
7490     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7491     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7492     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7493     }
7494     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7495     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7496       MIB.addOperand(MI->getOperand(i));
7497     MI->eraseFromParent();
7498     return BB;
7499   }
7500
7501   case ARM::tMOVCCr_pseudo: {
7502     // To "insert" a SELECT_CC instruction, we actually have to insert the
7503     // diamond control-flow pattern.  The incoming instruction knows the
7504     // destination vreg to set, the condition code register to branch on, the
7505     // true/false values to select between, and a branch opcode to use.
7506     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7507     MachineFunction::iterator It = BB;
7508     ++It;
7509
7510     //  thisMBB:
7511     //  ...
7512     //   TrueVal = ...
7513     //   cmpTY ccX, r1, r2
7514     //   bCC copy1MBB
7515     //   fallthrough --> copy0MBB
7516     MachineBasicBlock *thisMBB  = BB;
7517     MachineFunction *F = BB->getParent();
7518     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7519     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7520     F->insert(It, copy0MBB);
7521     F->insert(It, sinkMBB);
7522
7523     // Transfer the remainder of BB and its successor edges to sinkMBB.
7524     sinkMBB->splice(sinkMBB->begin(), BB,
7525                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7526     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7527
7528     BB->addSuccessor(copy0MBB);
7529     BB->addSuccessor(sinkMBB);
7530
7531     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7532       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7533
7534     //  copy0MBB:
7535     //   %FalseValue = ...
7536     //   # fallthrough to sinkMBB
7537     BB = copy0MBB;
7538
7539     // Update machine-CFG edges
7540     BB->addSuccessor(sinkMBB);
7541
7542     //  sinkMBB:
7543     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7544     //  ...
7545     BB = sinkMBB;
7546     BuildMI(*BB, BB->begin(), dl,
7547             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7548       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7549       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7550
7551     MI->eraseFromParent();   // The pseudo instruction is gone now.
7552     return BB;
7553   }
7554
7555   case ARM::BCCi64:
7556   case ARM::BCCZi64: {
7557     // If there is an unconditional branch to the other successor, remove it.
7558     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7559
7560     // Compare both parts that make up the double comparison separately for
7561     // equality.
7562     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7563
7564     unsigned LHS1 = MI->getOperand(1).getReg();
7565     unsigned LHS2 = MI->getOperand(2).getReg();
7566     if (RHSisZero) {
7567       AddDefaultPred(BuildMI(BB, dl,
7568                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7569                      .addReg(LHS1).addImm(0));
7570       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7571         .addReg(LHS2).addImm(0)
7572         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7573     } else {
7574       unsigned RHS1 = MI->getOperand(3).getReg();
7575       unsigned RHS2 = MI->getOperand(4).getReg();
7576       AddDefaultPred(BuildMI(BB, dl,
7577                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7578                      .addReg(LHS1).addReg(RHS1));
7579       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7580         .addReg(LHS2).addReg(RHS2)
7581         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7582     }
7583
7584     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7585     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7586     if (MI->getOperand(0).getImm() == ARMCC::NE)
7587       std::swap(destMBB, exitMBB);
7588
7589     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7590       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7591     if (isThumb2)
7592       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7593     else
7594       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7595
7596     MI->eraseFromParent();   // The pseudo instruction is gone now.
7597     return BB;
7598   }
7599
7600   case ARM::Int_eh_sjlj_setjmp:
7601   case ARM::Int_eh_sjlj_setjmp_nofp:
7602   case ARM::tInt_eh_sjlj_setjmp:
7603   case ARM::t2Int_eh_sjlj_setjmp:
7604   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7605     EmitSjLjDispatchBlock(MI, BB);
7606     return BB;
7607
7608   case ARM::ABS:
7609   case ARM::t2ABS: {
7610     // To insert an ABS instruction, we have to insert the
7611     // diamond control-flow pattern.  The incoming instruction knows the
7612     // source vreg to test against 0, the destination vreg to set,
7613     // the condition code register to branch on, the
7614     // true/false values to select between, and a branch opcode to use.
7615     // It transforms
7616     //     V1 = ABS V0
7617     // into
7618     //     V2 = MOVS V0
7619     //     BCC                      (branch to SinkBB if V0 >= 0)
7620     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7621     //     SinkBB: V1 = PHI(V2, V3)
7622     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7623     MachineFunction::iterator BBI = BB;
7624     ++BBI;
7625     MachineFunction *Fn = BB->getParent();
7626     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7627     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7628     Fn->insert(BBI, RSBBB);
7629     Fn->insert(BBI, SinkBB);
7630
7631     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7632     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7633     bool isThumb2 = Subtarget->isThumb2();
7634     MachineRegisterInfo &MRI = Fn->getRegInfo();
7635     // In Thumb mode S must not be specified if source register is the SP or
7636     // PC and if destination register is the SP, so restrict register class
7637     unsigned NewRsbDstReg =
7638       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7639
7640     // Transfer the remainder of BB and its successor edges to sinkMBB.
7641     SinkBB->splice(SinkBB->begin(), BB,
7642                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7643     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7644
7645     BB->addSuccessor(RSBBB);
7646     BB->addSuccessor(SinkBB);
7647
7648     // fall through to SinkMBB
7649     RSBBB->addSuccessor(SinkBB);
7650
7651     // insert a cmp at the end of BB
7652     AddDefaultPred(BuildMI(BB, dl,
7653                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7654                    .addReg(ABSSrcReg).addImm(0));
7655
7656     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7657     BuildMI(BB, dl,
7658       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7659       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7660
7661     // insert rsbri in RSBBB
7662     // Note: BCC and rsbri will be converted into predicated rsbmi
7663     // by if-conversion pass
7664     BuildMI(*RSBBB, RSBBB->begin(), dl,
7665       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7666       .addReg(ABSSrcReg, RegState::Kill)
7667       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7668
7669     // insert PHI in SinkBB,
7670     // reuse ABSDstReg to not change uses of ABS instruction
7671     BuildMI(*SinkBB, SinkBB->begin(), dl,
7672       TII->get(ARM::PHI), ABSDstReg)
7673       .addReg(NewRsbDstReg).addMBB(RSBBB)
7674       .addReg(ABSSrcReg).addMBB(BB);
7675
7676     // remove ABS instruction
7677     MI->eraseFromParent();
7678
7679     // return last added BB
7680     return SinkBB;
7681   }
7682   case ARM::COPY_STRUCT_BYVAL_I32:
7683     ++NumLoopByVals;
7684     return EmitStructByval(MI, BB);
7685   case ARM::WIN__CHKSTK:
7686     return EmitLowered__chkstk(MI, BB);
7687   }
7688 }
7689
7690 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7691                                                       SDNode *Node) const {
7692   const MCInstrDesc *MCID = &MI->getDesc();
7693   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7694   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7695   // operand is still set to noreg. If needed, set the optional operand's
7696   // register to CPSR, and remove the redundant implicit def.
7697   //
7698   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7699
7700   // Rename pseudo opcodes.
7701   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7702   if (NewOpc) {
7703     const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7704         getTargetMachine().getSubtargetImpl()->getInstrInfo());
7705     MCID = &TII->get(NewOpc);
7706
7707     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7708            "converted opcode should be the same except for cc_out");
7709
7710     MI->setDesc(*MCID);
7711
7712     // Add the optional cc_out operand
7713     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7714   }
7715   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7716
7717   // Any ARM instruction that sets the 's' bit should specify an optional
7718   // "cc_out" operand in the last operand position.
7719   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7720     assert(!NewOpc && "Optional cc_out operand required");
7721     return;
7722   }
7723   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7724   // since we already have an optional CPSR def.
7725   bool definesCPSR = false;
7726   bool deadCPSR = false;
7727   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7728        i != e; ++i) {
7729     const MachineOperand &MO = MI->getOperand(i);
7730     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7731       definesCPSR = true;
7732       if (MO.isDead())
7733         deadCPSR = true;
7734       MI->RemoveOperand(i);
7735       break;
7736     }
7737   }
7738   if (!definesCPSR) {
7739     assert(!NewOpc && "Optional cc_out operand required");
7740     return;
7741   }
7742   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7743   if (deadCPSR) {
7744     assert(!MI->getOperand(ccOutIdx).getReg() &&
7745            "expect uninitialized optional cc_out operand");
7746     return;
7747   }
7748
7749   // If this instruction was defined with an optional CPSR def and its dag node
7750   // had a live implicit CPSR def, then activate the optional CPSR def.
7751   MachineOperand &MO = MI->getOperand(ccOutIdx);
7752   MO.setReg(ARM::CPSR);
7753   MO.setIsDef(true);
7754 }
7755
7756 //===----------------------------------------------------------------------===//
7757 //                           ARM Optimization Hooks
7758 //===----------------------------------------------------------------------===//
7759
7760 // Helper function that checks if N is a null or all ones constant.
7761 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7762   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7763   if (!C)
7764     return false;
7765   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7766 }
7767
7768 // Return true if N is conditionally 0 or all ones.
7769 // Detects these expressions where cc is an i1 value:
7770 //
7771 //   (select cc 0, y)   [AllOnes=0]
7772 //   (select cc y, 0)   [AllOnes=0]
7773 //   (zext cc)          [AllOnes=0]
7774 //   (sext cc)          [AllOnes=0/1]
7775 //   (select cc -1, y)  [AllOnes=1]
7776 //   (select cc y, -1)  [AllOnes=1]
7777 //
7778 // Invert is set when N is the null/all ones constant when CC is false.
7779 // OtherOp is set to the alternative value of N.
7780 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7781                                        SDValue &CC, bool &Invert,
7782                                        SDValue &OtherOp,
7783                                        SelectionDAG &DAG) {
7784   switch (N->getOpcode()) {
7785   default: return false;
7786   case ISD::SELECT: {
7787     CC = N->getOperand(0);
7788     SDValue N1 = N->getOperand(1);
7789     SDValue N2 = N->getOperand(2);
7790     if (isZeroOrAllOnes(N1, AllOnes)) {
7791       Invert = false;
7792       OtherOp = N2;
7793       return true;
7794     }
7795     if (isZeroOrAllOnes(N2, AllOnes)) {
7796       Invert = true;
7797       OtherOp = N1;
7798       return true;
7799     }
7800     return false;
7801   }
7802   case ISD::ZERO_EXTEND:
7803     // (zext cc) can never be the all ones value.
7804     if (AllOnes)
7805       return false;
7806     // Fall through.
7807   case ISD::SIGN_EXTEND: {
7808     EVT VT = N->getValueType(0);
7809     CC = N->getOperand(0);
7810     if (CC.getValueType() != MVT::i1)
7811       return false;
7812     Invert = !AllOnes;
7813     if (AllOnes)
7814       // When looking for an AllOnes constant, N is an sext, and the 'other'
7815       // value is 0.
7816       OtherOp = DAG.getConstant(0, VT);
7817     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7818       // When looking for a 0 constant, N can be zext or sext.
7819       OtherOp = DAG.getConstant(1, VT);
7820     else
7821       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7822     return true;
7823   }
7824   }
7825 }
7826
7827 // Combine a constant select operand into its use:
7828 //
7829 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7830 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7831 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7832 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7833 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7834 //
7835 // The transform is rejected if the select doesn't have a constant operand that
7836 // is null, or all ones when AllOnes is set.
7837 //
7838 // Also recognize sext/zext from i1:
7839 //
7840 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7841 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7842 //
7843 // These transformations eventually create predicated instructions.
7844 //
7845 // @param N       The node to transform.
7846 // @param Slct    The N operand that is a select.
7847 // @param OtherOp The other N operand (x above).
7848 // @param DCI     Context.
7849 // @param AllOnes Require the select constant to be all ones instead of null.
7850 // @returns The new node, or SDValue() on failure.
7851 static
7852 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7853                             TargetLowering::DAGCombinerInfo &DCI,
7854                             bool AllOnes = false) {
7855   SelectionDAG &DAG = DCI.DAG;
7856   EVT VT = N->getValueType(0);
7857   SDValue NonConstantVal;
7858   SDValue CCOp;
7859   bool SwapSelectOps;
7860   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7861                                   NonConstantVal, DAG))
7862     return SDValue();
7863
7864   // Slct is now know to be the desired identity constant when CC is true.
7865   SDValue TrueVal = OtherOp;
7866   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7867                                  OtherOp, NonConstantVal);
7868   // Unless SwapSelectOps says CC should be false.
7869   if (SwapSelectOps)
7870     std::swap(TrueVal, FalseVal);
7871
7872   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7873                      CCOp, TrueVal, FalseVal);
7874 }
7875
7876 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7877 static
7878 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7879                                        TargetLowering::DAGCombinerInfo &DCI) {
7880   SDValue N0 = N->getOperand(0);
7881   SDValue N1 = N->getOperand(1);
7882   if (N0.getNode()->hasOneUse()) {
7883     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7884     if (Result.getNode())
7885       return Result;
7886   }
7887   if (N1.getNode()->hasOneUse()) {
7888     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7889     if (Result.getNode())
7890       return Result;
7891   }
7892   return SDValue();
7893 }
7894
7895 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7896 // (only after legalization).
7897 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7898                                  TargetLowering::DAGCombinerInfo &DCI,
7899                                  const ARMSubtarget *Subtarget) {
7900
7901   // Only perform optimization if after legalize, and if NEON is available. We
7902   // also expected both operands to be BUILD_VECTORs.
7903   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7904       || N0.getOpcode() != ISD::BUILD_VECTOR
7905       || N1.getOpcode() != ISD::BUILD_VECTOR)
7906     return SDValue();
7907
7908   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7909   EVT VT = N->getValueType(0);
7910   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7911     return SDValue();
7912
7913   // Check that the vector operands are of the right form.
7914   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7915   // operands, where N is the size of the formed vector.
7916   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7917   // index such that we have a pair wise add pattern.
7918
7919   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7920   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7921     return SDValue();
7922   SDValue Vec = N0->getOperand(0)->getOperand(0);
7923   SDNode *V = Vec.getNode();
7924   unsigned nextIndex = 0;
7925
7926   // For each operands to the ADD which are BUILD_VECTORs,
7927   // check to see if each of their operands are an EXTRACT_VECTOR with
7928   // the same vector and appropriate index.
7929   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7930     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7931         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7932
7933       SDValue ExtVec0 = N0->getOperand(i);
7934       SDValue ExtVec1 = N1->getOperand(i);
7935
7936       // First operand is the vector, verify its the same.
7937       if (V != ExtVec0->getOperand(0).getNode() ||
7938           V != ExtVec1->getOperand(0).getNode())
7939         return SDValue();
7940
7941       // Second is the constant, verify its correct.
7942       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7943       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7944
7945       // For the constant, we want to see all the even or all the odd.
7946       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7947           || C1->getZExtValue() != nextIndex+1)
7948         return SDValue();
7949
7950       // Increment index.
7951       nextIndex+=2;
7952     } else
7953       return SDValue();
7954   }
7955
7956   // Create VPADDL node.
7957   SelectionDAG &DAG = DCI.DAG;
7958   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7959
7960   // Build operand list.
7961   SmallVector<SDValue, 8> Ops;
7962   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7963                                 TLI.getPointerTy()));
7964
7965   // Input is the vector.
7966   Ops.push_back(Vec);
7967
7968   // Get widened type and narrowed type.
7969   MVT widenType;
7970   unsigned numElem = VT.getVectorNumElements();
7971   
7972   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7973   switch (inputLaneType.getSimpleVT().SimpleTy) {
7974     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7975     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7976     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7977     default:
7978       llvm_unreachable("Invalid vector element type for padd optimization.");
7979   }
7980
7981   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7982   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7983   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7984 }
7985
7986 static SDValue findMUL_LOHI(SDValue V) {
7987   if (V->getOpcode() == ISD::UMUL_LOHI ||
7988       V->getOpcode() == ISD::SMUL_LOHI)
7989     return V;
7990   return SDValue();
7991 }
7992
7993 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7994                                      TargetLowering::DAGCombinerInfo &DCI,
7995                                      const ARMSubtarget *Subtarget) {
7996
7997   if (Subtarget->isThumb1Only()) return SDValue();
7998
7999   // Only perform the checks after legalize when the pattern is available.
8000   if (DCI.isBeforeLegalize()) return SDValue();
8001
8002   // Look for multiply add opportunities.
8003   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8004   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8005   // a glue link from the first add to the second add.
8006   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8007   // a S/UMLAL instruction.
8008   //          loAdd   UMUL_LOHI
8009   //            \    / :lo    \ :hi
8010   //             \  /          \          [no multiline comment]
8011   //              ADDC         |  hiAdd
8012   //                 \ :glue  /  /
8013   //                  \      /  /
8014   //                    ADDE
8015   //
8016   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8017   SDValue AddcOp0 = AddcNode->getOperand(0);
8018   SDValue AddcOp1 = AddcNode->getOperand(1);
8019
8020   // Check if the two operands are from the same mul_lohi node.
8021   if (AddcOp0.getNode() == AddcOp1.getNode())
8022     return SDValue();
8023
8024   assert(AddcNode->getNumValues() == 2 &&
8025          AddcNode->getValueType(0) == MVT::i32 &&
8026          "Expect ADDC with two result values. First: i32");
8027
8028   // Check that we have a glued ADDC node.
8029   if (AddcNode->getValueType(1) != MVT::Glue)
8030     return SDValue();
8031
8032   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8033   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8034       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8035       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8036       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8037     return SDValue();
8038
8039   // Look for the glued ADDE.
8040   SDNode* AddeNode = AddcNode->getGluedUser();
8041   if (!AddeNode)
8042     return SDValue();
8043
8044   // Make sure it is really an ADDE.
8045   if (AddeNode->getOpcode() != ISD::ADDE)
8046     return SDValue();
8047
8048   assert(AddeNode->getNumOperands() == 3 &&
8049          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8050          "ADDE node has the wrong inputs");
8051
8052   // Check for the triangle shape.
8053   SDValue AddeOp0 = AddeNode->getOperand(0);
8054   SDValue AddeOp1 = AddeNode->getOperand(1);
8055
8056   // Make sure that the ADDE operands are not coming from the same node.
8057   if (AddeOp0.getNode() == AddeOp1.getNode())
8058     return SDValue();
8059
8060   // Find the MUL_LOHI node walking up ADDE's operands.
8061   bool IsLeftOperandMUL = false;
8062   SDValue MULOp = findMUL_LOHI(AddeOp0);
8063   if (MULOp == SDValue())
8064    MULOp = findMUL_LOHI(AddeOp1);
8065   else
8066     IsLeftOperandMUL = true;
8067   if (MULOp == SDValue())
8068      return SDValue();
8069
8070   // Figure out the right opcode.
8071   unsigned Opc = MULOp->getOpcode();
8072   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8073
8074   // Figure out the high and low input values to the MLAL node.
8075   SDValue* HiMul = &MULOp;
8076   SDValue* HiAdd = nullptr;
8077   SDValue* LoMul = nullptr;
8078   SDValue* LowAdd = nullptr;
8079
8080   if (IsLeftOperandMUL)
8081     HiAdd = &AddeOp1;
8082   else
8083     HiAdd = &AddeOp0;
8084
8085
8086   if (AddcOp0->getOpcode() == Opc) {
8087     LoMul = &AddcOp0;
8088     LowAdd = &AddcOp1;
8089   }
8090   if (AddcOp1->getOpcode() == Opc) {
8091     LoMul = &AddcOp1;
8092     LowAdd = &AddcOp0;
8093   }
8094
8095   if (!LoMul)
8096     return SDValue();
8097
8098   if (LoMul->getNode() != HiMul->getNode())
8099     return SDValue();
8100
8101   // Create the merged node.
8102   SelectionDAG &DAG = DCI.DAG;
8103
8104   // Build operand list.
8105   SmallVector<SDValue, 8> Ops;
8106   Ops.push_back(LoMul->getOperand(0));
8107   Ops.push_back(LoMul->getOperand(1));
8108   Ops.push_back(*LowAdd);
8109   Ops.push_back(*HiAdd);
8110
8111   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8112                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8113
8114   // Replace the ADDs' nodes uses by the MLA node's values.
8115   SDValue HiMLALResult(MLALNode.getNode(), 1);
8116   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8117
8118   SDValue LoMLALResult(MLALNode.getNode(), 0);
8119   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8120
8121   // Return original node to notify the driver to stop replacing.
8122   SDValue resNode(AddcNode, 0);
8123   return resNode;
8124 }
8125
8126 /// PerformADDCCombine - Target-specific dag combine transform from
8127 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8128 static SDValue PerformADDCCombine(SDNode *N,
8129                                  TargetLowering::DAGCombinerInfo &DCI,
8130                                  const ARMSubtarget *Subtarget) {
8131
8132   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8133
8134 }
8135
8136 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8137 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8138 /// called with the default operands, and if that fails, with commuted
8139 /// operands.
8140 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8141                                           TargetLowering::DAGCombinerInfo &DCI,
8142                                           const ARMSubtarget *Subtarget){
8143
8144   // Attempt to create vpaddl for this add.
8145   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8146   if (Result.getNode())
8147     return Result;
8148
8149   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8150   if (N0.getNode()->hasOneUse()) {
8151     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8152     if (Result.getNode()) return Result;
8153   }
8154   return SDValue();
8155 }
8156
8157 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8158 ///
8159 static SDValue PerformADDCombine(SDNode *N,
8160                                  TargetLowering::DAGCombinerInfo &DCI,
8161                                  const ARMSubtarget *Subtarget) {
8162   SDValue N0 = N->getOperand(0);
8163   SDValue N1 = N->getOperand(1);
8164
8165   // First try with the default operand order.
8166   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8167   if (Result.getNode())
8168     return Result;
8169
8170   // If that didn't work, try again with the operands commuted.
8171   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8172 }
8173
8174 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8175 ///
8176 static SDValue PerformSUBCombine(SDNode *N,
8177                                  TargetLowering::DAGCombinerInfo &DCI) {
8178   SDValue N0 = N->getOperand(0);
8179   SDValue N1 = N->getOperand(1);
8180
8181   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8182   if (N1.getNode()->hasOneUse()) {
8183     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8184     if (Result.getNode()) return Result;
8185   }
8186
8187   return SDValue();
8188 }
8189
8190 /// PerformVMULCombine
8191 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8192 /// special multiplier accumulator forwarding.
8193 ///   vmul d3, d0, d2
8194 ///   vmla d3, d1, d2
8195 /// is faster than
8196 ///   vadd d3, d0, d1
8197 ///   vmul d3, d3, d2
8198 //  However, for (A + B) * (A + B),
8199 //    vadd d2, d0, d1
8200 //    vmul d3, d0, d2
8201 //    vmla d3, d1, d2
8202 //  is slower than
8203 //    vadd d2, d0, d1
8204 //    vmul d3, d2, d2
8205 static SDValue PerformVMULCombine(SDNode *N,
8206                                   TargetLowering::DAGCombinerInfo &DCI,
8207                                   const ARMSubtarget *Subtarget) {
8208   if (!Subtarget->hasVMLxForwarding())
8209     return SDValue();
8210
8211   SelectionDAG &DAG = DCI.DAG;
8212   SDValue N0 = N->getOperand(0);
8213   SDValue N1 = N->getOperand(1);
8214   unsigned Opcode = N0.getOpcode();
8215   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8216       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8217     Opcode = N1.getOpcode();
8218     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8219         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8220       return SDValue();
8221     std::swap(N0, N1);
8222   }
8223
8224   if (N0 == N1)
8225     return SDValue();
8226
8227   EVT VT = N->getValueType(0);
8228   SDLoc DL(N);
8229   SDValue N00 = N0->getOperand(0);
8230   SDValue N01 = N0->getOperand(1);
8231   return DAG.getNode(Opcode, DL, VT,
8232                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8233                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8234 }
8235
8236 static SDValue PerformMULCombine(SDNode *N,
8237                                  TargetLowering::DAGCombinerInfo &DCI,
8238                                  const ARMSubtarget *Subtarget) {
8239   SelectionDAG &DAG = DCI.DAG;
8240
8241   if (Subtarget->isThumb1Only())
8242     return SDValue();
8243
8244   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8245     return SDValue();
8246
8247   EVT VT = N->getValueType(0);
8248   if (VT.is64BitVector() || VT.is128BitVector())
8249     return PerformVMULCombine(N, DCI, Subtarget);
8250   if (VT != MVT::i32)
8251     return SDValue();
8252
8253   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8254   if (!C)
8255     return SDValue();
8256
8257   int64_t MulAmt = C->getSExtValue();
8258   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8259
8260   ShiftAmt = ShiftAmt & (32 - 1);
8261   SDValue V = N->getOperand(0);
8262   SDLoc DL(N);
8263
8264   SDValue Res;
8265   MulAmt >>= ShiftAmt;
8266
8267   if (MulAmt >= 0) {
8268     if (isPowerOf2_32(MulAmt - 1)) {
8269       // (mul x, 2^N + 1) => (add (shl x, N), x)
8270       Res = DAG.getNode(ISD::ADD, DL, VT,
8271                         V,
8272                         DAG.getNode(ISD::SHL, DL, VT,
8273                                     V,
8274                                     DAG.getConstant(Log2_32(MulAmt - 1),
8275                                                     MVT::i32)));
8276     } else if (isPowerOf2_32(MulAmt + 1)) {
8277       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8278       Res = DAG.getNode(ISD::SUB, DL, VT,
8279                         DAG.getNode(ISD::SHL, DL, VT,
8280                                     V,
8281                                     DAG.getConstant(Log2_32(MulAmt + 1),
8282                                                     MVT::i32)),
8283                         V);
8284     } else
8285       return SDValue();
8286   } else {
8287     uint64_t MulAmtAbs = -MulAmt;
8288     if (isPowerOf2_32(MulAmtAbs + 1)) {
8289       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8290       Res = DAG.getNode(ISD::SUB, DL, VT,
8291                         V,
8292                         DAG.getNode(ISD::SHL, DL, VT,
8293                                     V,
8294                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8295                                                     MVT::i32)));
8296     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8297       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8298       Res = DAG.getNode(ISD::ADD, DL, VT,
8299                         V,
8300                         DAG.getNode(ISD::SHL, DL, VT,
8301                                     V,
8302                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8303                                                     MVT::i32)));
8304       Res = DAG.getNode(ISD::SUB, DL, VT,
8305                         DAG.getConstant(0, MVT::i32),Res);
8306
8307     } else
8308       return SDValue();
8309   }
8310
8311   if (ShiftAmt != 0)
8312     Res = DAG.getNode(ISD::SHL, DL, VT,
8313                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8314
8315   // Do not add new nodes to DAG combiner worklist.
8316   DCI.CombineTo(N, Res, false);
8317   return SDValue();
8318 }
8319
8320 static SDValue PerformANDCombine(SDNode *N,
8321                                  TargetLowering::DAGCombinerInfo &DCI,
8322                                  const ARMSubtarget *Subtarget) {
8323
8324   // Attempt to use immediate-form VBIC
8325   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8326   SDLoc dl(N);
8327   EVT VT = N->getValueType(0);
8328   SelectionDAG &DAG = DCI.DAG;
8329
8330   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8331     return SDValue();
8332
8333   APInt SplatBits, SplatUndef;
8334   unsigned SplatBitSize;
8335   bool HasAnyUndefs;
8336   if (BVN &&
8337       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8338     if (SplatBitSize <= 64) {
8339       EVT VbicVT;
8340       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8341                                       SplatUndef.getZExtValue(), SplatBitSize,
8342                                       DAG, VbicVT, VT.is128BitVector(),
8343                                       OtherModImm);
8344       if (Val.getNode()) {
8345         SDValue Input =
8346           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8347         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8348         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8349       }
8350     }
8351   }
8352
8353   if (!Subtarget->isThumb1Only()) {
8354     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8355     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8356     if (Result.getNode())
8357       return Result;
8358   }
8359
8360   return SDValue();
8361 }
8362
8363 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8364 static SDValue PerformORCombine(SDNode *N,
8365                                 TargetLowering::DAGCombinerInfo &DCI,
8366                                 const ARMSubtarget *Subtarget) {
8367   // Attempt to use immediate-form VORR
8368   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8369   SDLoc dl(N);
8370   EVT VT = N->getValueType(0);
8371   SelectionDAG &DAG = DCI.DAG;
8372
8373   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8374     return SDValue();
8375
8376   APInt SplatBits, SplatUndef;
8377   unsigned SplatBitSize;
8378   bool HasAnyUndefs;
8379   if (BVN && Subtarget->hasNEON() &&
8380       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8381     if (SplatBitSize <= 64) {
8382       EVT VorrVT;
8383       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8384                                       SplatUndef.getZExtValue(), SplatBitSize,
8385                                       DAG, VorrVT, VT.is128BitVector(),
8386                                       OtherModImm);
8387       if (Val.getNode()) {
8388         SDValue Input =
8389           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8390         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8391         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8392       }
8393     }
8394   }
8395
8396   if (!Subtarget->isThumb1Only()) {
8397     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8398     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8399     if (Result.getNode())
8400       return Result;
8401   }
8402
8403   // The code below optimizes (or (and X, Y), Z).
8404   // The AND operand needs to have a single user to make these optimizations
8405   // profitable.
8406   SDValue N0 = N->getOperand(0);
8407   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8408     return SDValue();
8409   SDValue N1 = N->getOperand(1);
8410
8411   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8412   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8413       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8414     APInt SplatUndef;
8415     unsigned SplatBitSize;
8416     bool HasAnyUndefs;
8417
8418     APInt SplatBits0, SplatBits1;
8419     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8420     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8421     // Ensure that the second operand of both ands are constants
8422     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8423                                       HasAnyUndefs) && !HasAnyUndefs) {
8424         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8425                                           HasAnyUndefs) && !HasAnyUndefs) {
8426             // Ensure that the bit width of the constants are the same and that
8427             // the splat arguments are logical inverses as per the pattern we
8428             // are trying to simplify.
8429             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8430                 SplatBits0 == ~SplatBits1) {
8431                 // Canonicalize the vector type to make instruction selection
8432                 // simpler.
8433                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8434                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8435                                              N0->getOperand(1),
8436                                              N0->getOperand(0),
8437                                              N1->getOperand(0));
8438                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8439             }
8440         }
8441     }
8442   }
8443
8444   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8445   // reasonable.
8446
8447   // BFI is only available on V6T2+
8448   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8449     return SDValue();
8450
8451   SDLoc DL(N);
8452   // 1) or (and A, mask), val => ARMbfi A, val, mask
8453   //      iff (val & mask) == val
8454   //
8455   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8456   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8457   //          && mask == ~mask2
8458   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8459   //          && ~mask == mask2
8460   //  (i.e., copy a bitfield value into another bitfield of the same width)
8461
8462   if (VT != MVT::i32)
8463     return SDValue();
8464
8465   SDValue N00 = N0.getOperand(0);
8466
8467   // The value and the mask need to be constants so we can verify this is
8468   // actually a bitfield set. If the mask is 0xffff, we can do better
8469   // via a movt instruction, so don't use BFI in that case.
8470   SDValue MaskOp = N0.getOperand(1);
8471   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8472   if (!MaskC)
8473     return SDValue();
8474   unsigned Mask = MaskC->getZExtValue();
8475   if (Mask == 0xffff)
8476     return SDValue();
8477   SDValue Res;
8478   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8479   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8480   if (N1C) {
8481     unsigned Val = N1C->getZExtValue();
8482     if ((Val & ~Mask) != Val)
8483       return SDValue();
8484
8485     if (ARM::isBitFieldInvertedMask(Mask)) {
8486       Val >>= countTrailingZeros(~Mask);
8487
8488       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8489                         DAG.getConstant(Val, MVT::i32),
8490                         DAG.getConstant(Mask, MVT::i32));
8491
8492       // Do not add new nodes to DAG combiner worklist.
8493       DCI.CombineTo(N, Res, false);
8494       return SDValue();
8495     }
8496   } else if (N1.getOpcode() == ISD::AND) {
8497     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8498     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8499     if (!N11C)
8500       return SDValue();
8501     unsigned Mask2 = N11C->getZExtValue();
8502
8503     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8504     // as is to match.
8505     if (ARM::isBitFieldInvertedMask(Mask) &&
8506         (Mask == ~Mask2)) {
8507       // The pack halfword instruction works better for masks that fit it,
8508       // so use that when it's available.
8509       if (Subtarget->hasT2ExtractPack() &&
8510           (Mask == 0xffff || Mask == 0xffff0000))
8511         return SDValue();
8512       // 2a
8513       unsigned amt = countTrailingZeros(Mask2);
8514       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8515                         DAG.getConstant(amt, MVT::i32));
8516       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8517                         DAG.getConstant(Mask, MVT::i32));
8518       // Do not add new nodes to DAG combiner worklist.
8519       DCI.CombineTo(N, Res, false);
8520       return SDValue();
8521     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8522                (~Mask == Mask2)) {
8523       // The pack halfword instruction works better for masks that fit it,
8524       // so use that when it's available.
8525       if (Subtarget->hasT2ExtractPack() &&
8526           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8527         return SDValue();
8528       // 2b
8529       unsigned lsb = countTrailingZeros(Mask);
8530       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8531                         DAG.getConstant(lsb, MVT::i32));
8532       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8533                         DAG.getConstant(Mask2, MVT::i32));
8534       // Do not add new nodes to DAG combiner worklist.
8535       DCI.CombineTo(N, Res, false);
8536       return SDValue();
8537     }
8538   }
8539
8540   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8541       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8542       ARM::isBitFieldInvertedMask(~Mask)) {
8543     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8544     // where lsb(mask) == #shamt and masked bits of B are known zero.
8545     SDValue ShAmt = N00.getOperand(1);
8546     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8547     unsigned LSB = countTrailingZeros(Mask);
8548     if (ShAmtC != LSB)
8549       return SDValue();
8550
8551     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8552                       DAG.getConstant(~Mask, MVT::i32));
8553
8554     // Do not add new nodes to DAG combiner worklist.
8555     DCI.CombineTo(N, Res, false);
8556   }
8557
8558   return SDValue();
8559 }
8560
8561 static SDValue PerformXORCombine(SDNode *N,
8562                                  TargetLowering::DAGCombinerInfo &DCI,
8563                                  const ARMSubtarget *Subtarget) {
8564   EVT VT = N->getValueType(0);
8565   SelectionDAG &DAG = DCI.DAG;
8566
8567   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8568     return SDValue();
8569
8570   if (!Subtarget->isThumb1Only()) {
8571     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8572     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8573     if (Result.getNode())
8574       return Result;
8575   }
8576
8577   return SDValue();
8578 }
8579
8580 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8581 /// the bits being cleared by the AND are not demanded by the BFI.
8582 static SDValue PerformBFICombine(SDNode *N,
8583                                  TargetLowering::DAGCombinerInfo &DCI) {
8584   SDValue N1 = N->getOperand(1);
8585   if (N1.getOpcode() == ISD::AND) {
8586     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8587     if (!N11C)
8588       return SDValue();
8589     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8590     unsigned LSB = countTrailingZeros(~InvMask);
8591     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8592     assert(Width <
8593                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8594            "undefined behavior");
8595     unsigned Mask = (1u << Width) - 1;
8596     unsigned Mask2 = N11C->getZExtValue();
8597     if ((Mask & (~Mask2)) == 0)
8598       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8599                              N->getOperand(0), N1.getOperand(0),
8600                              N->getOperand(2));
8601   }
8602   return SDValue();
8603 }
8604
8605 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8606 /// ARMISD::VMOVRRD.
8607 static SDValue PerformVMOVRRDCombine(SDNode *N,
8608                                      TargetLowering::DAGCombinerInfo &DCI,
8609                                      const ARMSubtarget *Subtarget) {
8610   // vmovrrd(vmovdrr x, y) -> x,y
8611   SDValue InDouble = N->getOperand(0);
8612   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8613     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8614
8615   // vmovrrd(load f64) -> (load i32), (load i32)
8616   SDNode *InNode = InDouble.getNode();
8617   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8618       InNode->getValueType(0) == MVT::f64 &&
8619       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8620       !cast<LoadSDNode>(InNode)->isVolatile()) {
8621     // TODO: Should this be done for non-FrameIndex operands?
8622     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8623
8624     SelectionDAG &DAG = DCI.DAG;
8625     SDLoc DL(LD);
8626     SDValue BasePtr = LD->getBasePtr();
8627     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8628                                  LD->getPointerInfo(), LD->isVolatile(),
8629                                  LD->isNonTemporal(), LD->isInvariant(),
8630                                  LD->getAlignment());
8631
8632     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8633                                     DAG.getConstant(4, MVT::i32));
8634     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8635                                  LD->getPointerInfo(), LD->isVolatile(),
8636                                  LD->isNonTemporal(), LD->isInvariant(),
8637                                  std::min(4U, LD->getAlignment() / 2));
8638
8639     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8640     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8641       std::swap (NewLD1, NewLD2);
8642     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8643     return Result;
8644   }
8645
8646   return SDValue();
8647 }
8648
8649 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8650 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8651 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8652   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8653   SDValue Op0 = N->getOperand(0);
8654   SDValue Op1 = N->getOperand(1);
8655   if (Op0.getOpcode() == ISD::BITCAST)
8656     Op0 = Op0.getOperand(0);
8657   if (Op1.getOpcode() == ISD::BITCAST)
8658     Op1 = Op1.getOperand(0);
8659   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8660       Op0.getNode() == Op1.getNode() &&
8661       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8662     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8663                        N->getValueType(0), Op0.getOperand(0));
8664   return SDValue();
8665 }
8666
8667 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8668 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8669 /// i64 vector to have f64 elements, since the value can then be loaded
8670 /// directly into a VFP register.
8671 static bool hasNormalLoadOperand(SDNode *N) {
8672   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8673   for (unsigned i = 0; i < NumElts; ++i) {
8674     SDNode *Elt = N->getOperand(i).getNode();
8675     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8676       return true;
8677   }
8678   return false;
8679 }
8680
8681 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8682 /// ISD::BUILD_VECTOR.
8683 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8684                                           TargetLowering::DAGCombinerInfo &DCI,
8685                                           const ARMSubtarget *Subtarget) {
8686   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8687   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8688   // into a pair of GPRs, which is fine when the value is used as a scalar,
8689   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8690   SelectionDAG &DAG = DCI.DAG;
8691   if (N->getNumOperands() == 2) {
8692     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8693     if (RV.getNode())
8694       return RV;
8695   }
8696
8697   // Load i64 elements as f64 values so that type legalization does not split
8698   // them up into i32 values.
8699   EVT VT = N->getValueType(0);
8700   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8701     return SDValue();
8702   SDLoc dl(N);
8703   SmallVector<SDValue, 8> Ops;
8704   unsigned NumElts = VT.getVectorNumElements();
8705   for (unsigned i = 0; i < NumElts; ++i) {
8706     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8707     Ops.push_back(V);
8708     // Make the DAGCombiner fold the bitcast.
8709     DCI.AddToWorklist(V.getNode());
8710   }
8711   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8712   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8713   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8714 }
8715
8716 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8717 static SDValue
8718 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8719   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8720   // At that time, we may have inserted bitcasts from integer to float.
8721   // If these bitcasts have survived DAGCombine, change the lowering of this
8722   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8723   // force to use floating point types.
8724
8725   // Make sure we can change the type of the vector.
8726   // This is possible iff:
8727   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8728   //    1.1. Vector is used only once.
8729   //    1.2. Use is a bit convert to an integer type.
8730   // 2. The size of its operands are 32-bits (64-bits are not legal).
8731   EVT VT = N->getValueType(0);
8732   EVT EltVT = VT.getVectorElementType();
8733
8734   // Check 1.1. and 2.
8735   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8736     return SDValue();
8737
8738   // By construction, the input type must be float.
8739   assert(EltVT == MVT::f32 && "Unexpected type!");
8740
8741   // Check 1.2.
8742   SDNode *Use = *N->use_begin();
8743   if (Use->getOpcode() != ISD::BITCAST ||
8744       Use->getValueType(0).isFloatingPoint())
8745     return SDValue();
8746
8747   // Check profitability.
8748   // Model is, if more than half of the relevant operands are bitcast from
8749   // i32, turn the build_vector into a sequence of insert_vector_elt.
8750   // Relevant operands are everything that is not statically
8751   // (i.e., at compile time) bitcasted.
8752   unsigned NumOfBitCastedElts = 0;
8753   unsigned NumElts = VT.getVectorNumElements();
8754   unsigned NumOfRelevantElts = NumElts;
8755   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8756     SDValue Elt = N->getOperand(Idx);
8757     if (Elt->getOpcode() == ISD::BITCAST) {
8758       // Assume only bit cast to i32 will go away.
8759       if (Elt->getOperand(0).getValueType() == MVT::i32)
8760         ++NumOfBitCastedElts;
8761     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8762       // Constants are statically casted, thus do not count them as
8763       // relevant operands.
8764       --NumOfRelevantElts;
8765   }
8766
8767   // Check if more than half of the elements require a non-free bitcast.
8768   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8769     return SDValue();
8770
8771   SelectionDAG &DAG = DCI.DAG;
8772   // Create the new vector type.
8773   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8774   // Check if the type is legal.
8775   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8776   if (!TLI.isTypeLegal(VecVT))
8777     return SDValue();
8778
8779   // Combine:
8780   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8781   // => BITCAST INSERT_VECTOR_ELT
8782   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8783   //                      (BITCAST EN), N.
8784   SDValue Vec = DAG.getUNDEF(VecVT);
8785   SDLoc dl(N);
8786   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8787     SDValue V = N->getOperand(Idx);
8788     if (V.getOpcode() == ISD::UNDEF)
8789       continue;
8790     if (V.getOpcode() == ISD::BITCAST &&
8791         V->getOperand(0).getValueType() == MVT::i32)
8792       // Fold obvious case.
8793       V = V.getOperand(0);
8794     else {
8795       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8796       // Make the DAGCombiner fold the bitcasts.
8797       DCI.AddToWorklist(V.getNode());
8798     }
8799     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8800     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8801   }
8802   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8803   // Make the DAGCombiner fold the bitcasts.
8804   DCI.AddToWorklist(Vec.getNode());
8805   return Vec;
8806 }
8807
8808 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8809 /// ISD::INSERT_VECTOR_ELT.
8810 static SDValue PerformInsertEltCombine(SDNode *N,
8811                                        TargetLowering::DAGCombinerInfo &DCI) {
8812   // Bitcast an i64 load inserted into a vector to f64.
8813   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8814   EVT VT = N->getValueType(0);
8815   SDNode *Elt = N->getOperand(1).getNode();
8816   if (VT.getVectorElementType() != MVT::i64 ||
8817       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8818     return SDValue();
8819
8820   SelectionDAG &DAG = DCI.DAG;
8821   SDLoc dl(N);
8822   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8823                                  VT.getVectorNumElements());
8824   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8825   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8826   // Make the DAGCombiner fold the bitcasts.
8827   DCI.AddToWorklist(Vec.getNode());
8828   DCI.AddToWorklist(V.getNode());
8829   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8830                                Vec, V, N->getOperand(2));
8831   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8832 }
8833
8834 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8835 /// ISD::VECTOR_SHUFFLE.
8836 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8837   // The LLVM shufflevector instruction does not require the shuffle mask
8838   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8839   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8840   // operands do not match the mask length, they are extended by concatenating
8841   // them with undef vectors.  That is probably the right thing for other
8842   // targets, but for NEON it is better to concatenate two double-register
8843   // size vector operands into a single quad-register size vector.  Do that
8844   // transformation here:
8845   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8846   //   shuffle(concat(v1, v2), undef)
8847   SDValue Op0 = N->getOperand(0);
8848   SDValue Op1 = N->getOperand(1);
8849   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8850       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8851       Op0.getNumOperands() != 2 ||
8852       Op1.getNumOperands() != 2)
8853     return SDValue();
8854   SDValue Concat0Op1 = Op0.getOperand(1);
8855   SDValue Concat1Op1 = Op1.getOperand(1);
8856   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8857       Concat1Op1.getOpcode() != ISD::UNDEF)
8858     return SDValue();
8859   // Skip the transformation if any of the types are illegal.
8860   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8861   EVT VT = N->getValueType(0);
8862   if (!TLI.isTypeLegal(VT) ||
8863       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8864       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8865     return SDValue();
8866
8867   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8868                                   Op0.getOperand(0), Op1.getOperand(0));
8869   // Translate the shuffle mask.
8870   SmallVector<int, 16> NewMask;
8871   unsigned NumElts = VT.getVectorNumElements();
8872   unsigned HalfElts = NumElts/2;
8873   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8874   for (unsigned n = 0; n < NumElts; ++n) {
8875     int MaskElt = SVN->getMaskElt(n);
8876     int NewElt = -1;
8877     if (MaskElt < (int)HalfElts)
8878       NewElt = MaskElt;
8879     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8880       NewElt = HalfElts + MaskElt - NumElts;
8881     NewMask.push_back(NewElt);
8882   }
8883   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8884                               DAG.getUNDEF(VT), NewMask.data());
8885 }
8886
8887 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8888 /// NEON load/store intrinsics to merge base address updates.
8889 static SDValue CombineBaseUpdate(SDNode *N,
8890                                  TargetLowering::DAGCombinerInfo &DCI) {
8891   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8892     return SDValue();
8893
8894   SelectionDAG &DAG = DCI.DAG;
8895   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8896                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8897   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8898   SDValue Addr = N->getOperand(AddrOpIdx);
8899
8900   // Search for a use of the address operand that is an increment.
8901   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8902          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8903     SDNode *User = *UI;
8904     if (User->getOpcode() != ISD::ADD ||
8905         UI.getUse().getResNo() != Addr.getResNo())
8906       continue;
8907
8908     // Check that the add is independent of the load/store.  Otherwise, folding
8909     // it would create a cycle.
8910     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8911       continue;
8912
8913     // Find the new opcode for the updating load/store.
8914     bool isLoad = true;
8915     bool isLaneOp = false;
8916     unsigned NewOpc = 0;
8917     unsigned NumVecs = 0;
8918     if (isIntrinsic) {
8919       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8920       switch (IntNo) {
8921       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8922       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8923         NumVecs = 1; break;
8924       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8925         NumVecs = 2; break;
8926       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8927         NumVecs = 3; break;
8928       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8929         NumVecs = 4; break;
8930       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8931         NumVecs = 2; isLaneOp = true; break;
8932       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8933         NumVecs = 3; isLaneOp = true; break;
8934       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8935         NumVecs = 4; isLaneOp = true; break;
8936       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8937         NumVecs = 1; isLoad = false; break;
8938       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8939         NumVecs = 2; isLoad = false; break;
8940       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8941         NumVecs = 3; isLoad = false; break;
8942       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8943         NumVecs = 4; isLoad = false; break;
8944       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8945         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8946       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8947         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8948       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8949         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8950       }
8951     } else {
8952       isLaneOp = true;
8953       switch (N->getOpcode()) {
8954       default: llvm_unreachable("unexpected opcode for Neon base update");
8955       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8956       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8957       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8958       }
8959     }
8960
8961     // Find the size of memory referenced by the load/store.
8962     EVT VecTy;
8963     if (isLoad)
8964       VecTy = N->getValueType(0);
8965     else
8966       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8967     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8968     if (isLaneOp)
8969       NumBytes /= VecTy.getVectorNumElements();
8970
8971     // If the increment is a constant, it must match the memory ref size.
8972     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8973     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8974       uint64_t IncVal = CInc->getZExtValue();
8975       if (IncVal != NumBytes)
8976         continue;
8977     } else if (NumBytes >= 3 * 16) {
8978       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8979       // separate instructions that make it harder to use a non-constant update.
8980       continue;
8981     }
8982
8983     // Create the new updating load/store node.
8984     EVT Tys[6];
8985     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8986     unsigned n;
8987     for (n = 0; n < NumResultVecs; ++n)
8988       Tys[n] = VecTy;
8989     Tys[n++] = MVT::i32;
8990     Tys[n] = MVT::Other;
8991     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
8992     SmallVector<SDValue, 8> Ops;
8993     Ops.push_back(N->getOperand(0)); // incoming chain
8994     Ops.push_back(N->getOperand(AddrOpIdx));
8995     Ops.push_back(Inc);
8996     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8997       Ops.push_back(N->getOperand(i));
8998     }
8999     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9000     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9001                                            Ops, MemInt->getMemoryVT(),
9002                                            MemInt->getMemOperand());
9003
9004     // Update the uses.
9005     std::vector<SDValue> NewResults;
9006     for (unsigned i = 0; i < NumResultVecs; ++i) {
9007       NewResults.push_back(SDValue(UpdN.getNode(), i));
9008     }
9009     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9010     DCI.CombineTo(N, NewResults);
9011     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9012
9013     break;
9014   }
9015   return SDValue();
9016 }
9017
9018 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9019 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9020 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9021 /// return true.
9022 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9023   SelectionDAG &DAG = DCI.DAG;
9024   EVT VT = N->getValueType(0);
9025   // vldN-dup instructions only support 64-bit vectors for N > 1.
9026   if (!VT.is64BitVector())
9027     return false;
9028
9029   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9030   SDNode *VLD = N->getOperand(0).getNode();
9031   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9032     return false;
9033   unsigned NumVecs = 0;
9034   unsigned NewOpc = 0;
9035   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9036   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9037     NumVecs = 2;
9038     NewOpc = ARMISD::VLD2DUP;
9039   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9040     NumVecs = 3;
9041     NewOpc = ARMISD::VLD3DUP;
9042   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9043     NumVecs = 4;
9044     NewOpc = ARMISD::VLD4DUP;
9045   } else {
9046     return false;
9047   }
9048
9049   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9050   // numbers match the load.
9051   unsigned VLDLaneNo =
9052     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9053   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9054        UI != UE; ++UI) {
9055     // Ignore uses of the chain result.
9056     if (UI.getUse().getResNo() == NumVecs)
9057       continue;
9058     SDNode *User = *UI;
9059     if (User->getOpcode() != ARMISD::VDUPLANE ||
9060         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9061       return false;
9062   }
9063
9064   // Create the vldN-dup node.
9065   EVT Tys[5];
9066   unsigned n;
9067   for (n = 0; n < NumVecs; ++n)
9068     Tys[n] = VT;
9069   Tys[n] = MVT::Other;
9070   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9071   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9072   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9073   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9074                                            Ops, VLDMemInt->getMemoryVT(),
9075                                            VLDMemInt->getMemOperand());
9076
9077   // Update the uses.
9078   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9079        UI != UE; ++UI) {
9080     unsigned ResNo = UI.getUse().getResNo();
9081     // Ignore uses of the chain result.
9082     if (ResNo == NumVecs)
9083       continue;
9084     SDNode *User = *UI;
9085     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9086   }
9087
9088   // Now the vldN-lane intrinsic is dead except for its chain result.
9089   // Update uses of the chain.
9090   std::vector<SDValue> VLDDupResults;
9091   for (unsigned n = 0; n < NumVecs; ++n)
9092     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9093   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9094   DCI.CombineTo(VLD, VLDDupResults);
9095
9096   return true;
9097 }
9098
9099 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9100 /// ARMISD::VDUPLANE.
9101 static SDValue PerformVDUPLANECombine(SDNode *N,
9102                                       TargetLowering::DAGCombinerInfo &DCI) {
9103   SDValue Op = N->getOperand(0);
9104
9105   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9106   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9107   if (CombineVLDDUP(N, DCI))
9108     return SDValue(N, 0);
9109
9110   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9111   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9112   while (Op.getOpcode() == ISD::BITCAST)
9113     Op = Op.getOperand(0);
9114   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9115     return SDValue();
9116
9117   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9118   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9119   // The canonical VMOV for a zero vector uses a 32-bit element size.
9120   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9121   unsigned EltBits;
9122   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9123     EltSize = 8;
9124   EVT VT = N->getValueType(0);
9125   if (EltSize > VT.getVectorElementType().getSizeInBits())
9126     return SDValue();
9127
9128   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9129 }
9130
9131 /// PerformSTORECombine - Target-specific dag combine xforms for
9132 /// ISD::STORE.
9133 static SDValue PerformSTORECombine(SDNode *N,
9134                                    TargetLowering::DAGCombinerInfo &DCI) {
9135   StoreSDNode *St = cast<StoreSDNode>(N);
9136   if (St->isVolatile())
9137     return SDValue();
9138
9139   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9140   // pack all of the elements in one place.  Next, store to memory in fewer
9141   // chunks.
9142   SDValue StVal = St->getValue();
9143   EVT VT = StVal.getValueType();
9144   if (St->isTruncatingStore() && VT.isVector()) {
9145     SelectionDAG &DAG = DCI.DAG;
9146     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9147     EVT StVT = St->getMemoryVT();
9148     unsigned NumElems = VT.getVectorNumElements();
9149     assert(StVT != VT && "Cannot truncate to the same type");
9150     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9151     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9152
9153     // From, To sizes and ElemCount must be pow of two
9154     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9155
9156     // We are going to use the original vector elt for storing.
9157     // Accumulated smaller vector elements must be a multiple of the store size.
9158     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9159
9160     unsigned SizeRatio  = FromEltSz / ToEltSz;
9161     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9162
9163     // Create a type on which we perform the shuffle.
9164     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9165                                      NumElems*SizeRatio);
9166     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9167
9168     SDLoc DL(St);
9169     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9170     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9171     for (unsigned i = 0; i < NumElems; ++i)
9172       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9173
9174     // Can't shuffle using an illegal type.
9175     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9176
9177     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9178                                 DAG.getUNDEF(WideVec.getValueType()),
9179                                 ShuffleVec.data());
9180     // At this point all of the data is stored at the bottom of the
9181     // register. We now need to save it to mem.
9182
9183     // Find the largest store unit
9184     MVT StoreType = MVT::i8;
9185     for (MVT Tp : MVT::integer_valuetypes()) {
9186       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9187         StoreType = Tp;
9188     }
9189     // Didn't find a legal store type.
9190     if (!TLI.isTypeLegal(StoreType))
9191       return SDValue();
9192
9193     // Bitcast the original vector into a vector of store-size units
9194     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9195             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9196     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9197     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9198     SmallVector<SDValue, 8> Chains;
9199     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9200                                         TLI.getPointerTy());
9201     SDValue BasePtr = St->getBasePtr();
9202
9203     // Perform one or more big stores into memory.
9204     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9205     for (unsigned I = 0; I < E; I++) {
9206       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9207                                    StoreType, ShuffWide,
9208                                    DAG.getIntPtrConstant(I));
9209       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9210                                 St->getPointerInfo(), St->isVolatile(),
9211                                 St->isNonTemporal(), St->getAlignment());
9212       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9213                             Increment);
9214       Chains.push_back(Ch);
9215     }
9216     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9217   }
9218
9219   if (!ISD::isNormalStore(St))
9220     return SDValue();
9221
9222   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9223   // ARM stores of arguments in the same cache line.
9224   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9225       StVal.getNode()->hasOneUse()) {
9226     SelectionDAG  &DAG = DCI.DAG;
9227     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9228     SDLoc DL(St);
9229     SDValue BasePtr = St->getBasePtr();
9230     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9231                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9232                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9233                                   St->isNonTemporal(), St->getAlignment());
9234
9235     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9236                                     DAG.getConstant(4, MVT::i32));
9237     return DAG.getStore(NewST1.getValue(0), DL,
9238                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9239                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9240                         St->isNonTemporal(),
9241                         std::min(4U, St->getAlignment() / 2));
9242   }
9243
9244   if (StVal.getValueType() == MVT::i64 &&
9245       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9246
9247     // Bitcast an i64 store extracted from a vector to f64.
9248     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9249     SelectionDAG &DAG = DCI.DAG;
9250     SDLoc dl(StVal);
9251     SDValue IntVec = StVal.getOperand(0);
9252     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9253                                    IntVec.getValueType().getVectorNumElements());
9254     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9255     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9256                                  Vec, StVal.getOperand(1));
9257     dl = SDLoc(N);
9258     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9259     // Make the DAGCombiner fold the bitcasts.
9260     DCI.AddToWorklist(Vec.getNode());
9261     DCI.AddToWorklist(ExtElt.getNode());
9262     DCI.AddToWorklist(V.getNode());
9263     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9264                         St->getPointerInfo(), St->isVolatile(),
9265                         St->isNonTemporal(), St->getAlignment(),
9266                         St->getAAInfo());
9267   }
9268
9269   return SDValue();
9270 }
9271
9272 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9273 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9274 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9275 {
9276   integerPart cN;
9277   integerPart c0 = 0;
9278   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9279        I != E; I++) {
9280     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9281     if (!C)
9282       return false;
9283
9284     bool isExact;
9285     APFloat APF = C->getValueAPF();
9286     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9287         != APFloat::opOK || !isExact)
9288       return false;
9289
9290     c0 = (I == 0) ? cN : c0;
9291     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9292       return false;
9293   }
9294   C = c0;
9295   return true;
9296 }
9297
9298 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9299 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9300 /// when the VMUL has a constant operand that is a power of 2.
9301 ///
9302 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9303 ///  vmul.f32        d16, d17, d16
9304 ///  vcvt.s32.f32    d16, d16
9305 /// becomes:
9306 ///  vcvt.s32.f32    d16, d16, #3
9307 static SDValue PerformVCVTCombine(SDNode *N,
9308                                   TargetLowering::DAGCombinerInfo &DCI,
9309                                   const ARMSubtarget *Subtarget) {
9310   SelectionDAG &DAG = DCI.DAG;
9311   SDValue Op = N->getOperand(0);
9312
9313   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9314       Op.getOpcode() != ISD::FMUL)
9315     return SDValue();
9316
9317   uint64_t C;
9318   SDValue N0 = Op->getOperand(0);
9319   SDValue ConstVec = Op->getOperand(1);
9320   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9321
9322   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9323       !isConstVecPow2(ConstVec, isSigned, C))
9324     return SDValue();
9325
9326   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9327   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9328   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9329   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9330       NumLanes > 4) {
9331     // These instructions only exist converting from f32 to i32. We can handle
9332     // smaller integers by generating an extra truncate, but larger ones would
9333     // be lossy. We also can't handle more then 4 lanes, since these intructions
9334     // only support v2i32/v4i32 types.
9335     return SDValue();
9336   }
9337
9338   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9339     Intrinsic::arm_neon_vcvtfp2fxu;
9340   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9341                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9342                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9343                                  DAG.getConstant(Log2_64(C), MVT::i32));
9344
9345   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9346     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9347
9348   return FixConv;
9349 }
9350
9351 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9352 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9353 /// when the VDIV has a constant operand that is a power of 2.
9354 ///
9355 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9356 ///  vcvt.f32.s32    d16, d16
9357 ///  vdiv.f32        d16, d17, d16
9358 /// becomes:
9359 ///  vcvt.f32.s32    d16, d16, #3
9360 static SDValue PerformVDIVCombine(SDNode *N,
9361                                   TargetLowering::DAGCombinerInfo &DCI,
9362                                   const ARMSubtarget *Subtarget) {
9363   SelectionDAG &DAG = DCI.DAG;
9364   SDValue Op = N->getOperand(0);
9365   unsigned OpOpcode = Op.getNode()->getOpcode();
9366
9367   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9368       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9369     return SDValue();
9370
9371   uint64_t C;
9372   SDValue ConstVec = N->getOperand(1);
9373   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9374
9375   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9376       !isConstVecPow2(ConstVec, isSigned, C))
9377     return SDValue();
9378
9379   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9380   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9381   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9382     // These instructions only exist converting from i32 to f32. We can handle
9383     // smaller integers by generating an extra extend, but larger ones would
9384     // be lossy.
9385     return SDValue();
9386   }
9387
9388   SDValue ConvInput = Op.getOperand(0);
9389   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9390   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9391     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9392                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9393                             ConvInput);
9394
9395   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9396     Intrinsic::arm_neon_vcvtfxu2fp;
9397   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9398                      Op.getValueType(),
9399                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9400                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9401 }
9402
9403 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9404 /// operand of a vector shift operation, where all the elements of the
9405 /// build_vector must have the same constant integer value.
9406 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9407   // Ignore bit_converts.
9408   while (Op.getOpcode() == ISD::BITCAST)
9409     Op = Op.getOperand(0);
9410   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9411   APInt SplatBits, SplatUndef;
9412   unsigned SplatBitSize;
9413   bool HasAnyUndefs;
9414   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9415                                       HasAnyUndefs, ElementBits) ||
9416       SplatBitSize > ElementBits)
9417     return false;
9418   Cnt = SplatBits.getSExtValue();
9419   return true;
9420 }
9421
9422 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9423 /// operand of a vector shift left operation.  That value must be in the range:
9424 ///   0 <= Value < ElementBits for a left shift; or
9425 ///   0 <= Value <= ElementBits for a long left shift.
9426 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, 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   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9432 }
9433
9434 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9435 /// operand of a vector shift right operation.  For a shift opcode, the value
9436 /// is positive, but for an intrinsic the value count must be negative. The
9437 /// absolute value must be in the range:
9438 ///   1 <= |Value| <= ElementBits for a right shift; or
9439 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9440 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9441                          int64_t &Cnt) {
9442   assert(VT.isVector() && "vector shift count is not a vector type");
9443   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9444   if (! getVShiftImm(Op, ElementBits, Cnt))
9445     return false;
9446   if (isIntrinsic)
9447     Cnt = -Cnt;
9448   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9449 }
9450
9451 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9452 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9453   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9454   switch (IntNo) {
9455   default:
9456     // Don't do anything for most intrinsics.
9457     break;
9458
9459   // Vector shifts: check for immediate versions and lower them.
9460   // Note: This is done during DAG combining instead of DAG legalizing because
9461   // the build_vectors for 64-bit vector element shift counts are generally
9462   // not legal, and it is hard to see their values after they get legalized to
9463   // loads from a constant pool.
9464   case Intrinsic::arm_neon_vshifts:
9465   case Intrinsic::arm_neon_vshiftu:
9466   case Intrinsic::arm_neon_vrshifts:
9467   case Intrinsic::arm_neon_vrshiftu:
9468   case Intrinsic::arm_neon_vrshiftn:
9469   case Intrinsic::arm_neon_vqshifts:
9470   case Intrinsic::arm_neon_vqshiftu:
9471   case Intrinsic::arm_neon_vqshiftsu:
9472   case Intrinsic::arm_neon_vqshiftns:
9473   case Intrinsic::arm_neon_vqshiftnu:
9474   case Intrinsic::arm_neon_vqshiftnsu:
9475   case Intrinsic::arm_neon_vqrshiftns:
9476   case Intrinsic::arm_neon_vqrshiftnu:
9477   case Intrinsic::arm_neon_vqrshiftnsu: {
9478     EVT VT = N->getOperand(1).getValueType();
9479     int64_t Cnt;
9480     unsigned VShiftOpc = 0;
9481
9482     switch (IntNo) {
9483     case Intrinsic::arm_neon_vshifts:
9484     case Intrinsic::arm_neon_vshiftu:
9485       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9486         VShiftOpc = ARMISD::VSHL;
9487         break;
9488       }
9489       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9490         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9491                      ARMISD::VSHRs : ARMISD::VSHRu);
9492         break;
9493       }
9494       return SDValue();
9495
9496     case Intrinsic::arm_neon_vrshifts:
9497     case Intrinsic::arm_neon_vrshiftu:
9498       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9499         break;
9500       return SDValue();
9501
9502     case Intrinsic::arm_neon_vqshifts:
9503     case Intrinsic::arm_neon_vqshiftu:
9504       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9505         break;
9506       return SDValue();
9507
9508     case Intrinsic::arm_neon_vqshiftsu:
9509       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9510         break;
9511       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9512
9513     case Intrinsic::arm_neon_vrshiftn:
9514     case Intrinsic::arm_neon_vqshiftns:
9515     case Intrinsic::arm_neon_vqshiftnu:
9516     case Intrinsic::arm_neon_vqshiftnsu:
9517     case Intrinsic::arm_neon_vqrshiftns:
9518     case Intrinsic::arm_neon_vqrshiftnu:
9519     case Intrinsic::arm_neon_vqrshiftnsu:
9520       // Narrowing shifts require an immediate right shift.
9521       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9522         break;
9523       llvm_unreachable("invalid shift count for narrowing vector shift "
9524                        "intrinsic");
9525
9526     default:
9527       llvm_unreachable("unhandled vector shift");
9528     }
9529
9530     switch (IntNo) {
9531     case Intrinsic::arm_neon_vshifts:
9532     case Intrinsic::arm_neon_vshiftu:
9533       // Opcode already set above.
9534       break;
9535     case Intrinsic::arm_neon_vrshifts:
9536       VShiftOpc = ARMISD::VRSHRs; break;
9537     case Intrinsic::arm_neon_vrshiftu:
9538       VShiftOpc = ARMISD::VRSHRu; break;
9539     case Intrinsic::arm_neon_vrshiftn:
9540       VShiftOpc = ARMISD::VRSHRN; break;
9541     case Intrinsic::arm_neon_vqshifts:
9542       VShiftOpc = ARMISD::VQSHLs; break;
9543     case Intrinsic::arm_neon_vqshiftu:
9544       VShiftOpc = ARMISD::VQSHLu; break;
9545     case Intrinsic::arm_neon_vqshiftsu:
9546       VShiftOpc = ARMISD::VQSHLsu; break;
9547     case Intrinsic::arm_neon_vqshiftns:
9548       VShiftOpc = ARMISD::VQSHRNs; break;
9549     case Intrinsic::arm_neon_vqshiftnu:
9550       VShiftOpc = ARMISD::VQSHRNu; break;
9551     case Intrinsic::arm_neon_vqshiftnsu:
9552       VShiftOpc = ARMISD::VQSHRNsu; break;
9553     case Intrinsic::arm_neon_vqrshiftns:
9554       VShiftOpc = ARMISD::VQRSHRNs; break;
9555     case Intrinsic::arm_neon_vqrshiftnu:
9556       VShiftOpc = ARMISD::VQRSHRNu; break;
9557     case Intrinsic::arm_neon_vqrshiftnsu:
9558       VShiftOpc = ARMISD::VQRSHRNsu; break;
9559     }
9560
9561     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9562                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9563   }
9564
9565   case Intrinsic::arm_neon_vshiftins: {
9566     EVT VT = N->getOperand(1).getValueType();
9567     int64_t Cnt;
9568     unsigned VShiftOpc = 0;
9569
9570     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9571       VShiftOpc = ARMISD::VSLI;
9572     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9573       VShiftOpc = ARMISD::VSRI;
9574     else {
9575       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9576     }
9577
9578     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9579                        N->getOperand(1), N->getOperand(2),
9580                        DAG.getConstant(Cnt, MVT::i32));
9581   }
9582
9583   case Intrinsic::arm_neon_vqrshifts:
9584   case Intrinsic::arm_neon_vqrshiftu:
9585     // No immediate versions of these to check for.
9586     break;
9587   }
9588
9589   return SDValue();
9590 }
9591
9592 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9593 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9594 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9595 /// vector element shift counts are generally not legal, and it is hard to see
9596 /// their values after they get legalized to loads from a constant pool.
9597 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9598                                    const ARMSubtarget *ST) {
9599   EVT VT = N->getValueType(0);
9600   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9601     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9602     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9603     SDValue N1 = N->getOperand(1);
9604     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9605       SDValue N0 = N->getOperand(0);
9606       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9607           DAG.MaskedValueIsZero(N0.getOperand(0),
9608                                 APInt::getHighBitsSet(32, 16)))
9609         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9610     }
9611   }
9612
9613   // Nothing to be done for scalar shifts.
9614   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9615   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9616     return SDValue();
9617
9618   assert(ST->hasNEON() && "unexpected vector shift");
9619   int64_t Cnt;
9620
9621   switch (N->getOpcode()) {
9622   default: llvm_unreachable("unexpected shift opcode");
9623
9624   case ISD::SHL:
9625     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9626       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9627                          DAG.getConstant(Cnt, MVT::i32));
9628     break;
9629
9630   case ISD::SRA:
9631   case ISD::SRL:
9632     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9633       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9634                             ARMISD::VSHRs : ARMISD::VSHRu);
9635       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9636                          DAG.getConstant(Cnt, MVT::i32));
9637     }
9638   }
9639   return SDValue();
9640 }
9641
9642 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9643 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9644 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9645                                     const ARMSubtarget *ST) {
9646   SDValue N0 = N->getOperand(0);
9647
9648   // Check for sign- and zero-extensions of vector extract operations of 8-
9649   // and 16-bit vector elements.  NEON supports these directly.  They are
9650   // handled during DAG combining because type legalization will promote them
9651   // to 32-bit types and it is messy to recognize the operations after that.
9652   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9653     SDValue Vec = N0.getOperand(0);
9654     SDValue Lane = N0.getOperand(1);
9655     EVT VT = N->getValueType(0);
9656     EVT EltVT = N0.getValueType();
9657     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9658
9659     if (VT == MVT::i32 &&
9660         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9661         TLI.isTypeLegal(Vec.getValueType()) &&
9662         isa<ConstantSDNode>(Lane)) {
9663
9664       unsigned Opc = 0;
9665       switch (N->getOpcode()) {
9666       default: llvm_unreachable("unexpected opcode");
9667       case ISD::SIGN_EXTEND:
9668         Opc = ARMISD::VGETLANEs;
9669         break;
9670       case ISD::ZERO_EXTEND:
9671       case ISD::ANY_EXTEND:
9672         Opc = ARMISD::VGETLANEu;
9673         break;
9674       }
9675       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9676     }
9677   }
9678
9679   return SDValue();
9680 }
9681
9682 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9683 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9684 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9685                                        const ARMSubtarget *ST) {
9686   // If the target supports NEON, try to use vmax/vmin instructions for f32
9687   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9688   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9689   // a NaN; only do the transformation when it matches that behavior.
9690
9691   // For now only do this when using NEON for FP operations; if using VFP, it
9692   // is not obvious that the benefit outweighs the cost of switching to the
9693   // NEON pipeline.
9694   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9695       N->getValueType(0) != MVT::f32)
9696     return SDValue();
9697
9698   SDValue CondLHS = N->getOperand(0);
9699   SDValue CondRHS = N->getOperand(1);
9700   SDValue LHS = N->getOperand(2);
9701   SDValue RHS = N->getOperand(3);
9702   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9703
9704   unsigned Opcode = 0;
9705   bool IsReversed;
9706   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9707     IsReversed = false; // x CC y ? x : y
9708   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9709     IsReversed = true ; // x CC y ? y : x
9710   } else {
9711     return SDValue();
9712   }
9713
9714   bool IsUnordered;
9715   switch (CC) {
9716   default: break;
9717   case ISD::SETOLT:
9718   case ISD::SETOLE:
9719   case ISD::SETLT:
9720   case ISD::SETLE:
9721   case ISD::SETULT:
9722   case ISD::SETULE:
9723     // If LHS is NaN, an ordered comparison will be false and the result will
9724     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9725     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9726     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9727     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9728       break;
9729     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9730     // will return -0, so vmin can only be used for unsafe math or if one of
9731     // the operands is known to be nonzero.
9732     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9733         !DAG.getTarget().Options.UnsafeFPMath &&
9734         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9735       break;
9736     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9737     break;
9738
9739   case ISD::SETOGT:
9740   case ISD::SETOGE:
9741   case ISD::SETGT:
9742   case ISD::SETGE:
9743   case ISD::SETUGT:
9744   case ISD::SETUGE:
9745     // If LHS is NaN, an ordered comparison will be false and the result will
9746     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9747     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9748     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9749     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9750       break;
9751     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9752     // will return +0, so vmax can only be used for unsafe math or if one of
9753     // the operands is known to be nonzero.
9754     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9755         !DAG.getTarget().Options.UnsafeFPMath &&
9756         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9757       break;
9758     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9759     break;
9760   }
9761
9762   if (!Opcode)
9763     return SDValue();
9764   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9765 }
9766
9767 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9768 SDValue
9769 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9770   SDValue Cmp = N->getOperand(4);
9771   if (Cmp.getOpcode() != ARMISD::CMPZ)
9772     // Only looking at EQ and NE cases.
9773     return SDValue();
9774
9775   EVT VT = N->getValueType(0);
9776   SDLoc dl(N);
9777   SDValue LHS = Cmp.getOperand(0);
9778   SDValue RHS = Cmp.getOperand(1);
9779   SDValue FalseVal = N->getOperand(0);
9780   SDValue TrueVal = N->getOperand(1);
9781   SDValue ARMcc = N->getOperand(2);
9782   ARMCC::CondCodes CC =
9783     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9784
9785   // Simplify
9786   //   mov     r1, r0
9787   //   cmp     r1, x
9788   //   mov     r0, y
9789   //   moveq   r0, x
9790   // to
9791   //   cmp     r0, x
9792   //   movne   r0, y
9793   //
9794   //   mov     r1, r0
9795   //   cmp     r1, x
9796   //   mov     r0, x
9797   //   movne   r0, y
9798   // to
9799   //   cmp     r0, x
9800   //   movne   r0, y
9801   /// FIXME: Turn this into a target neutral optimization?
9802   SDValue Res;
9803   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9804     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9805                       N->getOperand(3), Cmp);
9806   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9807     SDValue ARMcc;
9808     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9809     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9810                       N->getOperand(3), NewCmp);
9811   }
9812
9813   if (Res.getNode()) {
9814     APInt KnownZero, KnownOne;
9815     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9816     // Capture demanded bits information that would be otherwise lost.
9817     if (KnownZero == 0xfffffffe)
9818       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9819                         DAG.getValueType(MVT::i1));
9820     else if (KnownZero == 0xffffff00)
9821       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9822                         DAG.getValueType(MVT::i8));
9823     else if (KnownZero == 0xffff0000)
9824       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9825                         DAG.getValueType(MVT::i16));
9826   }
9827
9828   return Res;
9829 }
9830
9831 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9832                                              DAGCombinerInfo &DCI) const {
9833   switch (N->getOpcode()) {
9834   default: break;
9835   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9836   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9837   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9838   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9839   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9840   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9841   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9842   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9843   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9844   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9845   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9846   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9847   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9848   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9849   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9850   case ISD::FP_TO_SINT:
9851   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9852   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9853   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9854   case ISD::SHL:
9855   case ISD::SRA:
9856   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9857   case ISD::SIGN_EXTEND:
9858   case ISD::ZERO_EXTEND:
9859   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9860   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9861   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9862   case ARMISD::VLD2DUP:
9863   case ARMISD::VLD3DUP:
9864   case ARMISD::VLD4DUP:
9865     return CombineBaseUpdate(N, DCI);
9866   case ARMISD::BUILD_VECTOR:
9867     return PerformARMBUILD_VECTORCombine(N, DCI);
9868   case ISD::INTRINSIC_VOID:
9869   case ISD::INTRINSIC_W_CHAIN:
9870     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9871     case Intrinsic::arm_neon_vld1:
9872     case Intrinsic::arm_neon_vld2:
9873     case Intrinsic::arm_neon_vld3:
9874     case Intrinsic::arm_neon_vld4:
9875     case Intrinsic::arm_neon_vld2lane:
9876     case Intrinsic::arm_neon_vld3lane:
9877     case Intrinsic::arm_neon_vld4lane:
9878     case Intrinsic::arm_neon_vst1:
9879     case Intrinsic::arm_neon_vst2:
9880     case Intrinsic::arm_neon_vst3:
9881     case Intrinsic::arm_neon_vst4:
9882     case Intrinsic::arm_neon_vst2lane:
9883     case Intrinsic::arm_neon_vst3lane:
9884     case Intrinsic::arm_neon_vst4lane:
9885       return CombineBaseUpdate(N, DCI);
9886     default: break;
9887     }
9888     break;
9889   }
9890   return SDValue();
9891 }
9892
9893 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9894                                                           EVT VT) const {
9895   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9896 }
9897
9898 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9899                                                        unsigned,
9900                                                        unsigned,
9901                                                        bool *Fast) const {
9902   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9903   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9904
9905   switch (VT.getSimpleVT().SimpleTy) {
9906   default:
9907     return false;
9908   case MVT::i8:
9909   case MVT::i16:
9910   case MVT::i32: {
9911     // Unaligned access can use (for example) LRDB, LRDH, LDR
9912     if (AllowsUnaligned) {
9913       if (Fast)
9914         *Fast = Subtarget->hasV7Ops();
9915       return true;
9916     }
9917     return false;
9918   }
9919   case MVT::f64:
9920   case MVT::v2f64: {
9921     // For any little-endian targets with neon, we can support unaligned ld/st
9922     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9923     // A big-endian target may also explicitly support unaligned accesses
9924     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9925       if (Fast)
9926         *Fast = true;
9927       return true;
9928     }
9929     return false;
9930   }
9931   }
9932 }
9933
9934 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9935                        unsigned AlignCheck) {
9936   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9937           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9938 }
9939
9940 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9941                                            unsigned DstAlign, unsigned SrcAlign,
9942                                            bool IsMemset, bool ZeroMemset,
9943                                            bool MemcpyStrSrc,
9944                                            MachineFunction &MF) const {
9945   const Function *F = MF.getFunction();
9946
9947   // See if we can use NEON instructions for this...
9948   if ((!IsMemset || ZeroMemset) &&
9949       Subtarget->hasNEON() &&
9950       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9951                                        Attribute::NoImplicitFloat)) {
9952     bool Fast;
9953     if (Size >= 16 &&
9954         (memOpAlign(SrcAlign, DstAlign, 16) ||
9955          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9956       return MVT::v2f64;
9957     } else if (Size >= 8 &&
9958                (memOpAlign(SrcAlign, DstAlign, 8) ||
9959                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9960                  Fast))) {
9961       return MVT::f64;
9962     }
9963   }
9964
9965   // Lowering to i32/i16 if the size permits.
9966   if (Size >= 4)
9967     return MVT::i32;
9968   else if (Size >= 2)
9969     return MVT::i16;
9970
9971   // Let the target-independent logic figure it out.
9972   return MVT::Other;
9973 }
9974
9975 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9976   if (Val.getOpcode() != ISD::LOAD)
9977     return false;
9978
9979   EVT VT1 = Val.getValueType();
9980   if (!VT1.isSimple() || !VT1.isInteger() ||
9981       !VT2.isSimple() || !VT2.isInteger())
9982     return false;
9983
9984   switch (VT1.getSimpleVT().SimpleTy) {
9985   default: break;
9986   case MVT::i1:
9987   case MVT::i8:
9988   case MVT::i16:
9989     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9990     return true;
9991   }
9992
9993   return false;
9994 }
9995
9996 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9997   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9998     return false;
9999
10000   if (!isTypeLegal(EVT::getEVT(Ty1)))
10001     return false;
10002
10003   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10004
10005   // Assuming the caller doesn't have a zeroext or signext return parameter,
10006   // truncation all the way down to i1 is valid.
10007   return true;
10008 }
10009
10010
10011 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10012   if (V < 0)
10013     return false;
10014
10015   unsigned Scale = 1;
10016   switch (VT.getSimpleVT().SimpleTy) {
10017   default: return false;
10018   case MVT::i1:
10019   case MVT::i8:
10020     // Scale == 1;
10021     break;
10022   case MVT::i16:
10023     // Scale == 2;
10024     Scale = 2;
10025     break;
10026   case MVT::i32:
10027     // Scale == 4;
10028     Scale = 4;
10029     break;
10030   }
10031
10032   if ((V & (Scale - 1)) != 0)
10033     return false;
10034   V /= Scale;
10035   return V == (V & ((1LL << 5) - 1));
10036 }
10037
10038 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10039                                       const ARMSubtarget *Subtarget) {
10040   bool isNeg = false;
10041   if (V < 0) {
10042     isNeg = true;
10043     V = - V;
10044   }
10045
10046   switch (VT.getSimpleVT().SimpleTy) {
10047   default: return false;
10048   case MVT::i1:
10049   case MVT::i8:
10050   case MVT::i16:
10051   case MVT::i32:
10052     // + imm12 or - imm8
10053     if (isNeg)
10054       return V == (V & ((1LL << 8) - 1));
10055     return V == (V & ((1LL << 12) - 1));
10056   case MVT::f32:
10057   case MVT::f64:
10058     // Same as ARM mode. FIXME: NEON?
10059     if (!Subtarget->hasVFP2())
10060       return false;
10061     if ((V & 3) != 0)
10062       return false;
10063     V >>= 2;
10064     return V == (V & ((1LL << 8) - 1));
10065   }
10066 }
10067
10068 /// isLegalAddressImmediate - Return true if the integer value can be used
10069 /// as the offset of the target addressing mode for load / store of the
10070 /// given type.
10071 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10072                                     const ARMSubtarget *Subtarget) {
10073   if (V == 0)
10074     return true;
10075
10076   if (!VT.isSimple())
10077     return false;
10078
10079   if (Subtarget->isThumb1Only())
10080     return isLegalT1AddressImmediate(V, VT);
10081   else if (Subtarget->isThumb2())
10082     return isLegalT2AddressImmediate(V, VT, Subtarget);
10083
10084   // ARM mode.
10085   if (V < 0)
10086     V = - V;
10087   switch (VT.getSimpleVT().SimpleTy) {
10088   default: return false;
10089   case MVT::i1:
10090   case MVT::i8:
10091   case MVT::i32:
10092     // +- imm12
10093     return V == (V & ((1LL << 12) - 1));
10094   case MVT::i16:
10095     // +- imm8
10096     return V == (V & ((1LL << 8) - 1));
10097   case MVT::f32:
10098   case MVT::f64:
10099     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10100       return false;
10101     if ((V & 3) != 0)
10102       return false;
10103     V >>= 2;
10104     return V == (V & ((1LL << 8) - 1));
10105   }
10106 }
10107
10108 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10109                                                       EVT VT) const {
10110   int Scale = AM.Scale;
10111   if (Scale < 0)
10112     return false;
10113
10114   switch (VT.getSimpleVT().SimpleTy) {
10115   default: return false;
10116   case MVT::i1:
10117   case MVT::i8:
10118   case MVT::i16:
10119   case MVT::i32:
10120     if (Scale == 1)
10121       return true;
10122     // r + r << imm
10123     Scale = Scale & ~1;
10124     return Scale == 2 || Scale == 4 || Scale == 8;
10125   case MVT::i64:
10126     // r + r
10127     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10128       return true;
10129     return false;
10130   case MVT::isVoid:
10131     // Note, we allow "void" uses (basically, uses that aren't loads or
10132     // stores), because arm allows folding a scale into many arithmetic
10133     // operations.  This should be made more precise and revisited later.
10134
10135     // Allow r << imm, but the imm has to be a multiple of two.
10136     if (Scale & 1) return false;
10137     return isPowerOf2_32(Scale);
10138   }
10139 }
10140
10141 /// isLegalAddressingMode - Return true if the addressing mode represented
10142 /// by AM is legal for this target, for a load/store of the specified type.
10143 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10144                                               Type *Ty) const {
10145   EVT VT = getValueType(Ty, true);
10146   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10147     return false;
10148
10149   // Can never fold addr of global into load/store.
10150   if (AM.BaseGV)
10151     return false;
10152
10153   switch (AM.Scale) {
10154   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10155     break;
10156   case 1:
10157     if (Subtarget->isThumb1Only())
10158       return false;
10159     // FALL THROUGH.
10160   default:
10161     // ARM doesn't support any R+R*scale+imm addr modes.
10162     if (AM.BaseOffs)
10163       return false;
10164
10165     if (!VT.isSimple())
10166       return false;
10167
10168     if (Subtarget->isThumb2())
10169       return isLegalT2ScaledAddressingMode(AM, VT);
10170
10171     int Scale = AM.Scale;
10172     switch (VT.getSimpleVT().SimpleTy) {
10173     default: return false;
10174     case MVT::i1:
10175     case MVT::i8:
10176     case MVT::i32:
10177       if (Scale < 0) Scale = -Scale;
10178       if (Scale == 1)
10179         return true;
10180       // r + r << imm
10181       return isPowerOf2_32(Scale & ~1);
10182     case MVT::i16:
10183     case MVT::i64:
10184       // r + r
10185       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10186         return true;
10187       return false;
10188
10189     case MVT::isVoid:
10190       // Note, we allow "void" uses (basically, uses that aren't loads or
10191       // stores), because arm allows folding a scale into many arithmetic
10192       // operations.  This should be made more precise and revisited later.
10193
10194       // Allow r << imm, but the imm has to be a multiple of two.
10195       if (Scale & 1) return false;
10196       return isPowerOf2_32(Scale);
10197     }
10198   }
10199   return true;
10200 }
10201
10202 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10203 /// icmp immediate, that is the target has icmp instructions which can compare
10204 /// a register against the immediate without having to materialize the
10205 /// immediate into a register.
10206 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10207   // Thumb2 and ARM modes can use cmn for negative immediates.
10208   if (!Subtarget->isThumb())
10209     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10210   if (Subtarget->isThumb2())
10211     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10212   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10213   return Imm >= 0 && Imm <= 255;
10214 }
10215
10216 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10217 /// *or sub* immediate, that is the target has add or sub instructions which can
10218 /// add a register with the immediate without having to materialize the
10219 /// immediate into a register.
10220 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10221   // Same encoding for add/sub, just flip the sign.
10222   int64_t AbsImm = llvm::abs64(Imm);
10223   if (!Subtarget->isThumb())
10224     return ARM_AM::getSOImmVal(AbsImm) != -1;
10225   if (Subtarget->isThumb2())
10226     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10227   // Thumb1 only has 8-bit unsigned immediate.
10228   return AbsImm >= 0 && AbsImm <= 255;
10229 }
10230
10231 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10232                                       bool isSEXTLoad, SDValue &Base,
10233                                       SDValue &Offset, bool &isInc,
10234                                       SelectionDAG &DAG) {
10235   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10236     return false;
10237
10238   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10239     // AddressingMode 3
10240     Base = Ptr->getOperand(0);
10241     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10242       int RHSC = (int)RHS->getZExtValue();
10243       if (RHSC < 0 && RHSC > -256) {
10244         assert(Ptr->getOpcode() == ISD::ADD);
10245         isInc = false;
10246         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10247         return true;
10248       }
10249     }
10250     isInc = (Ptr->getOpcode() == ISD::ADD);
10251     Offset = Ptr->getOperand(1);
10252     return true;
10253   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10254     // AddressingMode 2
10255     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10256       int RHSC = (int)RHS->getZExtValue();
10257       if (RHSC < 0 && RHSC > -0x1000) {
10258         assert(Ptr->getOpcode() == ISD::ADD);
10259         isInc = false;
10260         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10261         Base = Ptr->getOperand(0);
10262         return true;
10263       }
10264     }
10265
10266     if (Ptr->getOpcode() == ISD::ADD) {
10267       isInc = true;
10268       ARM_AM::ShiftOpc ShOpcVal=
10269         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10270       if (ShOpcVal != ARM_AM::no_shift) {
10271         Base = Ptr->getOperand(1);
10272         Offset = Ptr->getOperand(0);
10273       } else {
10274         Base = Ptr->getOperand(0);
10275         Offset = Ptr->getOperand(1);
10276       }
10277       return true;
10278     }
10279
10280     isInc = (Ptr->getOpcode() == ISD::ADD);
10281     Base = Ptr->getOperand(0);
10282     Offset = Ptr->getOperand(1);
10283     return true;
10284   }
10285
10286   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10287   return false;
10288 }
10289
10290 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10291                                      bool isSEXTLoad, SDValue &Base,
10292                                      SDValue &Offset, bool &isInc,
10293                                      SelectionDAG &DAG) {
10294   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10295     return false;
10296
10297   Base = Ptr->getOperand(0);
10298   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10299     int RHSC = (int)RHS->getZExtValue();
10300     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10301       assert(Ptr->getOpcode() == ISD::ADD);
10302       isInc = false;
10303       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10304       return true;
10305     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10306       isInc = Ptr->getOpcode() == ISD::ADD;
10307       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10308       return true;
10309     }
10310   }
10311
10312   return false;
10313 }
10314
10315 /// getPreIndexedAddressParts - returns true by value, base pointer and
10316 /// offset pointer and addressing mode by reference if the node's address
10317 /// can be legally represented as pre-indexed load / store address.
10318 bool
10319 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10320                                              SDValue &Offset,
10321                                              ISD::MemIndexedMode &AM,
10322                                              SelectionDAG &DAG) const {
10323   if (Subtarget->isThumb1Only())
10324     return false;
10325
10326   EVT VT;
10327   SDValue Ptr;
10328   bool isSEXTLoad = false;
10329   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10330     Ptr = LD->getBasePtr();
10331     VT  = LD->getMemoryVT();
10332     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10333   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10334     Ptr = ST->getBasePtr();
10335     VT  = ST->getMemoryVT();
10336   } else
10337     return false;
10338
10339   bool isInc;
10340   bool isLegal = false;
10341   if (Subtarget->isThumb2())
10342     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10343                                        Offset, isInc, DAG);
10344   else
10345     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10346                                         Offset, isInc, DAG);
10347   if (!isLegal)
10348     return false;
10349
10350   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10351   return true;
10352 }
10353
10354 /// getPostIndexedAddressParts - returns true by value, base pointer and
10355 /// offset pointer and addressing mode by reference if this node can be
10356 /// combined with a load / store to form a post-indexed load / store.
10357 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10358                                                    SDValue &Base,
10359                                                    SDValue &Offset,
10360                                                    ISD::MemIndexedMode &AM,
10361                                                    SelectionDAG &DAG) const {
10362   if (Subtarget->isThumb1Only())
10363     return false;
10364
10365   EVT VT;
10366   SDValue Ptr;
10367   bool isSEXTLoad = false;
10368   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10369     VT  = LD->getMemoryVT();
10370     Ptr = LD->getBasePtr();
10371     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10372   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10373     VT  = ST->getMemoryVT();
10374     Ptr = ST->getBasePtr();
10375   } else
10376     return false;
10377
10378   bool isInc;
10379   bool isLegal = false;
10380   if (Subtarget->isThumb2())
10381     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10382                                        isInc, DAG);
10383   else
10384     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10385                                         isInc, DAG);
10386   if (!isLegal)
10387     return false;
10388
10389   if (Ptr != Base) {
10390     // Swap base ptr and offset to catch more post-index load / store when
10391     // it's legal. In Thumb2 mode, offset must be an immediate.
10392     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10393         !Subtarget->isThumb2())
10394       std::swap(Base, Offset);
10395
10396     // Post-indexed load / store update the base pointer.
10397     if (Ptr != Base)
10398       return false;
10399   }
10400
10401   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10402   return true;
10403 }
10404
10405 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10406                                                       APInt &KnownZero,
10407                                                       APInt &KnownOne,
10408                                                       const SelectionDAG &DAG,
10409                                                       unsigned Depth) const {
10410   unsigned BitWidth = KnownOne.getBitWidth();
10411   KnownZero = KnownOne = APInt(BitWidth, 0);
10412   switch (Op.getOpcode()) {
10413   default: break;
10414   case ARMISD::ADDC:
10415   case ARMISD::ADDE:
10416   case ARMISD::SUBC:
10417   case ARMISD::SUBE:
10418     // These nodes' second result is a boolean
10419     if (Op.getResNo() == 0)
10420       break;
10421     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10422     break;
10423   case ARMISD::CMOV: {
10424     // Bits are known zero/one if known on the LHS and RHS.
10425     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10426     if (KnownZero == 0 && KnownOne == 0) return;
10427
10428     APInt KnownZeroRHS, KnownOneRHS;
10429     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10430     KnownZero &= KnownZeroRHS;
10431     KnownOne  &= KnownOneRHS;
10432     return;
10433   }
10434   case ISD::INTRINSIC_W_CHAIN: {
10435     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10436     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10437     switch (IntID) {
10438     default: return;
10439     case Intrinsic::arm_ldaex:
10440     case Intrinsic::arm_ldrex: {
10441       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10442       unsigned MemBits = VT.getScalarType().getSizeInBits();
10443       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10444       return;
10445     }
10446     }
10447   }
10448   }
10449 }
10450
10451 //===----------------------------------------------------------------------===//
10452 //                           ARM Inline Assembly Support
10453 //===----------------------------------------------------------------------===//
10454
10455 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10456   // Looking for "rev" which is V6+.
10457   if (!Subtarget->hasV6Ops())
10458     return false;
10459
10460   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10461   std::string AsmStr = IA->getAsmString();
10462   SmallVector<StringRef, 4> AsmPieces;
10463   SplitString(AsmStr, AsmPieces, ";\n");
10464
10465   switch (AsmPieces.size()) {
10466   default: return false;
10467   case 1:
10468     AsmStr = AsmPieces[0];
10469     AsmPieces.clear();
10470     SplitString(AsmStr, AsmPieces, " \t,");
10471
10472     // rev $0, $1
10473     if (AsmPieces.size() == 3 &&
10474         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10475         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10476       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10477       if (Ty && Ty->getBitWidth() == 32)
10478         return IntrinsicLowering::LowerToByteSwap(CI);
10479     }
10480     break;
10481   }
10482
10483   return false;
10484 }
10485
10486 /// getConstraintType - Given a constraint letter, return the type of
10487 /// constraint it is for this target.
10488 ARMTargetLowering::ConstraintType
10489 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10490   if (Constraint.size() == 1) {
10491     switch (Constraint[0]) {
10492     default:  break;
10493     case 'l': return C_RegisterClass;
10494     case 'w': return C_RegisterClass;
10495     case 'h': return C_RegisterClass;
10496     case 'x': return C_RegisterClass;
10497     case 't': return C_RegisterClass;
10498     case 'j': return C_Other; // Constant for movw.
10499       // An address with a single base register. Due to the way we
10500       // currently handle addresses it is the same as an 'r' memory constraint.
10501     case 'Q': return C_Memory;
10502     }
10503   } else if (Constraint.size() == 2) {
10504     switch (Constraint[0]) {
10505     default: break;
10506     // All 'U+' constraints are addresses.
10507     case 'U': return C_Memory;
10508     }
10509   }
10510   return TargetLowering::getConstraintType(Constraint);
10511 }
10512
10513 /// Examine constraint type and operand type and determine a weight value.
10514 /// This object must already have been set up with the operand type
10515 /// and the current alternative constraint selected.
10516 TargetLowering::ConstraintWeight
10517 ARMTargetLowering::getSingleConstraintMatchWeight(
10518     AsmOperandInfo &info, const char *constraint) const {
10519   ConstraintWeight weight = CW_Invalid;
10520   Value *CallOperandVal = info.CallOperandVal;
10521     // If we don't have a value, we can't do a match,
10522     // but allow it at the lowest weight.
10523   if (!CallOperandVal)
10524     return CW_Default;
10525   Type *type = CallOperandVal->getType();
10526   // Look at the constraint type.
10527   switch (*constraint) {
10528   default:
10529     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10530     break;
10531   case 'l':
10532     if (type->isIntegerTy()) {
10533       if (Subtarget->isThumb())
10534         weight = CW_SpecificReg;
10535       else
10536         weight = CW_Register;
10537     }
10538     break;
10539   case 'w':
10540     if (type->isFloatingPointTy())
10541       weight = CW_Register;
10542     break;
10543   }
10544   return weight;
10545 }
10546
10547 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10548 RCPair
10549 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10550                                                 MVT VT) const {
10551   if (Constraint.size() == 1) {
10552     // GCC ARM Constraint Letters
10553     switch (Constraint[0]) {
10554     case 'l': // Low regs or general regs.
10555       if (Subtarget->isThumb())
10556         return RCPair(0U, &ARM::tGPRRegClass);
10557       return RCPair(0U, &ARM::GPRRegClass);
10558     case 'h': // High regs or no regs.
10559       if (Subtarget->isThumb())
10560         return RCPair(0U, &ARM::hGPRRegClass);
10561       break;
10562     case 'r':
10563       if (Subtarget->isThumb1Only())
10564         return RCPair(0U, &ARM::tGPRRegClass);
10565       return RCPair(0U, &ARM::GPRRegClass);
10566     case 'w':
10567       if (VT == MVT::Other)
10568         break;
10569       if (VT == MVT::f32)
10570         return RCPair(0U, &ARM::SPRRegClass);
10571       if (VT.getSizeInBits() == 64)
10572         return RCPair(0U, &ARM::DPRRegClass);
10573       if (VT.getSizeInBits() == 128)
10574         return RCPair(0U, &ARM::QPRRegClass);
10575       break;
10576     case 'x':
10577       if (VT == MVT::Other)
10578         break;
10579       if (VT == MVT::f32)
10580         return RCPair(0U, &ARM::SPR_8RegClass);
10581       if (VT.getSizeInBits() == 64)
10582         return RCPair(0U, &ARM::DPR_8RegClass);
10583       if (VT.getSizeInBits() == 128)
10584         return RCPair(0U, &ARM::QPR_8RegClass);
10585       break;
10586     case 't':
10587       if (VT == MVT::f32)
10588         return RCPair(0U, &ARM::SPRRegClass);
10589       break;
10590     }
10591   }
10592   if (StringRef("{cc}").equals_lower(Constraint))
10593     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10594
10595   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10596 }
10597
10598 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10599 /// vector.  If it is invalid, don't add anything to Ops.
10600 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10601                                                      std::string &Constraint,
10602                                                      std::vector<SDValue>&Ops,
10603                                                      SelectionDAG &DAG) const {
10604   SDValue Result;
10605
10606   // Currently only support length 1 constraints.
10607   if (Constraint.length() != 1) return;
10608
10609   char ConstraintLetter = Constraint[0];
10610   switch (ConstraintLetter) {
10611   default: break;
10612   case 'j':
10613   case 'I': case 'J': case 'K': case 'L':
10614   case 'M': case 'N': case 'O':
10615     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10616     if (!C)
10617       return;
10618
10619     int64_t CVal64 = C->getSExtValue();
10620     int CVal = (int) CVal64;
10621     // None of these constraints allow values larger than 32 bits.  Check
10622     // that the value fits in an int.
10623     if (CVal != CVal64)
10624       return;
10625
10626     switch (ConstraintLetter) {
10627       case 'j':
10628         // Constant suitable for movw, must be between 0 and
10629         // 65535.
10630         if (Subtarget->hasV6T2Ops())
10631           if (CVal >= 0 && CVal <= 65535)
10632             break;
10633         return;
10634       case 'I':
10635         if (Subtarget->isThumb1Only()) {
10636           // This must be a constant between 0 and 255, for ADD
10637           // immediates.
10638           if (CVal >= 0 && CVal <= 255)
10639             break;
10640         } else if (Subtarget->isThumb2()) {
10641           // A constant that can be used as an immediate value in a
10642           // data-processing instruction.
10643           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10644             break;
10645         } else {
10646           // A constant that can be used as an immediate value in a
10647           // data-processing instruction.
10648           if (ARM_AM::getSOImmVal(CVal) != -1)
10649             break;
10650         }
10651         return;
10652
10653       case 'J':
10654         if (Subtarget->isThumb()) {  // FIXME thumb2
10655           // This must be a constant between -255 and -1, for negated ADD
10656           // immediates. This can be used in GCC with an "n" modifier that
10657           // prints the negated value, for use with SUB instructions. It is
10658           // not useful otherwise but is implemented for compatibility.
10659           if (CVal >= -255 && CVal <= -1)
10660             break;
10661         } else {
10662           // This must be a constant between -4095 and 4095. It is not clear
10663           // what this constraint is intended for. Implemented for
10664           // compatibility with GCC.
10665           if (CVal >= -4095 && CVal <= 4095)
10666             break;
10667         }
10668         return;
10669
10670       case 'K':
10671         if (Subtarget->isThumb1Only()) {
10672           // A 32-bit value where only one byte has a nonzero value. Exclude
10673           // zero to match GCC. This constraint is used by GCC internally for
10674           // constants that can be loaded with a move/shift combination.
10675           // It is not useful otherwise but is implemented for compatibility.
10676           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10677             break;
10678         } else if (Subtarget->isThumb2()) {
10679           // A constant whose bitwise inverse can be used as an immediate
10680           // value in a data-processing instruction. This can be used in GCC
10681           // with a "B" modifier that prints the inverted value, for use with
10682           // BIC and MVN instructions. It is not useful otherwise but is
10683           // implemented for compatibility.
10684           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10685             break;
10686         } else {
10687           // A constant whose bitwise inverse can be used as an immediate
10688           // value in a data-processing instruction. This can be used in GCC
10689           // with a "B" modifier that prints the inverted value, for use with
10690           // BIC and MVN instructions. It is not useful otherwise but is
10691           // implemented for compatibility.
10692           if (ARM_AM::getSOImmVal(~CVal) != -1)
10693             break;
10694         }
10695         return;
10696
10697       case 'L':
10698         if (Subtarget->isThumb1Only()) {
10699           // This must be a constant between -7 and 7,
10700           // for 3-operand ADD/SUB immediate instructions.
10701           if (CVal >= -7 && CVal < 7)
10702             break;
10703         } else if (Subtarget->isThumb2()) {
10704           // A constant whose negation can be used as an immediate value in a
10705           // data-processing instruction. This can be used in GCC with an "n"
10706           // modifier that prints the negated value, for use with SUB
10707           // instructions. It is not useful otherwise but is implemented for
10708           // compatibility.
10709           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10710             break;
10711         } else {
10712           // A constant whose negation can be used as an immediate value in a
10713           // data-processing instruction. This can be used in GCC with an "n"
10714           // modifier that prints the negated value, for use with SUB
10715           // instructions. It is not useful otherwise but is implemented for
10716           // compatibility.
10717           if (ARM_AM::getSOImmVal(-CVal) != -1)
10718             break;
10719         }
10720         return;
10721
10722       case 'M':
10723         if (Subtarget->isThumb()) { // FIXME thumb2
10724           // This must be a multiple of 4 between 0 and 1020, for
10725           // ADD sp + immediate.
10726           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10727             break;
10728         } else {
10729           // A power of two or a constant between 0 and 32.  This is used in
10730           // GCC for the shift amount on shifted register operands, but it is
10731           // useful in general for any shift amounts.
10732           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10733             break;
10734         }
10735         return;
10736
10737       case 'N':
10738         if (Subtarget->isThumb()) {  // FIXME thumb2
10739           // This must be a constant between 0 and 31, for shift amounts.
10740           if (CVal >= 0 && CVal <= 31)
10741             break;
10742         }
10743         return;
10744
10745       case 'O':
10746         if (Subtarget->isThumb()) {  // FIXME thumb2
10747           // This must be a multiple of 4 between -508 and 508, for
10748           // ADD/SUB sp = sp + immediate.
10749           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10750             break;
10751         }
10752         return;
10753     }
10754     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10755     break;
10756   }
10757
10758   if (Result.getNode()) {
10759     Ops.push_back(Result);
10760     return;
10761   }
10762   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10763 }
10764
10765 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10766   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10767   unsigned Opcode = Op->getOpcode();
10768   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10769          "Invalid opcode for Div/Rem lowering");
10770   bool isSigned = (Opcode == ISD::SDIVREM);
10771   EVT VT = Op->getValueType(0);
10772   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10773
10774   RTLIB::Libcall LC;
10775   switch (VT.getSimpleVT().SimpleTy) {
10776   default: llvm_unreachable("Unexpected request for libcall!");
10777   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10778   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10779   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10780   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10781   }
10782
10783   SDValue InChain = DAG.getEntryNode();
10784
10785   TargetLowering::ArgListTy Args;
10786   TargetLowering::ArgListEntry Entry;
10787   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10788     EVT ArgVT = Op->getOperand(i).getValueType();
10789     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10790     Entry.Node = Op->getOperand(i);
10791     Entry.Ty = ArgTy;
10792     Entry.isSExt = isSigned;
10793     Entry.isZExt = !isSigned;
10794     Args.push_back(Entry);
10795   }
10796
10797   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10798                                          getPointerTy());
10799
10800   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10801
10802   SDLoc dl(Op);
10803   TargetLowering::CallLoweringInfo CLI(DAG);
10804   CLI.setDebugLoc(dl).setChain(InChain)
10805     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10806     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10807
10808   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10809   return CallInfo.first;
10810 }
10811
10812 SDValue
10813 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10814   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10815   SDLoc DL(Op);
10816
10817   // Get the inputs.
10818   SDValue Chain = Op.getOperand(0);
10819   SDValue Size  = Op.getOperand(1);
10820
10821   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10822                               DAG.getConstant(2, MVT::i32));
10823
10824   SDValue Flag;
10825   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10826   Flag = Chain.getValue(1);
10827
10828   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10829   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10830
10831   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10832   Chain = NewSP.getValue(1);
10833
10834   SDValue Ops[2] = { NewSP, Chain };
10835   return DAG.getMergeValues(Ops, DL);
10836 }
10837
10838 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10839   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10840          "Unexpected type for custom-lowering FP_EXTEND");
10841
10842   RTLIB::Libcall LC;
10843   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10844
10845   SDValue SrcVal = Op.getOperand(0);
10846   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10847                      /*isSigned*/ false, SDLoc(Op)).first;
10848 }
10849
10850 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10851   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10852          Subtarget->isFPOnlySP() &&
10853          "Unexpected type for custom-lowering FP_ROUND");
10854
10855   RTLIB::Libcall LC;
10856   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10857
10858   SDValue SrcVal = Op.getOperand(0);
10859   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10860                      /*isSigned*/ false, SDLoc(Op)).first;
10861 }
10862
10863 bool
10864 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10865   // The ARM target isn't yet aware of offsets.
10866   return false;
10867 }
10868
10869 bool ARM::isBitFieldInvertedMask(unsigned v) {
10870   if (v == 0xffffffff)
10871     return false;
10872
10873   // there can be 1's on either or both "outsides", all the "inside"
10874   // bits must be 0's
10875   unsigned TO = CountTrailingOnes_32(v);
10876   unsigned LO = CountLeadingOnes_32(v);
10877   v = (v >> TO) << TO;
10878   v = (v << LO) >> LO;
10879   return v == 0;
10880 }
10881
10882 /// isFPImmLegal - Returns true if the target can instruction select the
10883 /// specified FP immediate natively. If false, the legalizer will
10884 /// materialize the FP immediate as a load from a constant pool.
10885 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10886   if (!Subtarget->hasVFP3())
10887     return false;
10888   if (VT == MVT::f32)
10889     return ARM_AM::getFP32Imm(Imm) != -1;
10890   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10891     return ARM_AM::getFP64Imm(Imm) != -1;
10892   return false;
10893 }
10894
10895 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10896 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10897 /// specified in the intrinsic calls.
10898 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10899                                            const CallInst &I,
10900                                            unsigned Intrinsic) const {
10901   switch (Intrinsic) {
10902   case Intrinsic::arm_neon_vld1:
10903   case Intrinsic::arm_neon_vld2:
10904   case Intrinsic::arm_neon_vld3:
10905   case Intrinsic::arm_neon_vld4:
10906   case Intrinsic::arm_neon_vld2lane:
10907   case Intrinsic::arm_neon_vld3lane:
10908   case Intrinsic::arm_neon_vld4lane: {
10909     Info.opc = ISD::INTRINSIC_W_CHAIN;
10910     // Conservatively set memVT to the entire set of vectors loaded.
10911     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10912     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10913     Info.ptrVal = I.getArgOperand(0);
10914     Info.offset = 0;
10915     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10916     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10917     Info.vol = false; // volatile loads with NEON intrinsics not supported
10918     Info.readMem = true;
10919     Info.writeMem = false;
10920     return true;
10921   }
10922   case Intrinsic::arm_neon_vst1:
10923   case Intrinsic::arm_neon_vst2:
10924   case Intrinsic::arm_neon_vst3:
10925   case Intrinsic::arm_neon_vst4:
10926   case Intrinsic::arm_neon_vst2lane:
10927   case Intrinsic::arm_neon_vst3lane:
10928   case Intrinsic::arm_neon_vst4lane: {
10929     Info.opc = ISD::INTRINSIC_VOID;
10930     // Conservatively set memVT to the entire set of vectors stored.
10931     unsigned NumElts = 0;
10932     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10933       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10934       if (!ArgTy->isVectorTy())
10935         break;
10936       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10937     }
10938     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10939     Info.ptrVal = I.getArgOperand(0);
10940     Info.offset = 0;
10941     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10942     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10943     Info.vol = false; // volatile stores with NEON intrinsics not supported
10944     Info.readMem = false;
10945     Info.writeMem = true;
10946     return true;
10947   }
10948   case Intrinsic::arm_ldaex:
10949   case Intrinsic::arm_ldrex: {
10950     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10951     Info.opc = ISD::INTRINSIC_W_CHAIN;
10952     Info.memVT = MVT::getVT(PtrTy->getElementType());
10953     Info.ptrVal = I.getArgOperand(0);
10954     Info.offset = 0;
10955     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10956     Info.vol = true;
10957     Info.readMem = true;
10958     Info.writeMem = false;
10959     return true;
10960   }
10961   case Intrinsic::arm_stlex:
10962   case Intrinsic::arm_strex: {
10963     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10964     Info.opc = ISD::INTRINSIC_W_CHAIN;
10965     Info.memVT = MVT::getVT(PtrTy->getElementType());
10966     Info.ptrVal = I.getArgOperand(1);
10967     Info.offset = 0;
10968     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10969     Info.vol = true;
10970     Info.readMem = false;
10971     Info.writeMem = true;
10972     return true;
10973   }
10974   case Intrinsic::arm_stlexd:
10975   case Intrinsic::arm_strexd: {
10976     Info.opc = ISD::INTRINSIC_W_CHAIN;
10977     Info.memVT = MVT::i64;
10978     Info.ptrVal = I.getArgOperand(2);
10979     Info.offset = 0;
10980     Info.align = 8;
10981     Info.vol = true;
10982     Info.readMem = false;
10983     Info.writeMem = true;
10984     return true;
10985   }
10986   case Intrinsic::arm_ldaexd:
10987   case Intrinsic::arm_ldrexd: {
10988     Info.opc = ISD::INTRINSIC_W_CHAIN;
10989     Info.memVT = MVT::i64;
10990     Info.ptrVal = I.getArgOperand(0);
10991     Info.offset = 0;
10992     Info.align = 8;
10993     Info.vol = true;
10994     Info.readMem = true;
10995     Info.writeMem = false;
10996     return true;
10997   }
10998   default:
10999     break;
11000   }
11001
11002   return false;
11003 }
11004
11005 /// \brief Returns true if it is beneficial to convert a load of a constant
11006 /// to just the constant itself.
11007 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11008                                                           Type *Ty) const {
11009   assert(Ty->isIntegerTy());
11010
11011   unsigned Bits = Ty->getPrimitiveSizeInBits();
11012   if (Bits == 0 || Bits > 32)
11013     return false;
11014   return true;
11015 }
11016
11017 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11018
11019 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11020                                         ARM_MB::MemBOpt Domain) const {
11021   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11022
11023   // First, if the target has no DMB, see what fallback we can use.
11024   if (!Subtarget->hasDataBarrier()) {
11025     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11026     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11027     // here.
11028     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11029       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11030       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11031                         Builder.getInt32(0), Builder.getInt32(7),
11032                         Builder.getInt32(10), Builder.getInt32(5)};
11033       return Builder.CreateCall(MCR, args);
11034     } else {
11035       // Instead of using barriers, atomic accesses on these subtargets use
11036       // libcalls.
11037       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11038     }
11039   } else {
11040     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11041     // Only a full system barrier exists in the M-class architectures.
11042     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11043     Constant *CDomain = Builder.getInt32(Domain);
11044     return Builder.CreateCall(DMB, CDomain);
11045   }
11046 }
11047
11048 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11049 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11050                                          AtomicOrdering Ord, bool IsStore,
11051                                          bool IsLoad) const {
11052   if (!getInsertFencesForAtomic())
11053     return nullptr;
11054
11055   switch (Ord) {
11056   case NotAtomic:
11057   case Unordered:
11058     llvm_unreachable("Invalid fence: unordered/non-atomic");
11059   case Monotonic:
11060   case Acquire:
11061     return nullptr; // Nothing to do
11062   case SequentiallyConsistent:
11063     if (!IsStore)
11064       return nullptr; // Nothing to do
11065     /*FALLTHROUGH*/
11066   case Release:
11067   case AcquireRelease:
11068     if (Subtarget->isSwift())
11069       return makeDMB(Builder, ARM_MB::ISHST);
11070     // FIXME: add a comment with a link to documentation justifying this.
11071     else
11072       return makeDMB(Builder, ARM_MB::ISH);
11073   }
11074   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11075 }
11076
11077 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11078                                           AtomicOrdering Ord, bool IsStore,
11079                                           bool IsLoad) const {
11080   if (!getInsertFencesForAtomic())
11081     return nullptr;
11082
11083   switch (Ord) {
11084   case NotAtomic:
11085   case Unordered:
11086     llvm_unreachable("Invalid fence: unordered/not-atomic");
11087   case Monotonic:
11088   case Release:
11089     return nullptr; // Nothing to do
11090   case Acquire:
11091   case AcquireRelease:
11092   case SequentiallyConsistent:
11093     return makeDMB(Builder, ARM_MB::ISH);
11094   }
11095   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11096 }
11097
11098 // Loads and stores less than 64-bits are already atomic; ones above that
11099 // are doomed anyway, so defer to the default libcall and blame the OS when
11100 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11101 // anything for those.
11102 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11103   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11104   return (Size == 64) && !Subtarget->isMClass();
11105 }
11106
11107 // Loads and stores less than 64-bits are already atomic; ones above that
11108 // are doomed anyway, so defer to the default libcall and blame the OS when
11109 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11110 // anything for those.
11111 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11112 // guarantee, see DDI0406C ARM architecture reference manual,
11113 // sections A8.8.72-74 LDRD)
11114 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11115   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11116   return (Size == 64) && !Subtarget->isMClass();
11117 }
11118
11119 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11120 // and up to 64 bits on the non-M profiles
11121 bool ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11122   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11123   return Size <= (Subtarget->isMClass() ? 32U : 64U);
11124 }
11125
11126 // This has so far only been implemented for MachO.
11127 bool ARMTargetLowering::useLoadStackGuardNode() const {
11128   return Subtarget->isTargetMachO();
11129 }
11130
11131 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11132                                                   unsigned &Cost) const {
11133   // If we do not have NEON, vector types are not natively supported.
11134   if (!Subtarget->hasNEON())
11135     return false;
11136
11137   // Floating point values and vector values map to the same register file.
11138   // Therefore, althought we could do a store extract of a vector type, this is
11139   // better to leave at float as we have more freedom in the addressing mode for
11140   // those.
11141   if (VectorTy->isFPOrFPVectorTy())
11142     return false;
11143
11144   // If the index is unknown at compile time, this is very expensive to lower
11145   // and it is not possible to combine the store with the extract.
11146   if (!isa<ConstantInt>(Idx))
11147     return false;
11148
11149   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11150   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11151   // We can do a store + vector extract on any vector that fits perfectly in a D
11152   // or Q register.
11153   if (BitWidth == 64 || BitWidth == 128) {
11154     Cost = 0;
11155     return true;
11156   }
11157   return false;
11158 }
11159
11160 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11161                                          AtomicOrdering Ord) const {
11162   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11163   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11164   bool IsAcquire = isAtLeastAcquire(Ord);
11165
11166   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11167   // intrinsic must return {i32, i32} and we have to recombine them into a
11168   // single i64 here.
11169   if (ValTy->getPrimitiveSizeInBits() == 64) {
11170     Intrinsic::ID Int =
11171         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11172     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11173
11174     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11175     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11176
11177     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11178     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11179     if (!Subtarget->isLittle())
11180       std::swap (Lo, Hi);
11181     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11182     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11183     return Builder.CreateOr(
11184         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11185   }
11186
11187   Type *Tys[] = { Addr->getType() };
11188   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11189   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11190
11191   return Builder.CreateTruncOrBitCast(
11192       Builder.CreateCall(Ldrex, Addr),
11193       cast<PointerType>(Addr->getType())->getElementType());
11194 }
11195
11196 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11197                                                Value *Addr,
11198                                                AtomicOrdering Ord) const {
11199   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11200   bool IsRelease = isAtLeastRelease(Ord);
11201
11202   // Since the intrinsics must have legal type, the i64 intrinsics take two
11203   // parameters: "i32, i32". We must marshal Val into the appropriate form
11204   // before the call.
11205   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11206     Intrinsic::ID Int =
11207         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11208     Function *Strex = Intrinsic::getDeclaration(M, Int);
11209     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11210
11211     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11212     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11213     if (!Subtarget->isLittle())
11214       std::swap (Lo, Hi);
11215     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11216     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11217   }
11218
11219   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11220   Type *Tys[] = { Addr->getType() };
11221   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11222
11223   return Builder.CreateCall2(
11224       Strex, Builder.CreateZExtOrBitCast(
11225                  Val, Strex->getFunctionType()->getParamType(0)),
11226       Addr);
11227 }
11228
11229 enum HABaseType {
11230   HA_UNKNOWN = 0,
11231   HA_FLOAT,
11232   HA_DOUBLE,
11233   HA_VECT64,
11234   HA_VECT128
11235 };
11236
11237 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11238                                    uint64_t &Members) {
11239   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11240     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11241       uint64_t SubMembers = 0;
11242       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11243         return false;
11244       Members += SubMembers;
11245     }
11246   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11247     uint64_t SubMembers = 0;
11248     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11249       return false;
11250     Members += SubMembers * AT->getNumElements();
11251   } else if (Ty->isFloatTy()) {
11252     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11253       return false;
11254     Members = 1;
11255     Base = HA_FLOAT;
11256   } else if (Ty->isDoubleTy()) {
11257     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11258       return false;
11259     Members = 1;
11260     Base = HA_DOUBLE;
11261   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11262     Members = 1;
11263     switch (Base) {
11264     case HA_FLOAT:
11265     case HA_DOUBLE:
11266       return false;
11267     case HA_VECT64:
11268       return VT->getBitWidth() == 64;
11269     case HA_VECT128:
11270       return VT->getBitWidth() == 128;
11271     case HA_UNKNOWN:
11272       switch (VT->getBitWidth()) {
11273       case 64:
11274         Base = HA_VECT64;
11275         return true;
11276       case 128:
11277         Base = HA_VECT128;
11278         return true;
11279       default:
11280         return false;
11281       }
11282     }
11283   }
11284
11285   return (Members > 0 && Members <= 4);
11286 }
11287
11288 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11289 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11290 /// passing according to AAPCS rules.
11291 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11292     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11293   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11294       CallingConv::ARM_AAPCS_VFP)
11295     return false;
11296
11297   HABaseType Base = HA_UNKNOWN;
11298   uint64_t Members = 0;
11299   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11300   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11301
11302   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11303   return IsHA || IsIntArray;
11304 }