Reverting VLD1/VST1 base-updating/post-incrementing combining
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/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                                      const ARMSubtarget &STI)
161     : TargetLowering(TM), Subtarget(&STI) {
162   RegInfo = Subtarget->getRegisterInfo();
163   Itins = Subtarget->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 = Subtarget->getInstrInfo();
1197   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1198
1199   if (MCID.getNumDefs() == 0)
1200     return Sched::RegPressure;
1201   if (!Itins->isEmpty() &&
1202       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1203     return Sched::ILP;
1204
1205   return Sched::RegPressure;
1206 }
1207
1208 //===----------------------------------------------------------------------===//
1209 // Lowering Code
1210 //===----------------------------------------------------------------------===//
1211
1212 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1213 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1214   switch (CC) {
1215   default: llvm_unreachable("Unknown condition code!");
1216   case ISD::SETNE:  return ARMCC::NE;
1217   case ISD::SETEQ:  return ARMCC::EQ;
1218   case ISD::SETGT:  return ARMCC::GT;
1219   case ISD::SETGE:  return ARMCC::GE;
1220   case ISD::SETLT:  return ARMCC::LT;
1221   case ISD::SETLE:  return ARMCC::LE;
1222   case ISD::SETUGT: return ARMCC::HI;
1223   case ISD::SETUGE: return ARMCC::HS;
1224   case ISD::SETULT: return ARMCC::LO;
1225   case ISD::SETULE: return ARMCC::LS;
1226   }
1227 }
1228
1229 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1230 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1231                         ARMCC::CondCodes &CondCode2) {
1232   CondCode2 = ARMCC::AL;
1233   switch (CC) {
1234   default: llvm_unreachable("Unknown FP condition!");
1235   case ISD::SETEQ:
1236   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1237   case ISD::SETGT:
1238   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1239   case ISD::SETGE:
1240   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1241   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1242   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1243   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1244   case ISD::SETO:   CondCode = ARMCC::VC; break;
1245   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1246   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1247   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1248   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1249   case ISD::SETLT:
1250   case ISD::SETULT: CondCode = ARMCC::LT; break;
1251   case ISD::SETLE:
1252   case ISD::SETULE: CondCode = ARMCC::LE; break;
1253   case ISD::SETNE:
1254   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1255   }
1256 }
1257
1258 //===----------------------------------------------------------------------===//
1259 //                      Calling Convention Implementation
1260 //===----------------------------------------------------------------------===//
1261
1262 #include "ARMGenCallingConv.inc"
1263
1264 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1265 /// account presence of floating point hardware and calling convention
1266 /// limitations, such as support for variadic functions.
1267 CallingConv::ID
1268 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1269                                            bool isVarArg) const {
1270   switch (CC) {
1271   default:
1272     llvm_unreachable("Unsupported calling convention");
1273   case CallingConv::ARM_AAPCS:
1274   case CallingConv::ARM_APCS:
1275   case CallingConv::GHC:
1276     return CC;
1277   case CallingConv::ARM_AAPCS_VFP:
1278     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1279   case CallingConv::C:
1280     if (!Subtarget->isAAPCS_ABI())
1281       return CallingConv::ARM_APCS;
1282     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1283              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1284              !isVarArg)
1285       return CallingConv::ARM_AAPCS_VFP;
1286     else
1287       return CallingConv::ARM_AAPCS;
1288   case CallingConv::Fast:
1289     if (!Subtarget->isAAPCS_ABI()) {
1290       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1291         return CallingConv::Fast;
1292       return CallingConv::ARM_APCS;
1293     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1294       return CallingConv::ARM_AAPCS_VFP;
1295     else
1296       return CallingConv::ARM_AAPCS;
1297   }
1298 }
1299
1300 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1301 /// CallingConvention.
1302 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1303                                                  bool Return,
1304                                                  bool isVarArg) const {
1305   switch (getEffectiveCallingConv(CC, isVarArg)) {
1306   default:
1307     llvm_unreachable("Unsupported calling convention");
1308   case CallingConv::ARM_APCS:
1309     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1310   case CallingConv::ARM_AAPCS:
1311     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1312   case CallingConv::ARM_AAPCS_VFP:
1313     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1314   case CallingConv::Fast:
1315     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1316   case CallingConv::GHC:
1317     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1318   }
1319 }
1320
1321 /// LowerCallResult - Lower the result values of a call into the
1322 /// appropriate copies out of appropriate physical registers.
1323 SDValue
1324 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1325                                    CallingConv::ID CallConv, bool isVarArg,
1326                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1327                                    SDLoc dl, SelectionDAG &DAG,
1328                                    SmallVectorImpl<SDValue> &InVals,
1329                                    bool isThisReturn, SDValue ThisVal) const {
1330
1331   // Assign locations to each value returned by this call.
1332   SmallVector<CCValAssign, 16> RVLocs;
1333   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1334                     *DAG.getContext(), Call);
1335   CCInfo.AnalyzeCallResult(Ins,
1336                            CCAssignFnForNode(CallConv, /* Return*/ true,
1337                                              isVarArg));
1338
1339   // Copy all of the result registers out of their specified physreg.
1340   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1341     CCValAssign VA = RVLocs[i];
1342
1343     // Pass 'this' value directly from the argument to return value, to avoid
1344     // reg unit interference
1345     if (i == 0 && isThisReturn) {
1346       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1347              "unexpected return calling convention register assignment");
1348       InVals.push_back(ThisVal);
1349       continue;
1350     }
1351
1352     SDValue Val;
1353     if (VA.needsCustom()) {
1354       // Handle f64 or half of a v2f64.
1355       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1356                                       InFlag);
1357       Chain = Lo.getValue(1);
1358       InFlag = Lo.getValue(2);
1359       VA = RVLocs[++i]; // skip ahead to next loc
1360       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1361                                       InFlag);
1362       Chain = Hi.getValue(1);
1363       InFlag = Hi.getValue(2);
1364       if (!Subtarget->isLittle())
1365         std::swap (Lo, Hi);
1366       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1367
1368       if (VA.getLocVT() == MVT::v2f64) {
1369         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1370         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1371                           DAG.getConstant(0, MVT::i32));
1372
1373         VA = RVLocs[++i]; // skip ahead to next loc
1374         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1375         Chain = Lo.getValue(1);
1376         InFlag = Lo.getValue(2);
1377         VA = RVLocs[++i]; // skip ahead to next loc
1378         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1379         Chain = Hi.getValue(1);
1380         InFlag = Hi.getValue(2);
1381         if (!Subtarget->isLittle())
1382           std::swap (Lo, Hi);
1383         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1384         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1385                           DAG.getConstant(1, MVT::i32));
1386       }
1387     } else {
1388       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1389                                InFlag);
1390       Chain = Val.getValue(1);
1391       InFlag = Val.getValue(2);
1392     }
1393
1394     switch (VA.getLocInfo()) {
1395     default: llvm_unreachable("Unknown loc info!");
1396     case CCValAssign::Full: break;
1397     case CCValAssign::BCvt:
1398       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1399       break;
1400     }
1401
1402     InVals.push_back(Val);
1403   }
1404
1405   return Chain;
1406 }
1407
1408 /// LowerMemOpCallTo - Store the argument to the stack.
1409 SDValue
1410 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1411                                     SDValue StackPtr, SDValue Arg,
1412                                     SDLoc dl, SelectionDAG &DAG,
1413                                     const CCValAssign &VA,
1414                                     ISD::ArgFlagsTy Flags) const {
1415   unsigned LocMemOffset = VA.getLocMemOffset();
1416   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1417   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1418   return DAG.getStore(Chain, dl, Arg, PtrOff,
1419                       MachinePointerInfo::getStack(LocMemOffset),
1420                       false, false, 0);
1421 }
1422
1423 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1424                                          SDValue Chain, SDValue &Arg,
1425                                          RegsToPassVector &RegsToPass,
1426                                          CCValAssign &VA, CCValAssign &NextVA,
1427                                          SDValue &StackPtr,
1428                                          SmallVectorImpl<SDValue> &MemOpChains,
1429                                          ISD::ArgFlagsTy Flags) const {
1430
1431   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1432                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1433   unsigned id = Subtarget->isLittle() ? 0 : 1;
1434   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1435
1436   if (NextVA.isRegLoc())
1437     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1438   else {
1439     assert(NextVA.isMemLoc());
1440     if (!StackPtr.getNode())
1441       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1442
1443     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1444                                            dl, DAG, NextVA,
1445                                            Flags));
1446   }
1447 }
1448
1449 /// LowerCall - Lowering a call into a callseq_start <-
1450 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1451 /// nodes.
1452 SDValue
1453 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1454                              SmallVectorImpl<SDValue> &InVals) const {
1455   SelectionDAG &DAG                     = CLI.DAG;
1456   SDLoc &dl                          = CLI.DL;
1457   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1458   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1459   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1460   SDValue Chain                         = CLI.Chain;
1461   SDValue Callee                        = CLI.Callee;
1462   bool &isTailCall                      = CLI.IsTailCall;
1463   CallingConv::ID CallConv              = CLI.CallConv;
1464   bool doesNotRet                       = CLI.DoesNotReturn;
1465   bool isVarArg                         = CLI.IsVarArg;
1466
1467   MachineFunction &MF = DAG.getMachineFunction();
1468   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1469   bool isThisReturn   = false;
1470   bool isSibCall      = false;
1471
1472   // Disable tail calls if they're not supported.
1473   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1474     isTailCall = false;
1475
1476   if (isTailCall) {
1477     // Check if it's really possible to do a tail call.
1478     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1479                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1480                                                    Outs, OutVals, Ins, DAG);
1481     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1482       report_fatal_error("failed to perform tail call elimination on a call "
1483                          "site marked musttail");
1484     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1485     // detected sibcalls.
1486     if (isTailCall) {
1487       ++NumTailCalls;
1488       isSibCall = true;
1489     }
1490   }
1491
1492   // Analyze operands of the call, assigning locations to each operand.
1493   SmallVector<CCValAssign, 16> ArgLocs;
1494   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1495                     *DAG.getContext(), Call);
1496   CCInfo.AnalyzeCallOperands(Outs,
1497                              CCAssignFnForNode(CallConv, /* Return*/ false,
1498                                                isVarArg));
1499
1500   // Get a count of how many bytes are to be pushed on the stack.
1501   unsigned NumBytes = CCInfo.getNextStackOffset();
1502
1503   // For tail calls, memory operands are available in our caller's stack.
1504   if (isSibCall)
1505     NumBytes = 0;
1506
1507   // Adjust the stack pointer for the new arguments...
1508   // These operations are automatically eliminated by the prolog/epilog pass
1509   if (!isSibCall)
1510     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1511                                  dl);
1512
1513   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1514
1515   RegsToPassVector RegsToPass;
1516   SmallVector<SDValue, 8> MemOpChains;
1517
1518   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1519   // of tail call optimization, arguments are handled later.
1520   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1521        i != e;
1522        ++i, ++realArgIdx) {
1523     CCValAssign &VA = ArgLocs[i];
1524     SDValue Arg = OutVals[realArgIdx];
1525     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1526     bool isByVal = Flags.isByVal();
1527
1528     // Promote the value if needed.
1529     switch (VA.getLocInfo()) {
1530     default: llvm_unreachable("Unknown loc info!");
1531     case CCValAssign::Full: break;
1532     case CCValAssign::SExt:
1533       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1534       break;
1535     case CCValAssign::ZExt:
1536       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1537       break;
1538     case CCValAssign::AExt:
1539       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1540       break;
1541     case CCValAssign::BCvt:
1542       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1543       break;
1544     }
1545
1546     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1547     if (VA.needsCustom()) {
1548       if (VA.getLocVT() == MVT::v2f64) {
1549         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1550                                   DAG.getConstant(0, MVT::i32));
1551         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1552                                   DAG.getConstant(1, MVT::i32));
1553
1554         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1555                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1556
1557         VA = ArgLocs[++i]; // skip ahead to next loc
1558         if (VA.isRegLoc()) {
1559           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1560                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1561         } else {
1562           assert(VA.isMemLoc());
1563
1564           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1565                                                  dl, DAG, VA, Flags));
1566         }
1567       } else {
1568         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1569                          StackPtr, MemOpChains, Flags);
1570       }
1571     } else if (VA.isRegLoc()) {
1572       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1573         assert(VA.getLocVT() == MVT::i32 &&
1574                "unexpected calling convention register assignment");
1575         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1576                "unexpected use of 'returned'");
1577         isThisReturn = true;
1578       }
1579       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1580     } else if (isByVal) {
1581       assert(VA.isMemLoc());
1582       unsigned offset = 0;
1583
1584       // True if this byval aggregate will be split between registers
1585       // and memory.
1586       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1587       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1588
1589       if (CurByValIdx < ByValArgsCount) {
1590
1591         unsigned RegBegin, RegEnd;
1592         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1593
1594         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1595         unsigned int i, j;
1596         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1597           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1598           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1599           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1600                                      MachinePointerInfo(),
1601                                      false, false, false,
1602                                      DAG.InferPtrAlignment(AddArg));
1603           MemOpChains.push_back(Load.getValue(1));
1604           RegsToPass.push_back(std::make_pair(j, Load));
1605         }
1606
1607         // If parameter size outsides register area, "offset" value
1608         // helps us to calculate stack slot for remained part properly.
1609         offset = RegEnd - RegBegin;
1610
1611         CCInfo.nextInRegsParam();
1612       }
1613
1614       if (Flags.getByValSize() > 4*offset) {
1615         unsigned LocMemOffset = VA.getLocMemOffset();
1616         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1617         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1618                                   StkPtrOff);
1619         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1620         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1621         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1622                                            MVT::i32);
1623         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1624
1625         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1626         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1627         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1628                                           Ops));
1629       }
1630     } else if (!isSibCall) {
1631       assert(VA.isMemLoc());
1632
1633       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1634                                              dl, DAG, VA, Flags));
1635     }
1636   }
1637
1638   if (!MemOpChains.empty())
1639     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1640
1641   // Build a sequence of copy-to-reg nodes chained together with token chain
1642   // and flag operands which copy the outgoing args into the appropriate regs.
1643   SDValue InFlag;
1644   // Tail call byval lowering might overwrite argument registers so in case of
1645   // tail call optimization the copies to registers are lowered later.
1646   if (!isTailCall)
1647     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1648       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1649                                RegsToPass[i].second, InFlag);
1650       InFlag = Chain.getValue(1);
1651     }
1652
1653   // For tail calls lower the arguments to the 'real' stack slot.
1654   if (isTailCall) {
1655     // Force all the incoming stack arguments to be loaded from the stack
1656     // before any new outgoing arguments are stored to the stack, because the
1657     // outgoing stack slots may alias the incoming argument stack slots, and
1658     // the alias isn't otherwise explicit. This is slightly more conservative
1659     // than necessary, because it means that each store effectively depends
1660     // on every argument instead of just those arguments it would clobber.
1661
1662     // Do not flag preceding copytoreg stuff together with the following stuff.
1663     InFlag = SDValue();
1664     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1665       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1666                                RegsToPass[i].second, InFlag);
1667       InFlag = Chain.getValue(1);
1668     }
1669     InFlag = SDValue();
1670   }
1671
1672   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1673   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1674   // node so that legalize doesn't hack it.
1675   bool isDirect = false;
1676   bool isARMFunc = false;
1677   bool isLocalARMFunc = false;
1678   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1679
1680   if (EnableARMLongCalls) {
1681     assert((Subtarget->isTargetWindows() ||
1682             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1683            "long-calls with non-static relocation model!");
1684     // Handle a global address or an external symbol. If it's not one of
1685     // those, the target's already in a register, so we don't need to do
1686     // anything extra.
1687     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1688       const GlobalValue *GV = G->getGlobal();
1689       // Create a constant pool entry for the callee address
1690       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1691       ARMConstantPoolValue *CPV =
1692         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1693
1694       // Get the address of the callee into a register
1695       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1696       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1697       Callee = DAG.getLoad(getPointerTy(), dl,
1698                            DAG.getEntryNode(), CPAddr,
1699                            MachinePointerInfo::getConstantPool(),
1700                            false, false, false, 0);
1701     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1702       const char *Sym = S->getSymbol();
1703
1704       // Create a constant pool entry for the callee address
1705       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1706       ARMConstantPoolValue *CPV =
1707         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1708                                       ARMPCLabelIndex, 0);
1709       // Get the address of the callee into a register
1710       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1711       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1712       Callee = DAG.getLoad(getPointerTy(), dl,
1713                            DAG.getEntryNode(), CPAddr,
1714                            MachinePointerInfo::getConstantPool(),
1715                            false, false, false, 0);
1716     }
1717   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1718     const GlobalValue *GV = G->getGlobal();
1719     isDirect = true;
1720     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1721     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1722                    getTargetMachine().getRelocationModel() != Reloc::Static;
1723     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1724     // ARM call to a local ARM function is predicable.
1725     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1726     // tBX takes a register source operand.
1727     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1728       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1729       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1730                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1731                                                       0, ARMII::MO_NONLAZY));
1732       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1733                            MachinePointerInfo::getGOT(), false, false, true, 0);
1734     } else if (Subtarget->isTargetCOFF()) {
1735       assert(Subtarget->isTargetWindows() &&
1736              "Windows is the only supported COFF target");
1737       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1738                                  ? ARMII::MO_DLLIMPORT
1739                                  : ARMII::MO_NO_FLAG;
1740       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1741                                           TargetFlags);
1742       if (GV->hasDLLImportStorageClass())
1743         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1744                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1745                                          Callee), MachinePointerInfo::getGOT(),
1746                              false, false, false, 0);
1747     } else {
1748       // On ELF targets for PIC code, direct calls should go through the PLT
1749       unsigned OpFlags = 0;
1750       if (Subtarget->isTargetELF() &&
1751           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1752         OpFlags = ARMII::MO_PLT;
1753       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1754     }
1755   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1756     isDirect = true;
1757     bool isStub = Subtarget->isTargetMachO() &&
1758                   getTargetMachine().getRelocationModel() != Reloc::Static;
1759     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1760     // tBX takes a register source operand.
1761     const char *Sym = S->getSymbol();
1762     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1763       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1764       ARMConstantPoolValue *CPV =
1765         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1766                                       ARMPCLabelIndex, 4);
1767       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1768       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1769       Callee = DAG.getLoad(getPointerTy(), dl,
1770                            DAG.getEntryNode(), CPAddr,
1771                            MachinePointerInfo::getConstantPool(),
1772                            false, false, false, 0);
1773       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1774       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1775                            getPointerTy(), Callee, PICLabel);
1776     } else {
1777       unsigned OpFlags = 0;
1778       // On ELF targets for PIC code, direct calls should go through the PLT
1779       if (Subtarget->isTargetELF() &&
1780                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1781         OpFlags = ARMII::MO_PLT;
1782       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1783     }
1784   }
1785
1786   // FIXME: handle tail calls differently.
1787   unsigned CallOpc;
1788   bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1789       AttributeSet::FunctionIndex, Attribute::MinSize);
1790   if (Subtarget->isThumb()) {
1791     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1792       CallOpc = ARMISD::CALL_NOLINK;
1793     else
1794       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1795   } else {
1796     if (!isDirect && !Subtarget->hasV5TOps())
1797       CallOpc = ARMISD::CALL_NOLINK;
1798     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1799                // Emit regular call when code size is the priority
1800                !HasMinSizeAttr)
1801       // "mov lr, pc; b _foo" to avoid confusing the RSP
1802       CallOpc = ARMISD::CALL_NOLINK;
1803     else
1804       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1805   }
1806
1807   std::vector<SDValue> Ops;
1808   Ops.push_back(Chain);
1809   Ops.push_back(Callee);
1810
1811   // Add argument registers to the end of the list so that they are known live
1812   // into the call.
1813   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1814     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1815                                   RegsToPass[i].second.getValueType()));
1816
1817   // Add a register mask operand representing the call-preserved registers.
1818   if (!isTailCall) {
1819     const uint32_t *Mask;
1820     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1821     if (isThisReturn) {
1822       // For 'this' returns, use the R0-preserving mask if applicable
1823       Mask = ARI->getThisReturnPreservedMask(CallConv);
1824       if (!Mask) {
1825         // Set isThisReturn to false if the calling convention is not one that
1826         // allows 'returned' to be modeled in this way, so LowerCallResult does
1827         // not try to pass 'this' straight through
1828         isThisReturn = false;
1829         Mask = ARI->getCallPreservedMask(CallConv);
1830       }
1831     } else
1832       Mask = ARI->getCallPreservedMask(CallConv);
1833
1834     assert(Mask && "Missing call preserved mask for calling convention");
1835     Ops.push_back(DAG.getRegisterMask(Mask));
1836   }
1837
1838   if (InFlag.getNode())
1839     Ops.push_back(InFlag);
1840
1841   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1842   if (isTailCall)
1843     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1844
1845   // Returns a chain and a flag for retval copy to use.
1846   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1847   InFlag = Chain.getValue(1);
1848
1849   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1850                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1851   if (!Ins.empty())
1852     InFlag = Chain.getValue(1);
1853
1854   // Handle result values, copying them out of physregs into vregs that we
1855   // return.
1856   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1857                          InVals, isThisReturn,
1858                          isThisReturn ? OutVals[0] : SDValue());
1859 }
1860
1861 /// HandleByVal - Every parameter *after* a byval parameter is passed
1862 /// on the stack.  Remember the next parameter register to allocate,
1863 /// and then confiscate the rest of the parameter registers to insure
1864 /// this.
1865 void
1866 ARMTargetLowering::HandleByVal(
1867     CCState *State, unsigned &size, unsigned Align) const {
1868   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1869   assert((State->getCallOrPrologue() == Prologue ||
1870           State->getCallOrPrologue() == Call) &&
1871          "unhandled ParmContext");
1872
1873   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1874     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1875       unsigned AlignInRegs = Align / 4;
1876       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1877       for (unsigned i = 0; i < Waste; ++i)
1878         reg = State->AllocateReg(GPRArgRegs, 4);
1879     }
1880     if (reg != 0) {
1881       unsigned excess = 4 * (ARM::R4 - reg);
1882
1883       // Special case when NSAA != SP and parameter size greater than size of
1884       // all remained GPR regs. In that case we can't split parameter, we must
1885       // send it to stack. We also must set NCRN to R4, so waste all
1886       // remained registers.
1887       const unsigned NSAAOffset = State->getNextStackOffset();
1888       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1889         while (State->AllocateReg(GPRArgRegs, 4))
1890           ;
1891         return;
1892       }
1893
1894       // First register for byval parameter is the first register that wasn't
1895       // allocated before this method call, so it would be "reg".
1896       // If parameter is small enough to be saved in range [reg, r4), then
1897       // the end (first after last) register would be reg + param-size-in-regs,
1898       // else parameter would be splitted between registers and stack,
1899       // end register would be r4 in this case.
1900       unsigned ByValRegBegin = reg;
1901       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1902       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1903       // Note, first register is allocated in the beginning of function already,
1904       // allocate remained amount of registers we need.
1905       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1906         State->AllocateReg(GPRArgRegs, 4);
1907       // A byval parameter that is split between registers and memory needs its
1908       // size truncated here.
1909       // In the case where the entire structure fits in registers, we set the
1910       // size in memory to zero.
1911       if (size < excess)
1912         size = 0;
1913       else
1914         size -= excess;
1915     }
1916   }
1917 }
1918
1919 /// MatchingStackOffset - Return true if the given stack call argument is
1920 /// already available in the same position (relatively) of the caller's
1921 /// incoming argument stack.
1922 static
1923 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1924                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1925                          const TargetInstrInfo *TII) {
1926   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1927   int FI = INT_MAX;
1928   if (Arg.getOpcode() == ISD::CopyFromReg) {
1929     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1930     if (!TargetRegisterInfo::isVirtualRegister(VR))
1931       return false;
1932     MachineInstr *Def = MRI->getVRegDef(VR);
1933     if (!Def)
1934       return false;
1935     if (!Flags.isByVal()) {
1936       if (!TII->isLoadFromStackSlot(Def, FI))
1937         return false;
1938     } else {
1939       return false;
1940     }
1941   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1942     if (Flags.isByVal())
1943       // ByVal argument is passed in as a pointer but it's now being
1944       // dereferenced. e.g.
1945       // define @foo(%struct.X* %A) {
1946       //   tail call @bar(%struct.X* byval %A)
1947       // }
1948       return false;
1949     SDValue Ptr = Ld->getBasePtr();
1950     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1951     if (!FINode)
1952       return false;
1953     FI = FINode->getIndex();
1954   } else
1955     return false;
1956
1957   assert(FI != INT_MAX);
1958   if (!MFI->isFixedObjectIndex(FI))
1959     return false;
1960   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1961 }
1962
1963 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1964 /// for tail call optimization. Targets which want to do tail call
1965 /// optimization should implement this function.
1966 bool
1967 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1968                                                      CallingConv::ID CalleeCC,
1969                                                      bool isVarArg,
1970                                                      bool isCalleeStructRet,
1971                                                      bool isCallerStructRet,
1972                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1973                                     const SmallVectorImpl<SDValue> &OutVals,
1974                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1975                                                      SelectionDAG& DAG) const {
1976   const Function *CallerF = DAG.getMachineFunction().getFunction();
1977   CallingConv::ID CallerCC = CallerF->getCallingConv();
1978   bool CCMatch = CallerCC == CalleeCC;
1979
1980   // Look for obvious safe cases to perform tail call optimization that do not
1981   // require ABI changes. This is what gcc calls sibcall.
1982
1983   // Do not sibcall optimize vararg calls unless the call site is not passing
1984   // any arguments.
1985   if (isVarArg && !Outs.empty())
1986     return false;
1987
1988   // Exception-handling functions need a special set of instructions to indicate
1989   // a return to the hardware. Tail-calling another function would probably
1990   // break this.
1991   if (CallerF->hasFnAttribute("interrupt"))
1992     return false;
1993
1994   // Also avoid sibcall optimization if either caller or callee uses struct
1995   // return semantics.
1996   if (isCalleeStructRet || isCallerStructRet)
1997     return false;
1998
1999   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
2000   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2001   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2002   // support in the assembler and linker to be used. This would need to be
2003   // fixed to fully support tail calls in Thumb1.
2004   //
2005   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2006   // LR.  This means if we need to reload LR, it takes an extra instructions,
2007   // which outweighs the value of the tail call; but here we don't know yet
2008   // whether LR is going to be used.  Probably the right approach is to
2009   // generate the tail call here and turn it back into CALL/RET in
2010   // emitEpilogue if LR is used.
2011
2012   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2013   // but we need to make sure there are enough registers; the only valid
2014   // registers are the 4 used for parameters.  We don't currently do this
2015   // case.
2016   if (Subtarget->isThumb1Only())
2017     return false;
2018
2019   // Externally-defined functions with weak linkage should not be
2020   // tail-called on ARM when the OS does not support dynamic
2021   // pre-emption of symbols, as the AAELF spec requires normal calls
2022   // to undefined weak functions to be replaced with a NOP or jump to the
2023   // next instruction. The behaviour of branch instructions in this
2024   // situation (as used for tail calls) is implementation-defined, so we
2025   // cannot rely on the linker replacing the tail call with a return.
2026   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2027     const GlobalValue *GV = G->getGlobal();
2028     const Triple TT(getTargetMachine().getTargetTriple());
2029     if (GV->hasExternalWeakLinkage() &&
2030         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2031       return false;
2032   }
2033
2034   // If the calling conventions do not match, then we'd better make sure the
2035   // results are returned in the same way as what the caller expects.
2036   if (!CCMatch) {
2037     SmallVector<CCValAssign, 16> RVLocs1;
2038     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2039                        *DAG.getContext(), Call);
2040     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2041
2042     SmallVector<CCValAssign, 16> RVLocs2;
2043     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2044                        *DAG.getContext(), Call);
2045     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2046
2047     if (RVLocs1.size() != RVLocs2.size())
2048       return false;
2049     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2050       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2051         return false;
2052       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2053         return false;
2054       if (RVLocs1[i].isRegLoc()) {
2055         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2056           return false;
2057       } else {
2058         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2059           return false;
2060       }
2061     }
2062   }
2063
2064   // If Caller's vararg or byval argument has been split between registers and
2065   // stack, do not perform tail call, since part of the argument is in caller's
2066   // local frame.
2067   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2068                                       getInfo<ARMFunctionInfo>();
2069   if (AFI_Caller->getArgRegsSaveSize())
2070     return false;
2071
2072   // If the callee takes no arguments then go on to check the results of the
2073   // call.
2074   if (!Outs.empty()) {
2075     // Check if stack adjustment is needed. For now, do not do this if any
2076     // argument is passed on the stack.
2077     SmallVector<CCValAssign, 16> ArgLocs;
2078     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2079                       *DAG.getContext(), Call);
2080     CCInfo.AnalyzeCallOperands(Outs,
2081                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2082     if (CCInfo.getNextStackOffset()) {
2083       MachineFunction &MF = DAG.getMachineFunction();
2084
2085       // Check if the arguments are already laid out in the right way as
2086       // the caller's fixed stack objects.
2087       MachineFrameInfo *MFI = MF.getFrameInfo();
2088       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2089       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2090       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2091            i != e;
2092            ++i, ++realArgIdx) {
2093         CCValAssign &VA = ArgLocs[i];
2094         EVT RegVT = VA.getLocVT();
2095         SDValue Arg = OutVals[realArgIdx];
2096         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2097         if (VA.getLocInfo() == CCValAssign::Indirect)
2098           return false;
2099         if (VA.needsCustom()) {
2100           // f64 and vector types are split into multiple registers or
2101           // register/stack-slot combinations.  The types will not match
2102           // the registers; give up on memory f64 refs until we figure
2103           // out what to do about this.
2104           if (!VA.isRegLoc())
2105             return false;
2106           if (!ArgLocs[++i].isRegLoc())
2107             return false;
2108           if (RegVT == MVT::v2f64) {
2109             if (!ArgLocs[++i].isRegLoc())
2110               return false;
2111             if (!ArgLocs[++i].isRegLoc())
2112               return false;
2113           }
2114         } else if (!VA.isRegLoc()) {
2115           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2116                                    MFI, MRI, TII))
2117             return false;
2118         }
2119       }
2120     }
2121   }
2122
2123   return true;
2124 }
2125
2126 bool
2127 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2128                                   MachineFunction &MF, bool isVarArg,
2129                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2130                                   LLVMContext &Context) const {
2131   SmallVector<CCValAssign, 16> RVLocs;
2132   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2133   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2134                                                     isVarArg));
2135 }
2136
2137 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2138                                     SDLoc DL, SelectionDAG &DAG) {
2139   const MachineFunction &MF = DAG.getMachineFunction();
2140   const Function *F = MF.getFunction();
2141
2142   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2143
2144   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2145   // version of the "preferred return address". These offsets affect the return
2146   // instruction if this is a return from PL1 without hypervisor extensions.
2147   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2148   //    SWI:     0      "subs pc, lr, #0"
2149   //    ABORT:   +4     "subs pc, lr, #4"
2150   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2151   // UNDEF varies depending on where the exception came from ARM or Thumb
2152   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2153
2154   int64_t LROffset;
2155   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2156       IntKind == "ABORT")
2157     LROffset = 4;
2158   else if (IntKind == "SWI" || IntKind == "UNDEF")
2159     LROffset = 0;
2160   else
2161     report_fatal_error("Unsupported interrupt attribute. If present, value "
2162                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2163
2164   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2165
2166   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2167 }
2168
2169 SDValue
2170 ARMTargetLowering::LowerReturn(SDValue Chain,
2171                                CallingConv::ID CallConv, bool isVarArg,
2172                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2173                                const SmallVectorImpl<SDValue> &OutVals,
2174                                SDLoc dl, SelectionDAG &DAG) const {
2175
2176   // CCValAssign - represent the assignment of the return value to a location.
2177   SmallVector<CCValAssign, 16> RVLocs;
2178
2179   // CCState - Info about the registers and stack slots.
2180   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2181                     *DAG.getContext(), Call);
2182
2183   // Analyze outgoing return values.
2184   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2185                                                isVarArg));
2186
2187   SDValue Flag;
2188   SmallVector<SDValue, 4> RetOps;
2189   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2190   bool isLittleEndian = Subtarget->isLittle();
2191
2192   MachineFunction &MF = DAG.getMachineFunction();
2193   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2194   AFI->setReturnRegsCount(RVLocs.size());
2195
2196   // Copy the result values into the output registers.
2197   for (unsigned i = 0, realRVLocIdx = 0;
2198        i != RVLocs.size();
2199        ++i, ++realRVLocIdx) {
2200     CCValAssign &VA = RVLocs[i];
2201     assert(VA.isRegLoc() && "Can only return in registers!");
2202
2203     SDValue Arg = OutVals[realRVLocIdx];
2204
2205     switch (VA.getLocInfo()) {
2206     default: llvm_unreachable("Unknown loc info!");
2207     case CCValAssign::Full: break;
2208     case CCValAssign::BCvt:
2209       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2210       break;
2211     }
2212
2213     if (VA.needsCustom()) {
2214       if (VA.getLocVT() == MVT::v2f64) {
2215         // Extract the first half and return it in two registers.
2216         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2217                                    DAG.getConstant(0, MVT::i32));
2218         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2219                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2220
2221         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2222                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2223                                  Flag);
2224         Flag = Chain.getValue(1);
2225         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2226         VA = RVLocs[++i]; // skip ahead to next loc
2227         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2228                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2229                                  Flag);
2230         Flag = Chain.getValue(1);
2231         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2232         VA = RVLocs[++i]; // skip ahead to next loc
2233
2234         // Extract the 2nd half and fall through to handle it as an f64 value.
2235         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2236                           DAG.getConstant(1, MVT::i32));
2237       }
2238       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2239       // available.
2240       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2241                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2242       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2243                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2244                                Flag);
2245       Flag = Chain.getValue(1);
2246       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2247       VA = RVLocs[++i]; // skip ahead to next loc
2248       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2249                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2250                                Flag);
2251     } else
2252       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2253
2254     // Guarantee that all emitted copies are
2255     // stuck together, avoiding something bad.
2256     Flag = Chain.getValue(1);
2257     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2258   }
2259
2260   // Update chain and glue.
2261   RetOps[0] = Chain;
2262   if (Flag.getNode())
2263     RetOps.push_back(Flag);
2264
2265   // CPUs which aren't M-class use a special sequence to return from
2266   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2267   // though we use "subs pc, lr, #N").
2268   //
2269   // M-class CPUs actually use a normal return sequence with a special
2270   // (hardware-provided) value in LR, so the normal code path works.
2271   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2272       !Subtarget->isMClass()) {
2273     if (Subtarget->isThumb1Only())
2274       report_fatal_error("interrupt attribute is not supported in Thumb1");
2275     return LowerInterruptReturn(RetOps, dl, DAG);
2276   }
2277
2278   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2279 }
2280
2281 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2282   if (N->getNumValues() != 1)
2283     return false;
2284   if (!N->hasNUsesOfValue(1, 0))
2285     return false;
2286
2287   SDValue TCChain = Chain;
2288   SDNode *Copy = *N->use_begin();
2289   if (Copy->getOpcode() == ISD::CopyToReg) {
2290     // If the copy has a glue operand, we conservatively assume it isn't safe to
2291     // perform a tail call.
2292     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2293       return false;
2294     TCChain = Copy->getOperand(0);
2295   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2296     SDNode *VMov = Copy;
2297     // f64 returned in a pair of GPRs.
2298     SmallPtrSet<SDNode*, 2> Copies;
2299     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2300          UI != UE; ++UI) {
2301       if (UI->getOpcode() != ISD::CopyToReg)
2302         return false;
2303       Copies.insert(*UI);
2304     }
2305     if (Copies.size() > 2)
2306       return false;
2307
2308     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2309          UI != UE; ++UI) {
2310       SDValue UseChain = UI->getOperand(0);
2311       if (Copies.count(UseChain.getNode()))
2312         // Second CopyToReg
2313         Copy = *UI;
2314       else {
2315         // We are at the top of this chain.
2316         // If the copy has a glue operand, we conservatively assume it
2317         // isn't safe to perform a tail call.
2318         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2319           return false;
2320         // First CopyToReg
2321         TCChain = UseChain;
2322       }
2323     }
2324   } else if (Copy->getOpcode() == ISD::BITCAST) {
2325     // f32 returned in a single GPR.
2326     if (!Copy->hasOneUse())
2327       return false;
2328     Copy = *Copy->use_begin();
2329     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2330       return false;
2331     // If the copy has a glue operand, we conservatively assume it isn't safe to
2332     // perform a tail call.
2333     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2334       return false;
2335     TCChain = Copy->getOperand(0);
2336   } else {
2337     return false;
2338   }
2339
2340   bool HasRet = false;
2341   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2342        UI != UE; ++UI) {
2343     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2344         UI->getOpcode() != ARMISD::INTRET_FLAG)
2345       return false;
2346     HasRet = true;
2347   }
2348
2349   if (!HasRet)
2350     return false;
2351
2352   Chain = TCChain;
2353   return true;
2354 }
2355
2356 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2357   if (!Subtarget->supportsTailCall())
2358     return false;
2359
2360   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2361     return false;
2362
2363   return !Subtarget->isThumb1Only();
2364 }
2365
2366 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2367 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2368 // one of the above mentioned nodes. It has to be wrapped because otherwise
2369 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2370 // be used to form addressing mode. These wrapped nodes will be selected
2371 // into MOVi.
2372 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2373   EVT PtrVT = Op.getValueType();
2374   // FIXME there is no actual debug info here
2375   SDLoc dl(Op);
2376   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2377   SDValue Res;
2378   if (CP->isMachineConstantPoolEntry())
2379     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2380                                     CP->getAlignment());
2381   else
2382     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2383                                     CP->getAlignment());
2384   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2385 }
2386
2387 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2388   return MachineJumpTableInfo::EK_Inline;
2389 }
2390
2391 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2392                                              SelectionDAG &DAG) const {
2393   MachineFunction &MF = DAG.getMachineFunction();
2394   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2395   unsigned ARMPCLabelIndex = 0;
2396   SDLoc DL(Op);
2397   EVT PtrVT = getPointerTy();
2398   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2399   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2400   SDValue CPAddr;
2401   if (RelocM == Reloc::Static) {
2402     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2403   } else {
2404     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2405     ARMPCLabelIndex = AFI->createPICLabelUId();
2406     ARMConstantPoolValue *CPV =
2407       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2408                                       ARMCP::CPBlockAddress, PCAdj);
2409     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2410   }
2411   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2412   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2413                                MachinePointerInfo::getConstantPool(),
2414                                false, false, false, 0);
2415   if (RelocM == Reloc::Static)
2416     return Result;
2417   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2418   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2419 }
2420
2421 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2422 SDValue
2423 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2424                                                  SelectionDAG &DAG) const {
2425   SDLoc dl(GA);
2426   EVT PtrVT = getPointerTy();
2427   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2428   MachineFunction &MF = DAG.getMachineFunction();
2429   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2430   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2431   ARMConstantPoolValue *CPV =
2432     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2433                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2434   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2435   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2436   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2437                          MachinePointerInfo::getConstantPool(),
2438                          false, false, false, 0);
2439   SDValue Chain = Argument.getValue(1);
2440
2441   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2442   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2443
2444   // call __tls_get_addr.
2445   ArgListTy Args;
2446   ArgListEntry Entry;
2447   Entry.Node = Argument;
2448   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2449   Args.push_back(Entry);
2450
2451   // FIXME: is there useful debug info available here?
2452   TargetLowering::CallLoweringInfo CLI(DAG);
2453   CLI.setDebugLoc(dl).setChain(Chain)
2454     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2455                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2456                0);
2457
2458   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2459   return CallResult.first;
2460 }
2461
2462 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2463 // "local exec" model.
2464 SDValue
2465 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2466                                         SelectionDAG &DAG,
2467                                         TLSModel::Model model) const {
2468   const GlobalValue *GV = GA->getGlobal();
2469   SDLoc dl(GA);
2470   SDValue Offset;
2471   SDValue Chain = DAG.getEntryNode();
2472   EVT PtrVT = getPointerTy();
2473   // Get the Thread Pointer
2474   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2475
2476   if (model == TLSModel::InitialExec) {
2477     MachineFunction &MF = DAG.getMachineFunction();
2478     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2479     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2480     // Initial exec model.
2481     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2482     ARMConstantPoolValue *CPV =
2483       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2484                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2485                                       true);
2486     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2487     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2488     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2489                          MachinePointerInfo::getConstantPool(),
2490                          false, false, false, 0);
2491     Chain = Offset.getValue(1);
2492
2493     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2494     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2495
2496     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2497                          MachinePointerInfo::getConstantPool(),
2498                          false, false, false, 0);
2499   } else {
2500     // local exec model
2501     assert(model == TLSModel::LocalExec);
2502     ARMConstantPoolValue *CPV =
2503       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2504     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2505     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2506     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2507                          MachinePointerInfo::getConstantPool(),
2508                          false, false, false, 0);
2509   }
2510
2511   // The address of the thread local variable is the add of the thread
2512   // pointer with the offset of the variable.
2513   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2514 }
2515
2516 SDValue
2517 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2518   // TODO: implement the "local dynamic" model
2519   assert(Subtarget->isTargetELF() &&
2520          "TLS not implemented for non-ELF targets");
2521   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2522
2523   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2524
2525   switch (model) {
2526     case TLSModel::GeneralDynamic:
2527     case TLSModel::LocalDynamic:
2528       return LowerToTLSGeneralDynamicModel(GA, DAG);
2529     case TLSModel::InitialExec:
2530     case TLSModel::LocalExec:
2531       return LowerToTLSExecModels(GA, DAG, model);
2532   }
2533   llvm_unreachable("bogus TLS model");
2534 }
2535
2536 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2537                                                  SelectionDAG &DAG) const {
2538   EVT PtrVT = getPointerTy();
2539   SDLoc dl(Op);
2540   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2541   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2542     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2543     ARMConstantPoolValue *CPV =
2544       ARMConstantPoolConstant::Create(GV,
2545                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2546     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2547     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2548     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2549                                  CPAddr,
2550                                  MachinePointerInfo::getConstantPool(),
2551                                  false, false, false, 0);
2552     SDValue Chain = Result.getValue(1);
2553     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2554     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2555     if (!UseGOTOFF)
2556       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2557                            MachinePointerInfo::getGOT(),
2558                            false, false, false, 0);
2559     return Result;
2560   }
2561
2562   // If we have T2 ops, we can materialize the address directly via movt/movw
2563   // pair. This is always cheaper.
2564   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2565     ++NumMovwMovt;
2566     // FIXME: Once remat is capable of dealing with instructions with register
2567     // operands, expand this into two nodes.
2568     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2569                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2570   } else {
2571     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2572     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2573     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2574                        MachinePointerInfo::getConstantPool(),
2575                        false, false, false, 0);
2576   }
2577 }
2578
2579 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2580                                                     SelectionDAG &DAG) const {
2581   EVT PtrVT = getPointerTy();
2582   SDLoc dl(Op);
2583   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2584   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2585
2586   if (Subtarget->useMovt(DAG.getMachineFunction()))
2587     ++NumMovwMovt;
2588
2589   // FIXME: Once remat is capable of dealing with instructions with register
2590   // operands, expand this into multiple nodes
2591   unsigned Wrapper =
2592       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2593
2594   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2595   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2596
2597   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2598     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2599                          MachinePointerInfo::getGOT(), false, false, false, 0);
2600   return Result;
2601 }
2602
2603 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2604                                                      SelectionDAG &DAG) const {
2605   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2606   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2607          "Windows on ARM expects to use movw/movt");
2608
2609   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2610   const ARMII::TOF TargetFlags =
2611     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2612   EVT PtrVT = getPointerTy();
2613   SDValue Result;
2614   SDLoc DL(Op);
2615
2616   ++NumMovwMovt;
2617
2618   // FIXME: Once remat is capable of dealing with instructions with register
2619   // operands, expand this into two nodes.
2620   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2621                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2622                                                   TargetFlags));
2623   if (GV->hasDLLImportStorageClass())
2624     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2625                          MachinePointerInfo::getGOT(), false, false, false, 0);
2626   return Result;
2627 }
2628
2629 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2630                                                     SelectionDAG &DAG) const {
2631   assert(Subtarget->isTargetELF() &&
2632          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2633   MachineFunction &MF = DAG.getMachineFunction();
2634   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2635   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2636   EVT PtrVT = getPointerTy();
2637   SDLoc dl(Op);
2638   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2639   ARMConstantPoolValue *CPV =
2640     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2641                                   ARMPCLabelIndex, PCAdj);
2642   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2643   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2644   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2645                                MachinePointerInfo::getConstantPool(),
2646                                false, false, false, 0);
2647   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2648   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2649 }
2650
2651 SDValue
2652 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2653   SDLoc dl(Op);
2654   SDValue Val = DAG.getConstant(0, MVT::i32);
2655   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2656                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2657                      Op.getOperand(1), Val);
2658 }
2659
2660 SDValue
2661 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2662   SDLoc dl(Op);
2663   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2664                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2665 }
2666
2667 SDValue
2668 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2669                                           const ARMSubtarget *Subtarget) const {
2670   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2671   SDLoc dl(Op);
2672   switch (IntNo) {
2673   default: return SDValue();    // Don't custom lower most intrinsics.
2674   case Intrinsic::arm_rbit: {
2675     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2676            "RBIT intrinsic must have i32 type!");
2677     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2678   }
2679   case Intrinsic::arm_thread_pointer: {
2680     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2681     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2682   }
2683   case Intrinsic::eh_sjlj_lsda: {
2684     MachineFunction &MF = DAG.getMachineFunction();
2685     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2686     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2687     EVT PtrVT = getPointerTy();
2688     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2689     SDValue CPAddr;
2690     unsigned PCAdj = (RelocM != Reloc::PIC_)
2691       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2692     ARMConstantPoolValue *CPV =
2693       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2694                                       ARMCP::CPLSDA, PCAdj);
2695     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2696     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2697     SDValue Result =
2698       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2699                   MachinePointerInfo::getConstantPool(),
2700                   false, false, false, 0);
2701
2702     if (RelocM == Reloc::PIC_) {
2703       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2704       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2705     }
2706     return Result;
2707   }
2708   case Intrinsic::arm_neon_vmulls:
2709   case Intrinsic::arm_neon_vmullu: {
2710     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2711       ? ARMISD::VMULLs : ARMISD::VMULLu;
2712     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2713                        Op.getOperand(1), Op.getOperand(2));
2714   }
2715   }
2716 }
2717
2718 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2719                                  const ARMSubtarget *Subtarget) {
2720   // FIXME: handle "fence singlethread" more efficiently.
2721   SDLoc dl(Op);
2722   if (!Subtarget->hasDataBarrier()) {
2723     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2724     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2725     // here.
2726     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2727            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2728     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2729                        DAG.getConstant(0, MVT::i32));
2730   }
2731
2732   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2733   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2734   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2735   if (Subtarget->isMClass()) {
2736     // Only a full system barrier exists in the M-class architectures.
2737     Domain = ARM_MB::SY;
2738   } else if (Subtarget->isSwift() && Ord == Release) {
2739     // Swift happens to implement ISHST barriers in a way that's compatible with
2740     // Release semantics but weaker than ISH so we'd be fools not to use
2741     // it. Beware: other processors probably don't!
2742     Domain = ARM_MB::ISHST;
2743   }
2744
2745   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2746                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2747                      DAG.getConstant(Domain, MVT::i32));
2748 }
2749
2750 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2751                              const ARMSubtarget *Subtarget) {
2752   // ARM pre v5TE and Thumb1 does not have preload instructions.
2753   if (!(Subtarget->isThumb2() ||
2754         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2755     // Just preserve the chain.
2756     return Op.getOperand(0);
2757
2758   SDLoc dl(Op);
2759   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2760   if (!isRead &&
2761       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2762     // ARMv7 with MP extension has PLDW.
2763     return Op.getOperand(0);
2764
2765   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2766   if (Subtarget->isThumb()) {
2767     // Invert the bits.
2768     isRead = ~isRead & 1;
2769     isData = ~isData & 1;
2770   }
2771
2772   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2773                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2774                      DAG.getConstant(isData, MVT::i32));
2775 }
2776
2777 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2778   MachineFunction &MF = DAG.getMachineFunction();
2779   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2780
2781   // vastart just stores the address of the VarArgsFrameIndex slot into the
2782   // memory location argument.
2783   SDLoc dl(Op);
2784   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2785   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2786   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2787   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2788                       MachinePointerInfo(SV), false, false, 0);
2789 }
2790
2791 SDValue
2792 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2793                                         SDValue &Root, SelectionDAG &DAG,
2794                                         SDLoc dl) const {
2795   MachineFunction &MF = DAG.getMachineFunction();
2796   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2797
2798   const TargetRegisterClass *RC;
2799   if (AFI->isThumb1OnlyFunction())
2800     RC = &ARM::tGPRRegClass;
2801   else
2802     RC = &ARM::GPRRegClass;
2803
2804   // Transform the arguments stored in physical registers into virtual ones.
2805   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2806   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2807
2808   SDValue ArgValue2;
2809   if (NextVA.isMemLoc()) {
2810     MachineFrameInfo *MFI = MF.getFrameInfo();
2811     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2812
2813     // Create load node to retrieve arguments from the stack.
2814     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2815     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2816                             MachinePointerInfo::getFixedStack(FI),
2817                             false, false, false, 0);
2818   } else {
2819     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2820     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2821   }
2822   if (!Subtarget->isLittle())
2823     std::swap (ArgValue, ArgValue2);
2824   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2825 }
2826
2827 void
2828 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2829                                   unsigned InRegsParamRecordIdx,
2830                                   unsigned ArgSize,
2831                                   unsigned &ArgRegsSize,
2832                                   unsigned &ArgRegsSaveSize)
2833   const {
2834   unsigned NumGPRs;
2835   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2836     unsigned RBegin, REnd;
2837     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2838     NumGPRs = REnd - RBegin;
2839   } else {
2840     unsigned int firstUnalloced;
2841     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2842                                                 sizeof(GPRArgRegs) /
2843                                                 sizeof(GPRArgRegs[0]));
2844     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2845   }
2846
2847   unsigned Align = Subtarget->getFrameLowering()->getStackAlignment();
2848   ArgRegsSize = NumGPRs * 4;
2849
2850   // If parameter is split between stack and GPRs...
2851   if (NumGPRs && Align > 4 &&
2852       (ArgRegsSize < ArgSize ||
2853         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2854     // Add padding for part of param recovered from GPRs.  For example,
2855     // if Align == 8, its last byte must be at address K*8 - 1.
2856     // We need to do it, since remained (stack) part of parameter has
2857     // stack alignment, and we need to "attach" "GPRs head" without gaps
2858     // to it:
2859     // Stack:
2860     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2861     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2862     //
2863     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2864     unsigned Padding =
2865         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2866     ArgRegsSaveSize = ArgRegsSize + Padding;
2867   } else
2868     // We don't need to extend regs save size for byval parameters if they
2869     // are passed via GPRs only.
2870     ArgRegsSaveSize = ArgRegsSize;
2871 }
2872
2873 // The remaining GPRs hold either the beginning of variable-argument
2874 // data, or the beginning of an aggregate passed by value (usually
2875 // byval).  Either way, we allocate stack slots adjacent to the data
2876 // provided by our caller, and store the unallocated registers there.
2877 // If this is a variadic function, the va_list pointer will begin with
2878 // these values; otherwise, this reassembles a (byval) structure that
2879 // was split between registers and memory.
2880 // Return: The frame index registers were stored into.
2881 int
2882 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2883                                   SDLoc dl, SDValue &Chain,
2884                                   const Value *OrigArg,
2885                                   unsigned InRegsParamRecordIdx,
2886                                   unsigned OffsetFromOrigArg,
2887                                   unsigned ArgOffset,
2888                                   unsigned ArgSize,
2889                                   bool ForceMutable,
2890                                   unsigned ByValStoreOffset,
2891                                   unsigned TotalArgRegsSaveSize) const {
2892
2893   // Currently, two use-cases possible:
2894   // Case #1. Non-var-args function, and we meet first byval parameter.
2895   //          Setup first unallocated register as first byval register;
2896   //          eat all remained registers
2897   //          (these two actions are performed by HandleByVal method).
2898   //          Then, here, we initialize stack frame with
2899   //          "store-reg" instructions.
2900   // Case #2. Var-args function, that doesn't contain byval parameters.
2901   //          The same: eat all remained unallocated registers,
2902   //          initialize stack frame.
2903
2904   MachineFunction &MF = DAG.getMachineFunction();
2905   MachineFrameInfo *MFI = MF.getFrameInfo();
2906   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2907   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2908   unsigned RBegin, REnd;
2909   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2910     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2911     firstRegToSaveIndex = RBegin - ARM::R0;
2912     lastRegToSaveIndex = REnd - ARM::R0;
2913   } else {
2914     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2915       (GPRArgRegs, array_lengthof(GPRArgRegs));
2916     lastRegToSaveIndex = 4;
2917   }
2918
2919   unsigned ArgRegsSize, ArgRegsSaveSize;
2920   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2921                  ArgRegsSize, ArgRegsSaveSize);
2922
2923   // Store any by-val regs to their spots on the stack so that they may be
2924   // loaded by deferencing the result of formal parameter pointer or va_next.
2925   // Note: once stack area for byval/varargs registers
2926   // was initialized, it can't be initialized again.
2927   if (ArgRegsSaveSize) {
2928     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2929
2930     if (Padding) {
2931       assert(AFI->getStoredByValParamsPadding() == 0 &&
2932              "The only parameter may be padded.");
2933       AFI->setStoredByValParamsPadding(Padding);
2934     }
2935
2936     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2937                                             Padding +
2938                                               ByValStoreOffset -
2939                                               (int64_t)TotalArgRegsSaveSize,
2940                                             false);
2941     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2942     if (Padding) {
2943        MFI->CreateFixedObject(Padding,
2944                               ArgOffset + ByValStoreOffset -
2945                                 (int64_t)ArgRegsSaveSize,
2946                               false);
2947     }
2948
2949     SmallVector<SDValue, 4> MemOps;
2950     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2951          ++firstRegToSaveIndex, ++i) {
2952       const TargetRegisterClass *RC;
2953       if (AFI->isThumb1OnlyFunction())
2954         RC = &ARM::tGPRRegClass;
2955       else
2956         RC = &ARM::GPRRegClass;
2957
2958       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2959       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2960       SDValue Store =
2961         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2962                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2963                      false, false, 0);
2964       MemOps.push_back(Store);
2965       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2966                         DAG.getConstant(4, getPointerTy()));
2967     }
2968
2969     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2970
2971     if (!MemOps.empty())
2972       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2973     return FrameIndex;
2974   } else {
2975     if (ArgSize == 0) {
2976       // We cannot allocate a zero-byte object for the first variadic argument,
2977       // so just make up a size.
2978       ArgSize = 4;
2979     }
2980     // This will point to the next argument passed via stack.
2981     return MFI->CreateFixedObject(
2982       ArgSize, ArgOffset, !ForceMutable);
2983   }
2984 }
2985
2986 // Setup stack frame, the va_list pointer will start from.
2987 void
2988 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2989                                         SDLoc dl, SDValue &Chain,
2990                                         unsigned ArgOffset,
2991                                         unsigned TotalArgRegsSaveSize,
2992                                         bool ForceMutable) const {
2993   MachineFunction &MF = DAG.getMachineFunction();
2994   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2995
2996   // Try to store any remaining integer argument regs
2997   // to their spots on the stack so that they may be loaded by deferencing
2998   // the result of va_next.
2999   // If there is no regs to be stored, just point address after last
3000   // argument passed via stack.
3001   int FrameIndex =
3002     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3003                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
3004                    0, TotalArgRegsSaveSize);
3005
3006   AFI->setVarArgsFrameIndex(FrameIndex);
3007 }
3008
3009 SDValue
3010 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3011                                         CallingConv::ID CallConv, bool isVarArg,
3012                                         const SmallVectorImpl<ISD::InputArg>
3013                                           &Ins,
3014                                         SDLoc dl, SelectionDAG &DAG,
3015                                         SmallVectorImpl<SDValue> &InVals)
3016                                           const {
3017   MachineFunction &MF = DAG.getMachineFunction();
3018   MachineFrameInfo *MFI = MF.getFrameInfo();
3019
3020   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3021
3022   // Assign locations to all of the incoming arguments.
3023   SmallVector<CCValAssign, 16> ArgLocs;
3024   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3025                     *DAG.getContext(), Prologue);
3026   CCInfo.AnalyzeFormalArguments(Ins,
3027                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3028                                                   isVarArg));
3029
3030   SmallVector<SDValue, 16> ArgValues;
3031   int lastInsIndex = -1;
3032   SDValue ArgValue;
3033   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3034   unsigned CurArgIdx = 0;
3035
3036   // Initially ArgRegsSaveSize is zero.
3037   // Then we increase this value each time we meet byval parameter.
3038   // We also increase this value in case of varargs function.
3039   AFI->setArgRegsSaveSize(0);
3040
3041   unsigned ByValStoreOffset = 0;
3042   unsigned TotalArgRegsSaveSize = 0;
3043   unsigned ArgRegsSaveSizeMaxAlign = 4;
3044
3045   // Calculate the amount of stack space that we need to allocate to store
3046   // byval and variadic arguments that are passed in registers.
3047   // We need to know this before we allocate the first byval or variadic
3048   // argument, as they will be allocated a stack slot below the CFA (Canonical
3049   // Frame Address, the stack pointer at entry to the function).
3050   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3051     CCValAssign &VA = ArgLocs[i];
3052     if (VA.isMemLoc()) {
3053       int index = VA.getValNo();
3054       if (index != lastInsIndex) {
3055         ISD::ArgFlagsTy Flags = Ins[index].Flags;
3056         if (Flags.isByVal()) {
3057           unsigned ExtraArgRegsSize;
3058           unsigned ExtraArgRegsSaveSize;
3059           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProcessed(),
3060                          Flags.getByValSize(),
3061                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
3062
3063           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3064           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3065               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3066           CCInfo.nextInRegsParam();
3067         }
3068         lastInsIndex = index;
3069       }
3070     }
3071   }
3072   CCInfo.rewindByValRegsInfo();
3073   lastInsIndex = -1;
3074   if (isVarArg && MFI->hasVAStart()) {
3075     unsigned ExtraArgRegsSize;
3076     unsigned ExtraArgRegsSaveSize;
3077     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3078                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
3079     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3080   }
3081   // If the arg regs save area contains N-byte aligned values, the
3082   // bottom of it must be at least N-byte aligned.
3083   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3084   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3085
3086   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3087     CCValAssign &VA = ArgLocs[i];
3088     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3089     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3090     // Arguments stored in registers.
3091     if (VA.isRegLoc()) {
3092       EVT RegVT = VA.getLocVT();
3093
3094       if (VA.needsCustom()) {
3095         // f64 and vector types are split up into multiple registers or
3096         // combinations of registers and stack slots.
3097         if (VA.getLocVT() == MVT::v2f64) {
3098           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3099                                                    Chain, DAG, dl);
3100           VA = ArgLocs[++i]; // skip ahead to next loc
3101           SDValue ArgValue2;
3102           if (VA.isMemLoc()) {
3103             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3104             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3105             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3106                                     MachinePointerInfo::getFixedStack(FI),
3107                                     false, false, false, 0);
3108           } else {
3109             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3110                                              Chain, DAG, dl);
3111           }
3112           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3113           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3114                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3115           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3116                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3117         } else
3118           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3119
3120       } else {
3121         const TargetRegisterClass *RC;
3122
3123         if (RegVT == MVT::f32)
3124           RC = &ARM::SPRRegClass;
3125         else if (RegVT == MVT::f64)
3126           RC = &ARM::DPRRegClass;
3127         else if (RegVT == MVT::v2f64)
3128           RC = &ARM::QPRRegClass;
3129         else if (RegVT == MVT::i32)
3130           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3131                                            : &ARM::GPRRegClass;
3132         else
3133           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3134
3135         // Transform the arguments in physical registers into virtual ones.
3136         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3137         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3138       }
3139
3140       // If this is an 8 or 16-bit value, it is really passed promoted
3141       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3142       // truncate to the right size.
3143       switch (VA.getLocInfo()) {
3144       default: llvm_unreachable("Unknown loc info!");
3145       case CCValAssign::Full: break;
3146       case CCValAssign::BCvt:
3147         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3148         break;
3149       case CCValAssign::SExt:
3150         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3151                                DAG.getValueType(VA.getValVT()));
3152         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3153         break;
3154       case CCValAssign::ZExt:
3155         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3156                                DAG.getValueType(VA.getValVT()));
3157         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3158         break;
3159       }
3160
3161       InVals.push_back(ArgValue);
3162
3163     } else { // VA.isRegLoc()
3164
3165       // sanity check
3166       assert(VA.isMemLoc());
3167       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3168
3169       int index = ArgLocs[i].getValNo();
3170
3171       // Some Ins[] entries become multiple ArgLoc[] entries.
3172       // Process them only once.
3173       if (index != lastInsIndex)
3174         {
3175           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3176           // FIXME: For now, all byval parameter objects are marked mutable.
3177           // This can be changed with more analysis.
3178           // In case of tail call optimization mark all arguments mutable.
3179           // Since they could be overwritten by lowering of arguments in case of
3180           // a tail call.
3181           if (Flags.isByVal()) {
3182             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3183
3184             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3185             int FrameIndex = StoreByValRegs(
3186                 CCInfo, DAG, dl, Chain, CurOrigArg,
3187                 CurByValIndex,
3188                 Ins[VA.getValNo()].PartOffset,
3189                 VA.getLocMemOffset(),
3190                 Flags.getByValSize(),
3191                 true /*force mutable frames*/,
3192                 ByValStoreOffset,
3193                 TotalArgRegsSaveSize);
3194             ByValStoreOffset += Flags.getByValSize();
3195             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3196             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3197             CCInfo.nextInRegsParam();
3198           } else {
3199             unsigned FIOffset = VA.getLocMemOffset();
3200             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3201                                             FIOffset, true);
3202
3203             // Create load nodes to retrieve arguments from the stack.
3204             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3205             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3206                                          MachinePointerInfo::getFixedStack(FI),
3207                                          false, false, false, 0));
3208           }
3209           lastInsIndex = index;
3210         }
3211     }
3212   }
3213
3214   // varargs
3215   if (isVarArg && MFI->hasVAStart())
3216     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3217                          CCInfo.getNextStackOffset(),
3218                          TotalArgRegsSaveSize);
3219
3220   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3221
3222   return Chain;
3223 }
3224
3225 /// isFloatingPointZero - Return true if this is +0.0.
3226 static bool isFloatingPointZero(SDValue Op) {
3227   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3228     return CFP->getValueAPF().isPosZero();
3229   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3230     // Maybe this has already been legalized into the constant pool?
3231     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3232       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3233       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3234         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3235           return CFP->getValueAPF().isPosZero();
3236     }
3237   } else if (Op->getOpcode() == ISD::BITCAST &&
3238              Op->getValueType(0) == MVT::f64) {
3239     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3240     // created by LowerConstantFP().
3241     SDValue BitcastOp = Op->getOperand(0);
3242     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3243       SDValue MoveOp = BitcastOp->getOperand(0);
3244       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3245           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3246         return true;
3247       }
3248     }
3249   }
3250   return false;
3251 }
3252
3253 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3254 /// the given operands.
3255 SDValue
3256 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3257                              SDValue &ARMcc, SelectionDAG &DAG,
3258                              SDLoc dl) const {
3259   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3260     unsigned C = RHSC->getZExtValue();
3261     if (!isLegalICmpImmediate(C)) {
3262       // Constant does not fit, try adjusting it by one?
3263       switch (CC) {
3264       default: break;
3265       case ISD::SETLT:
3266       case ISD::SETGE:
3267         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3268           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3269           RHS = DAG.getConstant(C-1, MVT::i32);
3270         }
3271         break;
3272       case ISD::SETULT:
3273       case ISD::SETUGE:
3274         if (C != 0 && isLegalICmpImmediate(C-1)) {
3275           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3276           RHS = DAG.getConstant(C-1, MVT::i32);
3277         }
3278         break;
3279       case ISD::SETLE:
3280       case ISD::SETGT:
3281         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3282           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3283           RHS = DAG.getConstant(C+1, MVT::i32);
3284         }
3285         break;
3286       case ISD::SETULE:
3287       case ISD::SETUGT:
3288         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3289           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3290           RHS = DAG.getConstant(C+1, MVT::i32);
3291         }
3292         break;
3293       }
3294     }
3295   }
3296
3297   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3298   ARMISD::NodeType CompareType;
3299   switch (CondCode) {
3300   default:
3301     CompareType = ARMISD::CMP;
3302     break;
3303   case ARMCC::EQ:
3304   case ARMCC::NE:
3305     // Uses only Z Flag
3306     CompareType = ARMISD::CMPZ;
3307     break;
3308   }
3309   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3310   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3311 }
3312
3313 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3314 SDValue
3315 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3316                              SDLoc dl) const {
3317   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3318   SDValue Cmp;
3319   if (!isFloatingPointZero(RHS))
3320     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3321   else
3322     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3323   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3324 }
3325
3326 /// duplicateCmp - Glue values can have only one use, so this function
3327 /// duplicates a comparison node.
3328 SDValue
3329 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3330   unsigned Opc = Cmp.getOpcode();
3331   SDLoc DL(Cmp);
3332   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3333     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3334
3335   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3336   Cmp = Cmp.getOperand(0);
3337   Opc = Cmp.getOpcode();
3338   if (Opc == ARMISD::CMPFP)
3339     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3340   else {
3341     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3342     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3343   }
3344   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3345 }
3346
3347 std::pair<SDValue, SDValue>
3348 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3349                                  SDValue &ARMcc) const {
3350   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3351
3352   SDValue Value, OverflowCmp;
3353   SDValue LHS = Op.getOperand(0);
3354   SDValue RHS = Op.getOperand(1);
3355
3356
3357   // FIXME: We are currently always generating CMPs because we don't support
3358   // generating CMN through the backend. This is not as good as the natural
3359   // CMP case because it causes a register dependency and cannot be folded
3360   // later.
3361
3362   switch (Op.getOpcode()) {
3363   default:
3364     llvm_unreachable("Unknown overflow instruction!");
3365   case ISD::SADDO:
3366     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3367     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3368     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3369     break;
3370   case ISD::UADDO:
3371     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3372     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3373     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3374     break;
3375   case ISD::SSUBO:
3376     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3377     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3378     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3379     break;
3380   case ISD::USUBO:
3381     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3382     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3383     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3384     break;
3385   } // switch (...)
3386
3387   return std::make_pair(Value, OverflowCmp);
3388 }
3389
3390
3391 SDValue
3392 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3393   // Let legalize expand this if it isn't a legal type yet.
3394   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3395     return SDValue();
3396
3397   SDValue Value, OverflowCmp;
3398   SDValue ARMcc;
3399   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3400   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3401   // We use 0 and 1 as false and true values.
3402   SDValue TVal = DAG.getConstant(1, MVT::i32);
3403   SDValue FVal = DAG.getConstant(0, MVT::i32);
3404   EVT VT = Op.getValueType();
3405
3406   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3407                                  ARMcc, CCR, OverflowCmp);
3408
3409   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3410   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3411 }
3412
3413
3414 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3415   SDValue Cond = Op.getOperand(0);
3416   SDValue SelectTrue = Op.getOperand(1);
3417   SDValue SelectFalse = Op.getOperand(2);
3418   SDLoc dl(Op);
3419   unsigned Opc = Cond.getOpcode();
3420
3421   if (Cond.getResNo() == 1 &&
3422       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3423        Opc == ISD::USUBO)) {
3424     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3425       return SDValue();
3426
3427     SDValue Value, OverflowCmp;
3428     SDValue ARMcc;
3429     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3430     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3431     EVT VT = Op.getValueType();
3432
3433     return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3434                    OverflowCmp, DAG);
3435   }
3436
3437   // Convert:
3438   //
3439   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3440   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3441   //
3442   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3443     const ConstantSDNode *CMOVTrue =
3444       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3445     const ConstantSDNode *CMOVFalse =
3446       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3447
3448     if (CMOVTrue && CMOVFalse) {
3449       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3450       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3451
3452       SDValue True;
3453       SDValue False;
3454       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3455         True = SelectTrue;
3456         False = SelectFalse;
3457       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3458         True = SelectFalse;
3459         False = SelectTrue;
3460       }
3461
3462       if (True.getNode() && False.getNode()) {
3463         EVT VT = Op.getValueType();
3464         SDValue ARMcc = Cond.getOperand(2);
3465         SDValue CCR = Cond.getOperand(3);
3466         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3467         assert(True.getValueType() == VT);
3468         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3469       }
3470     }
3471   }
3472
3473   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3474   // undefined bits before doing a full-word comparison with zero.
3475   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3476                      DAG.getConstant(1, Cond.getValueType()));
3477
3478   return DAG.getSelectCC(dl, Cond,
3479                          DAG.getConstant(0, Cond.getValueType()),
3480                          SelectTrue, SelectFalse, ISD::SETNE);
3481 }
3482
3483 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3484   if (CC == ISD::SETNE)
3485     return ISD::SETEQ;
3486   return ISD::getSetCCInverse(CC, true);
3487 }
3488
3489 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3490                                  bool &swpCmpOps, bool &swpVselOps) {
3491   // Start by selecting the GE condition code for opcodes that return true for
3492   // 'equality'
3493   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3494       CC == ISD::SETULE)
3495     CondCode = ARMCC::GE;
3496
3497   // and GT for opcodes that return false for 'equality'.
3498   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3499            CC == ISD::SETULT)
3500     CondCode = ARMCC::GT;
3501
3502   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3503   // to swap the compare operands.
3504   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3505       CC == ISD::SETULT)
3506     swpCmpOps = true;
3507
3508   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3509   // If we have an unordered opcode, we need to swap the operands to the VSEL
3510   // instruction (effectively negating the condition).
3511   //
3512   // This also has the effect of swapping which one of 'less' or 'greater'
3513   // returns true, so we also swap the compare operands. It also switches
3514   // whether we return true for 'equality', so we compensate by picking the
3515   // opposite condition code to our original choice.
3516   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3517       CC == ISD::SETUGT) {
3518     swpCmpOps = !swpCmpOps;
3519     swpVselOps = !swpVselOps;
3520     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3521   }
3522
3523   // 'ordered' is 'anything but unordered', so use the VS condition code and
3524   // swap the VSEL operands.
3525   if (CC == ISD::SETO) {
3526     CondCode = ARMCC::VS;
3527     swpVselOps = true;
3528   }
3529
3530   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3531   // code and swap the VSEL operands.
3532   if (CC == ISD::SETUNE) {
3533     CondCode = ARMCC::EQ;
3534     swpVselOps = true;
3535   }
3536 }
3537
3538 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3539                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3540                                    SDValue Cmp, SelectionDAG &DAG) const {
3541   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3542     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3543                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3544     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3545                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3546
3547     SDValue TrueLow = TrueVal.getValue(0);
3548     SDValue TrueHigh = TrueVal.getValue(1);
3549     SDValue FalseLow = FalseVal.getValue(0);
3550     SDValue FalseHigh = FalseVal.getValue(1);
3551
3552     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3553                               ARMcc, CCR, Cmp);
3554     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3555                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3556
3557     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3558   } else {
3559     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3560                        Cmp);
3561   }
3562 }
3563
3564 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3565   EVT VT = Op.getValueType();
3566   SDValue LHS = Op.getOperand(0);
3567   SDValue RHS = Op.getOperand(1);
3568   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3569   SDValue TrueVal = Op.getOperand(2);
3570   SDValue FalseVal = Op.getOperand(3);
3571   SDLoc dl(Op);
3572
3573   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3574     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3575                                                     dl);
3576
3577     // If softenSetCCOperands only returned one value, we should compare it to
3578     // zero.
3579     if (!RHS.getNode()) {
3580       RHS = DAG.getConstant(0, LHS.getValueType());
3581       CC = ISD::SETNE;
3582     }
3583   }
3584
3585   if (LHS.getValueType() == MVT::i32) {
3586     // Try to generate VSEL on ARMv8.
3587     // The VSEL instruction can't use all the usual ARM condition
3588     // codes: it only has two bits to select the condition code, so it's
3589     // constrained to use only GE, GT, VS and EQ.
3590     //
3591     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3592     // swap the operands of the previous compare instruction (effectively
3593     // inverting the compare condition, swapping 'less' and 'greater') and
3594     // sometimes need to swap the operands to the VSEL (which inverts the
3595     // condition in the sense of firing whenever the previous condition didn't)
3596     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3597                                     TrueVal.getValueType() == MVT::f64)) {
3598       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3599       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3600           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3601         CC = getInverseCCForVSEL(CC);
3602         std::swap(TrueVal, FalseVal);
3603       }
3604     }
3605
3606     SDValue ARMcc;
3607     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3608     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3609     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3610   }
3611
3612   ARMCC::CondCodes CondCode, CondCode2;
3613   FPCCToARMCC(CC, CondCode, CondCode2);
3614
3615   // Try to generate VSEL on ARMv8.
3616   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3617                                   TrueVal.getValueType() == MVT::f64)) {
3618     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3619     // same operands, as follows:
3620     //   c = fcmp [ogt, olt, ugt, ult] a, b
3621     //   select c, a, b
3622     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3623     // handled differently than the original code sequence.
3624     if (getTargetMachine().Options.UnsafeFPMath) {
3625       if (LHS == TrueVal && RHS == FalseVal) {
3626         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3627           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3628         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3629           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3630       } else if (LHS == FalseVal && RHS == TrueVal) {
3631         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3632           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3633         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3634           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3635       }
3636     }
3637
3638     bool swpCmpOps = false;
3639     bool swpVselOps = false;
3640     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3641
3642     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3643         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3644       if (swpCmpOps)
3645         std::swap(LHS, RHS);
3646       if (swpVselOps)
3647         std::swap(TrueVal, FalseVal);
3648     }
3649   }
3650
3651   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3652   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3653   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3654   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3655   if (CondCode2 != ARMCC::AL) {
3656     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3657     // FIXME: Needs another CMP because flag can have but one use.
3658     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3659     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3660   }
3661   return Result;
3662 }
3663
3664 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3665 /// to morph to an integer compare sequence.
3666 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3667                            const ARMSubtarget *Subtarget) {
3668   SDNode *N = Op.getNode();
3669   if (!N->hasOneUse())
3670     // Otherwise it requires moving the value from fp to integer registers.
3671     return false;
3672   if (!N->getNumValues())
3673     return false;
3674   EVT VT = Op.getValueType();
3675   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3676     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3677     // vmrs are very slow, e.g. cortex-a8.
3678     return false;
3679
3680   if (isFloatingPointZero(Op)) {
3681     SeenZero = true;
3682     return true;
3683   }
3684   return ISD::isNormalLoad(N);
3685 }
3686
3687 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3688   if (isFloatingPointZero(Op))
3689     return DAG.getConstant(0, MVT::i32);
3690
3691   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3692     return DAG.getLoad(MVT::i32, SDLoc(Op),
3693                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3694                        Ld->isVolatile(), Ld->isNonTemporal(),
3695                        Ld->isInvariant(), Ld->getAlignment());
3696
3697   llvm_unreachable("Unknown VFP cmp argument!");
3698 }
3699
3700 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3701                            SDValue &RetVal1, SDValue &RetVal2) {
3702   if (isFloatingPointZero(Op)) {
3703     RetVal1 = DAG.getConstant(0, MVT::i32);
3704     RetVal2 = DAG.getConstant(0, MVT::i32);
3705     return;
3706   }
3707
3708   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3709     SDValue Ptr = Ld->getBasePtr();
3710     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3711                           Ld->getChain(), Ptr,
3712                           Ld->getPointerInfo(),
3713                           Ld->isVolatile(), Ld->isNonTemporal(),
3714                           Ld->isInvariant(), Ld->getAlignment());
3715
3716     EVT PtrType = Ptr.getValueType();
3717     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3718     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3719                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3720     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3721                           Ld->getChain(), NewPtr,
3722                           Ld->getPointerInfo().getWithOffset(4),
3723                           Ld->isVolatile(), Ld->isNonTemporal(),
3724                           Ld->isInvariant(), NewAlign);
3725     return;
3726   }
3727
3728   llvm_unreachable("Unknown VFP cmp argument!");
3729 }
3730
3731 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3732 /// f32 and even f64 comparisons to integer ones.
3733 SDValue
3734 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3735   SDValue Chain = Op.getOperand(0);
3736   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3737   SDValue LHS = Op.getOperand(2);
3738   SDValue RHS = Op.getOperand(3);
3739   SDValue Dest = Op.getOperand(4);
3740   SDLoc dl(Op);
3741
3742   bool LHSSeenZero = false;
3743   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3744   bool RHSSeenZero = false;
3745   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3746   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3747     // If unsafe fp math optimization is enabled and there are no other uses of
3748     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3749     // to an integer comparison.
3750     if (CC == ISD::SETOEQ)
3751       CC = ISD::SETEQ;
3752     else if (CC == ISD::SETUNE)
3753       CC = ISD::SETNE;
3754
3755     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3756     SDValue ARMcc;
3757     if (LHS.getValueType() == MVT::f32) {
3758       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3759                         bitcastf32Toi32(LHS, DAG), Mask);
3760       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3761                         bitcastf32Toi32(RHS, DAG), Mask);
3762       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3763       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3764       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3765                          Chain, Dest, ARMcc, CCR, Cmp);
3766     }
3767
3768     SDValue LHS1, LHS2;
3769     SDValue RHS1, RHS2;
3770     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3771     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3772     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3773     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3774     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3775     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3776     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3777     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3778     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3779   }
3780
3781   return SDValue();
3782 }
3783
3784 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3785   SDValue Chain = Op.getOperand(0);
3786   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3787   SDValue LHS = Op.getOperand(2);
3788   SDValue RHS = Op.getOperand(3);
3789   SDValue Dest = Op.getOperand(4);
3790   SDLoc dl(Op);
3791
3792   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3793     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3794                                                     dl);
3795
3796     // If softenSetCCOperands only returned one value, we should compare it to
3797     // zero.
3798     if (!RHS.getNode()) {
3799       RHS = DAG.getConstant(0, LHS.getValueType());
3800       CC = ISD::SETNE;
3801     }
3802   }
3803
3804   if (LHS.getValueType() == MVT::i32) {
3805     SDValue ARMcc;
3806     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3807     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3808     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3809                        Chain, Dest, ARMcc, CCR, Cmp);
3810   }
3811
3812   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3813
3814   if (getTargetMachine().Options.UnsafeFPMath &&
3815       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3816        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3817     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3818     if (Result.getNode())
3819       return Result;
3820   }
3821
3822   ARMCC::CondCodes CondCode, CondCode2;
3823   FPCCToARMCC(CC, CondCode, CondCode2);
3824
3825   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3826   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3827   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3828   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3829   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3830   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3831   if (CondCode2 != ARMCC::AL) {
3832     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3833     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3834     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3835   }
3836   return Res;
3837 }
3838
3839 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3840   SDValue Chain = Op.getOperand(0);
3841   SDValue Table = Op.getOperand(1);
3842   SDValue Index = Op.getOperand(2);
3843   SDLoc dl(Op);
3844
3845   EVT PTy = getPointerTy();
3846   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3847   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3848   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3849   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3850   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3851   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3852   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3853   if (Subtarget->isThumb2()) {
3854     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3855     // which does another jump to the destination. This also makes it easier
3856     // to translate it to TBB / TBH later.
3857     // FIXME: This might not work if the function is extremely large.
3858     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3859                        Addr, Op.getOperand(2), JTI, UId);
3860   }
3861   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3862     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3863                        MachinePointerInfo::getJumpTable(),
3864                        false, false, false, 0);
3865     Chain = Addr.getValue(1);
3866     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3867     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3868   } else {
3869     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3870                        MachinePointerInfo::getJumpTable(),
3871                        false, false, false, 0);
3872     Chain = Addr.getValue(1);
3873     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3874   }
3875 }
3876
3877 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3878   EVT VT = Op.getValueType();
3879   SDLoc dl(Op);
3880
3881   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3882     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3883       return Op;
3884     return DAG.UnrollVectorOp(Op.getNode());
3885   }
3886
3887   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3888          "Invalid type for custom lowering!");
3889   if (VT != MVT::v4i16)
3890     return DAG.UnrollVectorOp(Op.getNode());
3891
3892   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3893   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3894 }
3895
3896 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3897   EVT VT = Op.getValueType();
3898   if (VT.isVector())
3899     return LowerVectorFP_TO_INT(Op, DAG);
3900
3901   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3902     RTLIB::Libcall LC;
3903     if (Op.getOpcode() == ISD::FP_TO_SINT)
3904       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3905                               Op.getValueType());
3906     else
3907       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3908                               Op.getValueType());
3909     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3910                        /*isSigned*/ false, SDLoc(Op)).first;
3911   }
3912
3913   SDLoc dl(Op);
3914   unsigned Opc;
3915
3916   switch (Op.getOpcode()) {
3917   default: llvm_unreachable("Invalid opcode!");
3918   case ISD::FP_TO_SINT:
3919     Opc = ARMISD::FTOSI;
3920     break;
3921   case ISD::FP_TO_UINT:
3922     Opc = ARMISD::FTOUI;
3923     break;
3924   }
3925   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3926   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3927 }
3928
3929 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3930   EVT VT = Op.getValueType();
3931   SDLoc dl(Op);
3932
3933   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3934     if (VT.getVectorElementType() == MVT::f32)
3935       return Op;
3936     return DAG.UnrollVectorOp(Op.getNode());
3937   }
3938
3939   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3940          "Invalid type for custom lowering!");
3941   if (VT != MVT::v4f32)
3942     return DAG.UnrollVectorOp(Op.getNode());
3943
3944   unsigned CastOpc;
3945   unsigned Opc;
3946   switch (Op.getOpcode()) {
3947   default: llvm_unreachable("Invalid opcode!");
3948   case ISD::SINT_TO_FP:
3949     CastOpc = ISD::SIGN_EXTEND;
3950     Opc = ISD::SINT_TO_FP;
3951     break;
3952   case ISD::UINT_TO_FP:
3953     CastOpc = ISD::ZERO_EXTEND;
3954     Opc = ISD::UINT_TO_FP;
3955     break;
3956   }
3957
3958   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3959   return DAG.getNode(Opc, dl, VT, Op);
3960 }
3961
3962 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3963   EVT VT = Op.getValueType();
3964   if (VT.isVector())
3965     return LowerVectorINT_TO_FP(Op, DAG);
3966
3967   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3968     RTLIB::Libcall LC;
3969     if (Op.getOpcode() == ISD::SINT_TO_FP)
3970       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3971                               Op.getValueType());
3972     else
3973       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3974                               Op.getValueType());
3975     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3976                        /*isSigned*/ false, SDLoc(Op)).first;
3977   }
3978
3979   SDLoc dl(Op);
3980   unsigned Opc;
3981
3982   switch (Op.getOpcode()) {
3983   default: llvm_unreachable("Invalid opcode!");
3984   case ISD::SINT_TO_FP:
3985     Opc = ARMISD::SITOF;
3986     break;
3987   case ISD::UINT_TO_FP:
3988     Opc = ARMISD::UITOF;
3989     break;
3990   }
3991
3992   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3993   return DAG.getNode(Opc, dl, VT, Op);
3994 }
3995
3996 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3997   // Implement fcopysign with a fabs and a conditional fneg.
3998   SDValue Tmp0 = Op.getOperand(0);
3999   SDValue Tmp1 = Op.getOperand(1);
4000   SDLoc dl(Op);
4001   EVT VT = Op.getValueType();
4002   EVT SrcVT = Tmp1.getValueType();
4003   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4004     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4005   bool UseNEON = !InGPR && Subtarget->hasNEON();
4006
4007   if (UseNEON) {
4008     // Use VBSL to copy the sign bit.
4009     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4010     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4011                                DAG.getTargetConstant(EncodedVal, MVT::i32));
4012     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4013     if (VT == MVT::f64)
4014       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4015                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4016                          DAG.getConstant(32, MVT::i32));
4017     else /*if (VT == MVT::f32)*/
4018       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4019     if (SrcVT == MVT::f32) {
4020       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4021       if (VT == MVT::f64)
4022         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4023                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4024                            DAG.getConstant(32, MVT::i32));
4025     } else if (VT == MVT::f32)
4026       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4027                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4028                          DAG.getConstant(32, MVT::i32));
4029     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4030     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4031
4032     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4033                                             MVT::i32);
4034     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4035     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4036                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4037
4038     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4039                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4040                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4041     if (VT == MVT::f32) {
4042       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4043       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4044                         DAG.getConstant(0, MVT::i32));
4045     } else {
4046       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4047     }
4048
4049     return Res;
4050   }
4051
4052   // Bitcast operand 1 to i32.
4053   if (SrcVT == MVT::f64)
4054     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4055                        Tmp1).getValue(1);
4056   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4057
4058   // Or in the signbit with integer operations.
4059   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4060   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4061   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4062   if (VT == MVT::f32) {
4063     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4064                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4065     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4066                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4067   }
4068
4069   // f64: Or the high part with signbit and then combine two parts.
4070   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4071                      Tmp0);
4072   SDValue Lo = Tmp0.getValue(0);
4073   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4074   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4075   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4076 }
4077
4078 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4079   MachineFunction &MF = DAG.getMachineFunction();
4080   MachineFrameInfo *MFI = MF.getFrameInfo();
4081   MFI->setReturnAddressIsTaken(true);
4082
4083   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4084     return SDValue();
4085
4086   EVT VT = Op.getValueType();
4087   SDLoc dl(Op);
4088   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4089   if (Depth) {
4090     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4091     SDValue Offset = DAG.getConstant(4, MVT::i32);
4092     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4093                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4094                        MachinePointerInfo(), false, false, false, 0);
4095   }
4096
4097   // Return LR, which contains the return address. Mark it an implicit live-in.
4098   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4099   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4100 }
4101
4102 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4103   const ARMBaseRegisterInfo &ARI =
4104     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4105   MachineFunction &MF = DAG.getMachineFunction();
4106   MachineFrameInfo *MFI = MF.getFrameInfo();
4107   MFI->setFrameAddressIsTaken(true);
4108
4109   EVT VT = Op.getValueType();
4110   SDLoc dl(Op);  // FIXME probably not meaningful
4111   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4112   unsigned FrameReg = ARI.getFrameRegister(MF);
4113   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4114   while (Depth--)
4115     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4116                             MachinePointerInfo(),
4117                             false, false, false, 0);
4118   return FrameAddr;
4119 }
4120
4121 // FIXME? Maybe this could be a TableGen attribute on some registers and
4122 // this table could be generated automatically from RegInfo.
4123 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4124                                               EVT VT) const {
4125   unsigned Reg = StringSwitch<unsigned>(RegName)
4126                        .Case("sp", ARM::SP)
4127                        .Default(0);
4128   if (Reg)
4129     return Reg;
4130   report_fatal_error("Invalid register name global variable");
4131 }
4132
4133 /// ExpandBITCAST - If the target supports VFP, this function is called to
4134 /// expand a bit convert where either the source or destination type is i64 to
4135 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4136 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4137 /// vectors), since the legalizer won't know what to do with that.
4138 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4139   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4140   SDLoc dl(N);
4141   SDValue Op = N->getOperand(0);
4142
4143   // This function is only supposed to be called for i64 types, either as the
4144   // source or destination of the bit convert.
4145   EVT SrcVT = Op.getValueType();
4146   EVT DstVT = N->getValueType(0);
4147   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4148          "ExpandBITCAST called for non-i64 type");
4149
4150   // Turn i64->f64 into VMOVDRR.
4151   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4152     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4153                              DAG.getConstant(0, MVT::i32));
4154     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4155                              DAG.getConstant(1, MVT::i32));
4156     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4157                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4158   }
4159
4160   // Turn f64->i64 into VMOVRRD.
4161   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4162     SDValue Cvt;
4163     if (TLI.isBigEndian() && SrcVT.isVector() &&
4164         SrcVT.getVectorNumElements() > 1)
4165       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4166                         DAG.getVTList(MVT::i32, MVT::i32),
4167                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4168     else
4169       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4170                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4171     // Merge the pieces into a single i64 value.
4172     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4173   }
4174
4175   return SDValue();
4176 }
4177
4178 /// getZeroVector - Returns a vector of specified type with all zero elements.
4179 /// Zero vectors are used to represent vector negation and in those cases
4180 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4181 /// not support i64 elements, so sometimes the zero vectors will need to be
4182 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4183 /// zero vector.
4184 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4185   assert(VT.isVector() && "Expected a vector type");
4186   // The canonical modified immediate encoding of a zero vector is....0!
4187   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4188   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4189   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4190   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4191 }
4192
4193 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4194 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4195 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4196                                                 SelectionDAG &DAG) const {
4197   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4198   EVT VT = Op.getValueType();
4199   unsigned VTBits = VT.getSizeInBits();
4200   SDLoc dl(Op);
4201   SDValue ShOpLo = Op.getOperand(0);
4202   SDValue ShOpHi = Op.getOperand(1);
4203   SDValue ShAmt  = Op.getOperand(2);
4204   SDValue ARMcc;
4205   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4206
4207   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4208
4209   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4210                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4211   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4212   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4213                                    DAG.getConstant(VTBits, MVT::i32));
4214   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4215   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4216   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4217
4218   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4219   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4220                           ARMcc, DAG, dl);
4221   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4222   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4223                            CCR, Cmp);
4224
4225   SDValue Ops[2] = { Lo, Hi };
4226   return DAG.getMergeValues(Ops, dl);
4227 }
4228
4229 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4230 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4231 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4232                                                SelectionDAG &DAG) const {
4233   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4234   EVT VT = Op.getValueType();
4235   unsigned VTBits = VT.getSizeInBits();
4236   SDLoc dl(Op);
4237   SDValue ShOpLo = Op.getOperand(0);
4238   SDValue ShOpHi = Op.getOperand(1);
4239   SDValue ShAmt  = Op.getOperand(2);
4240   SDValue ARMcc;
4241
4242   assert(Op.getOpcode() == ISD::SHL_PARTS);
4243   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4244                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4245   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4246   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4247                                    DAG.getConstant(VTBits, MVT::i32));
4248   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4249   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4250
4251   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4252   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4253   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4254                           ARMcc, DAG, dl);
4255   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4256   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4257                            CCR, Cmp);
4258
4259   SDValue Ops[2] = { Lo, Hi };
4260   return DAG.getMergeValues(Ops, dl);
4261 }
4262
4263 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4264                                             SelectionDAG &DAG) const {
4265   // The rounding mode is in bits 23:22 of the FPSCR.
4266   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4267   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4268   // so that the shift + and get folded into a bitfield extract.
4269   SDLoc dl(Op);
4270   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4271                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4272                                               MVT::i32));
4273   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4274                                   DAG.getConstant(1U << 22, MVT::i32));
4275   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4276                               DAG.getConstant(22, MVT::i32));
4277   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4278                      DAG.getConstant(3, MVT::i32));
4279 }
4280
4281 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4282                          const ARMSubtarget *ST) {
4283   EVT VT = N->getValueType(0);
4284   SDLoc dl(N);
4285
4286   if (!ST->hasV6T2Ops())
4287     return SDValue();
4288
4289   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4290   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4291 }
4292
4293 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4294 /// for each 16-bit element from operand, repeated.  The basic idea is to
4295 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4296 ///
4297 /// Trace for v4i16:
4298 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4299 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4300 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4301 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4302 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4303 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4304 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4305 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4306 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4307   EVT VT = N->getValueType(0);
4308   SDLoc DL(N);
4309
4310   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4311   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4312   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4313   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4314   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4315   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4316 }
4317
4318 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4319 /// bit-count for each 16-bit element from the operand.  We need slightly
4320 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4321 /// 64/128-bit registers.
4322 ///
4323 /// Trace for v4i16:
4324 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4325 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4326 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4327 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4328 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4329   EVT VT = N->getValueType(0);
4330   SDLoc DL(N);
4331
4332   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4333   if (VT.is64BitVector()) {
4334     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4335     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4336                        DAG.getIntPtrConstant(0));
4337   } else {
4338     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4339                                     BitCounts, DAG.getIntPtrConstant(0));
4340     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4341   }
4342 }
4343
4344 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4345 /// bit-count for each 32-bit element from the operand.  The idea here is
4346 /// to split the vector into 16-bit elements, leverage the 16-bit count
4347 /// routine, and then combine the results.
4348 ///
4349 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4350 /// input    = [v0    v1    ] (vi: 32-bit elements)
4351 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4352 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4353 /// vrev: N0 = [k1 k0 k3 k2 ]
4354 ///            [k0 k1 k2 k3 ]
4355 ///       N1 =+[k1 k0 k3 k2 ]
4356 ///            [k0 k2 k1 k3 ]
4357 ///       N2 =+[k1 k3 k0 k2 ]
4358 ///            [k0    k2    k1    k3    ]
4359 /// Extended =+[k1    k3    k0    k2    ]
4360 ///            [k0    k2    ]
4361 /// Extracted=+[k1    k3    ]
4362 ///
4363 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4364   EVT VT = N->getValueType(0);
4365   SDLoc DL(N);
4366
4367   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4368
4369   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4370   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4371   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4372   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4373   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4374
4375   if (VT.is64BitVector()) {
4376     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4377     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4378                        DAG.getIntPtrConstant(0));
4379   } else {
4380     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4381                                     DAG.getIntPtrConstant(0));
4382     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4383   }
4384 }
4385
4386 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4387                           const ARMSubtarget *ST) {
4388   EVT VT = N->getValueType(0);
4389
4390   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4391   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4392           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4393          "Unexpected type for custom ctpop lowering");
4394
4395   if (VT.getVectorElementType() == MVT::i32)
4396     return lowerCTPOP32BitElements(N, DAG);
4397   else
4398     return lowerCTPOP16BitElements(N, DAG);
4399 }
4400
4401 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4402                           const ARMSubtarget *ST) {
4403   EVT VT = N->getValueType(0);
4404   SDLoc dl(N);
4405
4406   if (!VT.isVector())
4407     return SDValue();
4408
4409   // Lower vector shifts on NEON to use VSHL.
4410   assert(ST->hasNEON() && "unexpected vector shift");
4411
4412   // Left shifts translate directly to the vshiftu intrinsic.
4413   if (N->getOpcode() == ISD::SHL)
4414     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4415                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4416                        N->getOperand(0), N->getOperand(1));
4417
4418   assert((N->getOpcode() == ISD::SRA ||
4419           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4420
4421   // NEON uses the same intrinsics for both left and right shifts.  For
4422   // right shifts, the shift amounts are negative, so negate the vector of
4423   // shift amounts.
4424   EVT ShiftVT = N->getOperand(1).getValueType();
4425   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4426                                      getZeroVector(ShiftVT, DAG, dl),
4427                                      N->getOperand(1));
4428   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4429                              Intrinsic::arm_neon_vshifts :
4430                              Intrinsic::arm_neon_vshiftu);
4431   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4432                      DAG.getConstant(vshiftInt, MVT::i32),
4433                      N->getOperand(0), NegatedCount);
4434 }
4435
4436 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4437                                 const ARMSubtarget *ST) {
4438   EVT VT = N->getValueType(0);
4439   SDLoc dl(N);
4440
4441   // We can get here for a node like i32 = ISD::SHL i32, i64
4442   if (VT != MVT::i64)
4443     return SDValue();
4444
4445   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4446          "Unknown shift to lower!");
4447
4448   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4449   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4450       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4451     return SDValue();
4452
4453   // If we are in thumb mode, we don't have RRX.
4454   if (ST->isThumb1Only()) return SDValue();
4455
4456   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4457   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4458                            DAG.getConstant(0, MVT::i32));
4459   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4460                            DAG.getConstant(1, MVT::i32));
4461
4462   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4463   // captures the result into a carry flag.
4464   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4465   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4466
4467   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4468   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4469
4470   // Merge the pieces into a single i64 value.
4471  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4472 }
4473
4474 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4475   SDValue TmpOp0, TmpOp1;
4476   bool Invert = false;
4477   bool Swap = false;
4478   unsigned Opc = 0;
4479
4480   SDValue Op0 = Op.getOperand(0);
4481   SDValue Op1 = Op.getOperand(1);
4482   SDValue CC = Op.getOperand(2);
4483   EVT VT = Op.getValueType();
4484   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4485   SDLoc dl(Op);
4486
4487   if (Op1.getValueType().isFloatingPoint()) {
4488     switch (SetCCOpcode) {
4489     default: llvm_unreachable("Illegal FP comparison");
4490     case ISD::SETUNE:
4491     case ISD::SETNE:  Invert = true; // Fallthrough
4492     case ISD::SETOEQ:
4493     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4494     case ISD::SETOLT:
4495     case ISD::SETLT: Swap = true; // Fallthrough
4496     case ISD::SETOGT:
4497     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4498     case ISD::SETOLE:
4499     case ISD::SETLE:  Swap = true; // Fallthrough
4500     case ISD::SETOGE:
4501     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4502     case ISD::SETUGE: Swap = true; // Fallthrough
4503     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4504     case ISD::SETUGT: Swap = true; // Fallthrough
4505     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4506     case ISD::SETUEQ: Invert = true; // Fallthrough
4507     case ISD::SETONE:
4508       // Expand this to (OLT | OGT).
4509       TmpOp0 = Op0;
4510       TmpOp1 = Op1;
4511       Opc = ISD::OR;
4512       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4513       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4514       break;
4515     case ISD::SETUO: Invert = true; // Fallthrough
4516     case ISD::SETO:
4517       // Expand this to (OLT | OGE).
4518       TmpOp0 = Op0;
4519       TmpOp1 = Op1;
4520       Opc = ISD::OR;
4521       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4522       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4523       break;
4524     }
4525   } else {
4526     // Integer comparisons.
4527     switch (SetCCOpcode) {
4528     default: llvm_unreachable("Illegal integer comparison");
4529     case ISD::SETNE:  Invert = true;
4530     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4531     case ISD::SETLT:  Swap = true;
4532     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4533     case ISD::SETLE:  Swap = true;
4534     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4535     case ISD::SETULT: Swap = true;
4536     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4537     case ISD::SETULE: Swap = true;
4538     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4539     }
4540
4541     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4542     if (Opc == ARMISD::VCEQ) {
4543
4544       SDValue AndOp;
4545       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4546         AndOp = Op0;
4547       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4548         AndOp = Op1;
4549
4550       // Ignore bitconvert.
4551       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4552         AndOp = AndOp.getOperand(0);
4553
4554       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4555         Opc = ARMISD::VTST;
4556         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4557         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4558         Invert = !Invert;
4559       }
4560     }
4561   }
4562
4563   if (Swap)
4564     std::swap(Op0, Op1);
4565
4566   // If one of the operands is a constant vector zero, attempt to fold the
4567   // comparison to a specialized compare-against-zero form.
4568   SDValue SingleOp;
4569   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4570     SingleOp = Op0;
4571   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4572     if (Opc == ARMISD::VCGE)
4573       Opc = ARMISD::VCLEZ;
4574     else if (Opc == ARMISD::VCGT)
4575       Opc = ARMISD::VCLTZ;
4576     SingleOp = Op1;
4577   }
4578
4579   SDValue Result;
4580   if (SingleOp.getNode()) {
4581     switch (Opc) {
4582     case ARMISD::VCEQ:
4583       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4584     case ARMISD::VCGE:
4585       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4586     case ARMISD::VCLEZ:
4587       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4588     case ARMISD::VCGT:
4589       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4590     case ARMISD::VCLTZ:
4591       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4592     default:
4593       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4594     }
4595   } else {
4596      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4597   }
4598
4599   if (Invert)
4600     Result = DAG.getNOT(dl, Result, VT);
4601
4602   return Result;
4603 }
4604
4605 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4606 /// valid vector constant for a NEON instruction with a "modified immediate"
4607 /// operand (e.g., VMOV).  If so, return the encoded value.
4608 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4609                                  unsigned SplatBitSize, SelectionDAG &DAG,
4610                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4611   unsigned OpCmode, Imm;
4612
4613   // SplatBitSize is set to the smallest size that splats the vector, so a
4614   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4615   // immediate instructions others than VMOV do not support the 8-bit encoding
4616   // of a zero vector, and the default encoding of zero is supposed to be the
4617   // 32-bit version.
4618   if (SplatBits == 0)
4619     SplatBitSize = 32;
4620
4621   switch (SplatBitSize) {
4622   case 8:
4623     if (type != VMOVModImm)
4624       return SDValue();
4625     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4626     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4627     OpCmode = 0xe;
4628     Imm = SplatBits;
4629     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4630     break;
4631
4632   case 16:
4633     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4634     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4635     if ((SplatBits & ~0xff) == 0) {
4636       // Value = 0x00nn: Op=x, Cmode=100x.
4637       OpCmode = 0x8;
4638       Imm = SplatBits;
4639       break;
4640     }
4641     if ((SplatBits & ~0xff00) == 0) {
4642       // Value = 0xnn00: Op=x, Cmode=101x.
4643       OpCmode = 0xa;
4644       Imm = SplatBits >> 8;
4645       break;
4646     }
4647     return SDValue();
4648
4649   case 32:
4650     // NEON's 32-bit VMOV supports splat values where:
4651     // * only one byte is nonzero, or
4652     // * the least significant byte is 0xff and the second byte is nonzero, or
4653     // * the least significant 2 bytes are 0xff and the third is nonzero.
4654     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4655     if ((SplatBits & ~0xff) == 0) {
4656       // Value = 0x000000nn: Op=x, Cmode=000x.
4657       OpCmode = 0;
4658       Imm = SplatBits;
4659       break;
4660     }
4661     if ((SplatBits & ~0xff00) == 0) {
4662       // Value = 0x0000nn00: Op=x, Cmode=001x.
4663       OpCmode = 0x2;
4664       Imm = SplatBits >> 8;
4665       break;
4666     }
4667     if ((SplatBits & ~0xff0000) == 0) {
4668       // Value = 0x00nn0000: Op=x, Cmode=010x.
4669       OpCmode = 0x4;
4670       Imm = SplatBits >> 16;
4671       break;
4672     }
4673     if ((SplatBits & ~0xff000000) == 0) {
4674       // Value = 0xnn000000: Op=x, Cmode=011x.
4675       OpCmode = 0x6;
4676       Imm = SplatBits >> 24;
4677       break;
4678     }
4679
4680     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4681     if (type == OtherModImm) return SDValue();
4682
4683     if ((SplatBits & ~0xffff) == 0 &&
4684         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4685       // Value = 0x0000nnff: Op=x, Cmode=1100.
4686       OpCmode = 0xc;
4687       Imm = SplatBits >> 8;
4688       break;
4689     }
4690
4691     if ((SplatBits & ~0xffffff) == 0 &&
4692         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4693       // Value = 0x00nnffff: Op=x, Cmode=1101.
4694       OpCmode = 0xd;
4695       Imm = SplatBits >> 16;
4696       break;
4697     }
4698
4699     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4700     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4701     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4702     // and fall through here to test for a valid 64-bit splat.  But, then the
4703     // caller would also need to check and handle the change in size.
4704     return SDValue();
4705
4706   case 64: {
4707     if (type != VMOVModImm)
4708       return SDValue();
4709     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4710     uint64_t BitMask = 0xff;
4711     uint64_t Val = 0;
4712     unsigned ImmMask = 1;
4713     Imm = 0;
4714     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4715       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4716         Val |= BitMask;
4717         Imm |= ImmMask;
4718       } else if ((SplatBits & BitMask) != 0) {
4719         return SDValue();
4720       }
4721       BitMask <<= 8;
4722       ImmMask <<= 1;
4723     }
4724
4725     if (DAG.getTargetLoweringInfo().isBigEndian())
4726       // swap higher and lower 32 bit word
4727       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4728
4729     // Op=1, Cmode=1110.
4730     OpCmode = 0x1e;
4731     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4732     break;
4733   }
4734
4735   default:
4736     llvm_unreachable("unexpected size for isNEONModifiedImm");
4737   }
4738
4739   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4740   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4741 }
4742
4743 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4744                                            const ARMSubtarget *ST) const {
4745   if (!ST->hasVFP3())
4746     return SDValue();
4747
4748   bool IsDouble = Op.getValueType() == MVT::f64;
4749   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4750
4751   // Use the default (constant pool) lowering for double constants when we have
4752   // an SP-only FPU
4753   if (IsDouble && Subtarget->isFPOnlySP())
4754     return SDValue();
4755
4756   // Try splatting with a VMOV.f32...
4757   APFloat FPVal = CFP->getValueAPF();
4758   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4759
4760   if (ImmVal != -1) {
4761     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4762       // We have code in place to select a valid ConstantFP already, no need to
4763       // do any mangling.
4764       return Op;
4765     }
4766
4767     // It's a float and we are trying to use NEON operations where
4768     // possible. Lower it to a splat followed by an extract.
4769     SDLoc DL(Op);
4770     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4771     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4772                                       NewVal);
4773     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4774                        DAG.getConstant(0, MVT::i32));
4775   }
4776
4777   // The rest of our options are NEON only, make sure that's allowed before
4778   // proceeding..
4779   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4780     return SDValue();
4781
4782   EVT VMovVT;
4783   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4784
4785   // It wouldn't really be worth bothering for doubles except for one very
4786   // important value, which does happen to match: 0.0. So make sure we don't do
4787   // anything stupid.
4788   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4789     return SDValue();
4790
4791   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4792   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4793                                      false, VMOVModImm);
4794   if (NewVal != SDValue()) {
4795     SDLoc DL(Op);
4796     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4797                                       NewVal);
4798     if (IsDouble)
4799       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4800
4801     // It's a float: cast and extract a vector element.
4802     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4803                                        VecConstant);
4804     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4805                        DAG.getConstant(0, MVT::i32));
4806   }
4807
4808   // Finally, try a VMVN.i32
4809   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4810                              false, VMVNModImm);
4811   if (NewVal != SDValue()) {
4812     SDLoc DL(Op);
4813     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4814
4815     if (IsDouble)
4816       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4817
4818     // It's a float: cast and extract a vector element.
4819     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4820                                        VecConstant);
4821     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4822                        DAG.getConstant(0, MVT::i32));
4823   }
4824
4825   return SDValue();
4826 }
4827
4828 // check if an VEXT instruction can handle the shuffle mask when the
4829 // vector sources of the shuffle are the same.
4830 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4831   unsigned NumElts = VT.getVectorNumElements();
4832
4833   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4834   if (M[0] < 0)
4835     return false;
4836
4837   Imm = M[0];
4838
4839   // If this is a VEXT shuffle, the immediate value is the index of the first
4840   // element.  The other shuffle indices must be the successive elements after
4841   // the first one.
4842   unsigned ExpectedElt = Imm;
4843   for (unsigned i = 1; i < NumElts; ++i) {
4844     // Increment the expected index.  If it wraps around, just follow it
4845     // back to index zero and keep going.
4846     ++ExpectedElt;
4847     if (ExpectedElt == NumElts)
4848       ExpectedElt = 0;
4849
4850     if (M[i] < 0) continue; // ignore UNDEF indices
4851     if (ExpectedElt != static_cast<unsigned>(M[i]))
4852       return false;
4853   }
4854
4855   return true;
4856 }
4857
4858
4859 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4860                        bool &ReverseVEXT, unsigned &Imm) {
4861   unsigned NumElts = VT.getVectorNumElements();
4862   ReverseVEXT = false;
4863
4864   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4865   if (M[0] < 0)
4866     return false;
4867
4868   Imm = M[0];
4869
4870   // If this is a VEXT shuffle, the immediate value is the index of the first
4871   // element.  The other shuffle indices must be the successive elements after
4872   // the first one.
4873   unsigned ExpectedElt = Imm;
4874   for (unsigned i = 1; i < NumElts; ++i) {
4875     // Increment the expected index.  If it wraps around, it may still be
4876     // a VEXT but the source vectors must be swapped.
4877     ExpectedElt += 1;
4878     if (ExpectedElt == NumElts * 2) {
4879       ExpectedElt = 0;
4880       ReverseVEXT = true;
4881     }
4882
4883     if (M[i] < 0) continue; // ignore UNDEF indices
4884     if (ExpectedElt != static_cast<unsigned>(M[i]))
4885       return false;
4886   }
4887
4888   // Adjust the index value if the source operands will be swapped.
4889   if (ReverseVEXT)
4890     Imm -= NumElts;
4891
4892   return true;
4893 }
4894
4895 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4896 /// instruction with the specified blocksize.  (The order of the elements
4897 /// within each block of the vector is reversed.)
4898 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4899   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4900          "Only possible block sizes for VREV are: 16, 32, 64");
4901
4902   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4903   if (EltSz == 64)
4904     return false;
4905
4906   unsigned NumElts = VT.getVectorNumElements();
4907   unsigned BlockElts = M[0] + 1;
4908   // If the first shuffle index is UNDEF, be optimistic.
4909   if (M[0] < 0)
4910     BlockElts = BlockSize / EltSz;
4911
4912   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4913     return false;
4914
4915   for (unsigned i = 0; i < NumElts; ++i) {
4916     if (M[i] < 0) continue; // ignore UNDEF indices
4917     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4918       return false;
4919   }
4920
4921   return true;
4922 }
4923
4924 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4925   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4926   // range, then 0 is placed into the resulting vector. So pretty much any mask
4927   // of 8 elements can work here.
4928   return VT == MVT::v8i8 && M.size() == 8;
4929 }
4930
4931 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4932   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4933   if (EltSz == 64)
4934     return false;
4935
4936   unsigned NumElts = VT.getVectorNumElements();
4937   WhichResult = (M[0] == 0 ? 0 : 1);
4938   for (unsigned i = 0; i < NumElts; i += 2) {
4939     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4940         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4941       return false;
4942   }
4943   return true;
4944 }
4945
4946 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4947 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4948 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4949 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4950   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4951   if (EltSz == 64)
4952     return false;
4953
4954   unsigned NumElts = VT.getVectorNumElements();
4955   WhichResult = (M[0] == 0 ? 0 : 1);
4956   for (unsigned i = 0; i < NumElts; i += 2) {
4957     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4958         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4959       return false;
4960   }
4961   return true;
4962 }
4963
4964 static bool isVUZPMask(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) {
4972     if (M[i] < 0) continue; // ignore UNDEF indices
4973     if ((unsigned) M[i] != 2 * i + WhichResult)
4974       return false;
4975   }
4976
4977   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4978   if (VT.is64BitVector() && EltSz == 32)
4979     return false;
4980
4981   return true;
4982 }
4983
4984 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4985 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4986 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4987 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4988   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4989   if (EltSz == 64)
4990     return false;
4991
4992   unsigned Half = VT.getVectorNumElements() / 2;
4993   WhichResult = (M[0] == 0 ? 0 : 1);
4994   for (unsigned j = 0; j != 2; ++j) {
4995     unsigned Idx = WhichResult;
4996     for (unsigned i = 0; i != Half; ++i) {
4997       int MIdx = M[i + j * Half];
4998       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4999         return false;
5000       Idx += 2;
5001     }
5002   }
5003
5004   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5005   if (VT.is64BitVector() && EltSz == 32)
5006     return false;
5007
5008   return true;
5009 }
5010
5011 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5012   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5013   if (EltSz == 64)
5014     return false;
5015
5016   unsigned NumElts = VT.getVectorNumElements();
5017   WhichResult = (M[0] == 0 ? 0 : 1);
5018   unsigned Idx = WhichResult * NumElts / 2;
5019   for (unsigned i = 0; i != NumElts; i += 2) {
5020     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5021         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5022       return false;
5023     Idx += 1;
5024   }
5025
5026   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5027   if (VT.is64BitVector() && EltSz == 32)
5028     return false;
5029
5030   return true;
5031 }
5032
5033 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5034 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5035 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5036 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5037   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5038   if (EltSz == 64)
5039     return false;
5040
5041   unsigned NumElts = VT.getVectorNumElements();
5042   WhichResult = (M[0] == 0 ? 0 : 1);
5043   unsigned Idx = WhichResult * NumElts / 2;
5044   for (unsigned i = 0; i != NumElts; i += 2) {
5045     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5046         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5047       return false;
5048     Idx += 1;
5049   }
5050
5051   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5052   if (VT.is64BitVector() && EltSz == 32)
5053     return false;
5054
5055   return true;
5056 }
5057
5058 /// \return true if this is a reverse operation on an vector.
5059 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5060   unsigned NumElts = VT.getVectorNumElements();
5061   // Make sure the mask has the right size.
5062   if (NumElts != M.size())
5063       return false;
5064
5065   // Look for <15, ..., 3, -1, 1, 0>.
5066   for (unsigned i = 0; i != NumElts; ++i)
5067     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5068       return false;
5069
5070   return true;
5071 }
5072
5073 // If N is an integer constant that can be moved into a register in one
5074 // instruction, return an SDValue of such a constant (will become a MOV
5075 // instruction).  Otherwise return null.
5076 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5077                                      const ARMSubtarget *ST, SDLoc dl) {
5078   uint64_t Val;
5079   if (!isa<ConstantSDNode>(N))
5080     return SDValue();
5081   Val = cast<ConstantSDNode>(N)->getZExtValue();
5082
5083   if (ST->isThumb1Only()) {
5084     if (Val <= 255 || ~Val <= 255)
5085       return DAG.getConstant(Val, MVT::i32);
5086   } else {
5087     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5088       return DAG.getConstant(Val, MVT::i32);
5089   }
5090   return SDValue();
5091 }
5092
5093 // If this is a case we can't handle, return null and let the default
5094 // expansion code take care of it.
5095 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5096                                              const ARMSubtarget *ST) const {
5097   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5098   SDLoc dl(Op);
5099   EVT VT = Op.getValueType();
5100
5101   APInt SplatBits, SplatUndef;
5102   unsigned SplatBitSize;
5103   bool HasAnyUndefs;
5104   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5105     if (SplatBitSize <= 64) {
5106       // Check if an immediate VMOV works.
5107       EVT VmovVT;
5108       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5109                                       SplatUndef.getZExtValue(), SplatBitSize,
5110                                       DAG, VmovVT, VT.is128BitVector(),
5111                                       VMOVModImm);
5112       if (Val.getNode()) {
5113         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5114         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5115       }
5116
5117       // Try an immediate VMVN.
5118       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5119       Val = isNEONModifiedImm(NegatedImm,
5120                                       SplatUndef.getZExtValue(), SplatBitSize,
5121                                       DAG, VmovVT, VT.is128BitVector(),
5122                                       VMVNModImm);
5123       if (Val.getNode()) {
5124         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5125         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5126       }
5127
5128       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5129       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5130         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5131         if (ImmVal != -1) {
5132           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5133           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5134         }
5135       }
5136     }
5137   }
5138
5139   // Scan through the operands to see if only one value is used.
5140   //
5141   // As an optimisation, even if more than one value is used it may be more
5142   // profitable to splat with one value then change some lanes.
5143   //
5144   // Heuristically we decide to do this if the vector has a "dominant" value,
5145   // defined as splatted to more than half of the lanes.
5146   unsigned NumElts = VT.getVectorNumElements();
5147   bool isOnlyLowElement = true;
5148   bool usesOnlyOneValue = true;
5149   bool hasDominantValue = false;
5150   bool isConstant = true;
5151
5152   // Map of the number of times a particular SDValue appears in the
5153   // element list.
5154   DenseMap<SDValue, unsigned> ValueCounts;
5155   SDValue Value;
5156   for (unsigned i = 0; i < NumElts; ++i) {
5157     SDValue V = Op.getOperand(i);
5158     if (V.getOpcode() == ISD::UNDEF)
5159       continue;
5160     if (i > 0)
5161       isOnlyLowElement = false;
5162     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5163       isConstant = false;
5164
5165     ValueCounts.insert(std::make_pair(V, 0));
5166     unsigned &Count = ValueCounts[V];
5167
5168     // Is this value dominant? (takes up more than half of the lanes)
5169     if (++Count > (NumElts / 2)) {
5170       hasDominantValue = true;
5171       Value = V;
5172     }
5173   }
5174   if (ValueCounts.size() != 1)
5175     usesOnlyOneValue = false;
5176   if (!Value.getNode() && ValueCounts.size() > 0)
5177     Value = ValueCounts.begin()->first;
5178
5179   if (ValueCounts.size() == 0)
5180     return DAG.getUNDEF(VT);
5181
5182   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5183   // Keep going if we are hitting this case.
5184   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5185     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5186
5187   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5188
5189   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5190   // i32 and try again.
5191   if (hasDominantValue && EltSize <= 32) {
5192     if (!isConstant) {
5193       SDValue N;
5194
5195       // If we are VDUPing a value that comes directly from a vector, that will
5196       // cause an unnecessary move to and from a GPR, where instead we could
5197       // just use VDUPLANE. We can only do this if the lane being extracted
5198       // is at a constant index, as the VDUP from lane instructions only have
5199       // constant-index forms.
5200       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5201           isa<ConstantSDNode>(Value->getOperand(1))) {
5202         // We need to create a new undef vector to use for the VDUPLANE if the
5203         // size of the vector from which we get the value is different than the
5204         // size of the vector that we need to create. We will insert the element
5205         // such that the register coalescer will remove unnecessary copies.
5206         if (VT != Value->getOperand(0).getValueType()) {
5207           ConstantSDNode *constIndex;
5208           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5209           assert(constIndex && "The index is not a constant!");
5210           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5211                              VT.getVectorNumElements();
5212           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5213                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5214                         Value, DAG.getConstant(index, MVT::i32)),
5215                            DAG.getConstant(index, MVT::i32));
5216         } else
5217           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5218                         Value->getOperand(0), Value->getOperand(1));
5219       } else
5220         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5221
5222       if (!usesOnlyOneValue) {
5223         // The dominant value was splatted as 'N', but we now have to insert
5224         // all differing elements.
5225         for (unsigned I = 0; I < NumElts; ++I) {
5226           if (Op.getOperand(I) == Value)
5227             continue;
5228           SmallVector<SDValue, 3> Ops;
5229           Ops.push_back(N);
5230           Ops.push_back(Op.getOperand(I));
5231           Ops.push_back(DAG.getConstant(I, MVT::i32));
5232           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5233         }
5234       }
5235       return N;
5236     }
5237     if (VT.getVectorElementType().isFloatingPoint()) {
5238       SmallVector<SDValue, 8> Ops;
5239       for (unsigned i = 0; i < NumElts; ++i)
5240         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5241                                   Op.getOperand(i)));
5242       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5243       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5244       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5245       if (Val.getNode())
5246         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5247     }
5248     if (usesOnlyOneValue) {
5249       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5250       if (isConstant && Val.getNode())
5251         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5252     }
5253   }
5254
5255   // If all elements are constants and the case above didn't get hit, fall back
5256   // to the default expansion, which will generate a load from the constant
5257   // pool.
5258   if (isConstant)
5259     return SDValue();
5260
5261   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5262   if (NumElts >= 4) {
5263     SDValue shuffle = ReconstructShuffle(Op, DAG);
5264     if (shuffle != SDValue())
5265       return shuffle;
5266   }
5267
5268   // Vectors with 32- or 64-bit elements can be built by directly assigning
5269   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5270   // will be legalized.
5271   if (EltSize >= 32) {
5272     // Do the expansion with floating-point types, since that is what the VFP
5273     // registers are defined to use, and since i64 is not legal.
5274     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5275     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5276     SmallVector<SDValue, 8> Ops;
5277     for (unsigned i = 0; i < NumElts; ++i)
5278       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5279     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5280     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5281   }
5282
5283   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5284   // know the default expansion would otherwise fall back on something even
5285   // worse. For a vector with one or two non-undef values, that's
5286   // scalar_to_vector for the elements followed by a shuffle (provided the
5287   // shuffle is valid for the target) and materialization element by element
5288   // on the stack followed by a load for everything else.
5289   if (!isConstant && !usesOnlyOneValue) {
5290     SDValue Vec = DAG.getUNDEF(VT);
5291     for (unsigned i = 0 ; i < NumElts; ++i) {
5292       SDValue V = Op.getOperand(i);
5293       if (V.getOpcode() == ISD::UNDEF)
5294         continue;
5295       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5296       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5297     }
5298     return Vec;
5299   }
5300
5301   return SDValue();
5302 }
5303
5304 // Gather data to see if the operation can be modelled as a
5305 // shuffle in combination with VEXTs.
5306 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5307                                               SelectionDAG &DAG) const {
5308   SDLoc dl(Op);
5309   EVT VT = Op.getValueType();
5310   unsigned NumElts = VT.getVectorNumElements();
5311
5312   SmallVector<SDValue, 2> SourceVecs;
5313   SmallVector<unsigned, 2> MinElts;
5314   SmallVector<unsigned, 2> MaxElts;
5315
5316   for (unsigned i = 0; i < NumElts; ++i) {
5317     SDValue V = Op.getOperand(i);
5318     if (V.getOpcode() == ISD::UNDEF)
5319       continue;
5320     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5321       // A shuffle can only come from building a vector from various
5322       // elements of other vectors.
5323       return SDValue();
5324     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5325                VT.getVectorElementType()) {
5326       // This code doesn't know how to handle shuffles where the vector
5327       // element types do not match (this happens because type legalization
5328       // promotes the return type of EXTRACT_VECTOR_ELT).
5329       // FIXME: It might be appropriate to extend this code to handle
5330       // mismatched types.
5331       return SDValue();
5332     }
5333
5334     // Record this extraction against the appropriate vector if possible...
5335     SDValue SourceVec = V.getOperand(0);
5336     // If the element number isn't a constant, we can't effectively
5337     // analyze what's going on.
5338     if (!isa<ConstantSDNode>(V.getOperand(1)))
5339       return SDValue();
5340     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5341     bool FoundSource = false;
5342     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5343       if (SourceVecs[j] == SourceVec) {
5344         if (MinElts[j] > EltNo)
5345           MinElts[j] = EltNo;
5346         if (MaxElts[j] < EltNo)
5347           MaxElts[j] = EltNo;
5348         FoundSource = true;
5349         break;
5350       }
5351     }
5352
5353     // Or record a new source if not...
5354     if (!FoundSource) {
5355       SourceVecs.push_back(SourceVec);
5356       MinElts.push_back(EltNo);
5357       MaxElts.push_back(EltNo);
5358     }
5359   }
5360
5361   // Currently only do something sane when at most two source vectors
5362   // involved.
5363   if (SourceVecs.size() > 2)
5364     return SDValue();
5365
5366   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5367   int VEXTOffsets[2] = {0, 0};
5368
5369   // This loop extracts the usage patterns of the source vectors
5370   // and prepares appropriate SDValues for a shuffle if possible.
5371   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5372     if (SourceVecs[i].getValueType() == VT) {
5373       // No VEXT necessary
5374       ShuffleSrcs[i] = SourceVecs[i];
5375       VEXTOffsets[i] = 0;
5376       continue;
5377     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5378       // It probably isn't worth padding out a smaller vector just to
5379       // break it down again in a shuffle.
5380       return SDValue();
5381     }
5382
5383     // Since only 64-bit and 128-bit vectors are legal on ARM and
5384     // we've eliminated the other cases...
5385     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5386            "unexpected vector sizes in ReconstructShuffle");
5387
5388     if (MaxElts[i] - MinElts[i] >= NumElts) {
5389       // Span too large for a VEXT to cope
5390       return SDValue();
5391     }
5392
5393     if (MinElts[i] >= NumElts) {
5394       // The extraction can just take the second half
5395       VEXTOffsets[i] = NumElts;
5396       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5397                                    SourceVecs[i],
5398                                    DAG.getIntPtrConstant(NumElts));
5399     } else if (MaxElts[i] < NumElts) {
5400       // The extraction can just take the first half
5401       VEXTOffsets[i] = 0;
5402       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5403                                    SourceVecs[i],
5404                                    DAG.getIntPtrConstant(0));
5405     } else {
5406       // An actual VEXT is needed
5407       VEXTOffsets[i] = MinElts[i];
5408       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5409                                      SourceVecs[i],
5410                                      DAG.getIntPtrConstant(0));
5411       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5412                                      SourceVecs[i],
5413                                      DAG.getIntPtrConstant(NumElts));
5414       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5415                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5416     }
5417   }
5418
5419   SmallVector<int, 8> Mask;
5420
5421   for (unsigned i = 0; i < NumElts; ++i) {
5422     SDValue Entry = Op.getOperand(i);
5423     if (Entry.getOpcode() == ISD::UNDEF) {
5424       Mask.push_back(-1);
5425       continue;
5426     }
5427
5428     SDValue ExtractVec = Entry.getOperand(0);
5429     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5430                                           .getOperand(1))->getSExtValue();
5431     if (ExtractVec == SourceVecs[0]) {
5432       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5433     } else {
5434       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5435     }
5436   }
5437
5438   // Final check before we try to produce nonsense...
5439   if (isShuffleMaskLegal(Mask, VT))
5440     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5441                                 &Mask[0]);
5442
5443   return SDValue();
5444 }
5445
5446 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5447 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5448 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5449 /// are assumed to be legal.
5450 bool
5451 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5452                                       EVT VT) const {
5453   if (VT.getVectorNumElements() == 4 &&
5454       (VT.is128BitVector() || VT.is64BitVector())) {
5455     unsigned PFIndexes[4];
5456     for (unsigned i = 0; i != 4; ++i) {
5457       if (M[i] < 0)
5458         PFIndexes[i] = 8;
5459       else
5460         PFIndexes[i] = M[i];
5461     }
5462
5463     // Compute the index in the perfect shuffle table.
5464     unsigned PFTableIndex =
5465       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5466     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5467     unsigned Cost = (PFEntry >> 30);
5468
5469     if (Cost <= 4)
5470       return true;
5471   }
5472
5473   bool ReverseVEXT;
5474   unsigned Imm, WhichResult;
5475
5476   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5477   return (EltSize >= 32 ||
5478           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5479           isVREVMask(M, VT, 64) ||
5480           isVREVMask(M, VT, 32) ||
5481           isVREVMask(M, VT, 16) ||
5482           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5483           isVTBLMask(M, VT) ||
5484           isVTRNMask(M, VT, WhichResult) ||
5485           isVUZPMask(M, VT, WhichResult) ||
5486           isVZIPMask(M, VT, WhichResult) ||
5487           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5488           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5489           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5490           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5491 }
5492
5493 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5494 /// the specified operations to build the shuffle.
5495 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5496                                       SDValue RHS, SelectionDAG &DAG,
5497                                       SDLoc dl) {
5498   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5499   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5500   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5501
5502   enum {
5503     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5504     OP_VREV,
5505     OP_VDUP0,
5506     OP_VDUP1,
5507     OP_VDUP2,
5508     OP_VDUP3,
5509     OP_VEXT1,
5510     OP_VEXT2,
5511     OP_VEXT3,
5512     OP_VUZPL, // VUZP, left result
5513     OP_VUZPR, // VUZP, right result
5514     OP_VZIPL, // VZIP, left result
5515     OP_VZIPR, // VZIP, right result
5516     OP_VTRNL, // VTRN, left result
5517     OP_VTRNR  // VTRN, right result
5518   };
5519
5520   if (OpNum == OP_COPY) {
5521     if (LHSID == (1*9+2)*9+3) return LHS;
5522     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5523     return RHS;
5524   }
5525
5526   SDValue OpLHS, OpRHS;
5527   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5528   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5529   EVT VT = OpLHS.getValueType();
5530
5531   switch (OpNum) {
5532   default: llvm_unreachable("Unknown shuffle opcode!");
5533   case OP_VREV:
5534     // VREV divides the vector in half and swaps within the half.
5535     if (VT.getVectorElementType() == MVT::i32 ||
5536         VT.getVectorElementType() == MVT::f32)
5537       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5538     // vrev <4 x i16> -> VREV32
5539     if (VT.getVectorElementType() == MVT::i16)
5540       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5541     // vrev <4 x i8> -> VREV16
5542     assert(VT.getVectorElementType() == MVT::i8);
5543     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5544   case OP_VDUP0:
5545   case OP_VDUP1:
5546   case OP_VDUP2:
5547   case OP_VDUP3:
5548     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5549                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5550   case OP_VEXT1:
5551   case OP_VEXT2:
5552   case OP_VEXT3:
5553     return DAG.getNode(ARMISD::VEXT, dl, VT,
5554                        OpLHS, OpRHS,
5555                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5556   case OP_VUZPL:
5557   case OP_VUZPR:
5558     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5559                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5560   case OP_VZIPL:
5561   case OP_VZIPR:
5562     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5563                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5564   case OP_VTRNL:
5565   case OP_VTRNR:
5566     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5567                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5568   }
5569 }
5570
5571 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5572                                        ArrayRef<int> ShuffleMask,
5573                                        SelectionDAG &DAG) {
5574   // Check to see if we can use the VTBL instruction.
5575   SDValue V1 = Op.getOperand(0);
5576   SDValue V2 = Op.getOperand(1);
5577   SDLoc DL(Op);
5578
5579   SmallVector<SDValue, 8> VTBLMask;
5580   for (ArrayRef<int>::iterator
5581          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5582     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5583
5584   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5585     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5586                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5587
5588   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5589                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5590 }
5591
5592 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5593                                                       SelectionDAG &DAG) {
5594   SDLoc DL(Op);
5595   SDValue OpLHS = Op.getOperand(0);
5596   EVT VT = OpLHS.getValueType();
5597
5598   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5599          "Expect an v8i16/v16i8 type");
5600   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5601   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5602   // extract the first 8 bytes into the top double word and the last 8 bytes
5603   // into the bottom double word. The v8i16 case is similar.
5604   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5605   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5606                      DAG.getConstant(ExtractNum, MVT::i32));
5607 }
5608
5609 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5610   SDValue V1 = Op.getOperand(0);
5611   SDValue V2 = Op.getOperand(1);
5612   SDLoc dl(Op);
5613   EVT VT = Op.getValueType();
5614   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5615
5616   // Convert shuffles that are directly supported on NEON to target-specific
5617   // DAG nodes, instead of keeping them as shuffles and matching them again
5618   // during code selection.  This is more efficient and avoids the possibility
5619   // of inconsistencies between legalization and selection.
5620   // FIXME: floating-point vectors should be canonicalized to integer vectors
5621   // of the same time so that they get CSEd properly.
5622   ArrayRef<int> ShuffleMask = SVN->getMask();
5623
5624   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5625   if (EltSize <= 32) {
5626     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5627       int Lane = SVN->getSplatIndex();
5628       // If this is undef splat, generate it via "just" vdup, if possible.
5629       if (Lane == -1) Lane = 0;
5630
5631       // Test if V1 is a SCALAR_TO_VECTOR.
5632       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5633         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5634       }
5635       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5636       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5637       // reaches it).
5638       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5639           !isa<ConstantSDNode>(V1.getOperand(0))) {
5640         bool IsScalarToVector = true;
5641         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5642           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5643             IsScalarToVector = false;
5644             break;
5645           }
5646         if (IsScalarToVector)
5647           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5648       }
5649       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5650                          DAG.getConstant(Lane, MVT::i32));
5651     }
5652
5653     bool ReverseVEXT;
5654     unsigned Imm;
5655     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5656       if (ReverseVEXT)
5657         std::swap(V1, V2);
5658       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5659                          DAG.getConstant(Imm, MVT::i32));
5660     }
5661
5662     if (isVREVMask(ShuffleMask, VT, 64))
5663       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5664     if (isVREVMask(ShuffleMask, VT, 32))
5665       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5666     if (isVREVMask(ShuffleMask, VT, 16))
5667       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5668
5669     if (V2->getOpcode() == ISD::UNDEF &&
5670         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5671       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5672                          DAG.getConstant(Imm, MVT::i32));
5673     }
5674
5675     // Check for Neon shuffles that modify both input vectors in place.
5676     // If both results are used, i.e., if there are two shuffles with the same
5677     // source operands and with masks corresponding to both results of one of
5678     // these operations, DAG memoization will ensure that a single node is
5679     // used for both shuffles.
5680     unsigned WhichResult;
5681     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5682       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5683                          V1, V2).getValue(WhichResult);
5684     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5685       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5686                          V1, V2).getValue(WhichResult);
5687     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5688       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5689                          V1, V2).getValue(WhichResult);
5690
5691     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5692       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5693                          V1, V1).getValue(WhichResult);
5694     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5695       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5696                          V1, V1).getValue(WhichResult);
5697     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5698       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5699                          V1, V1).getValue(WhichResult);
5700   }
5701
5702   // If the shuffle is not directly supported and it has 4 elements, use
5703   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5704   unsigned NumElts = VT.getVectorNumElements();
5705   if (NumElts == 4) {
5706     unsigned PFIndexes[4];
5707     for (unsigned i = 0; i != 4; ++i) {
5708       if (ShuffleMask[i] < 0)
5709         PFIndexes[i] = 8;
5710       else
5711         PFIndexes[i] = ShuffleMask[i];
5712     }
5713
5714     // Compute the index in the perfect shuffle table.
5715     unsigned PFTableIndex =
5716       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5717     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5718     unsigned Cost = (PFEntry >> 30);
5719
5720     if (Cost <= 4)
5721       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5722   }
5723
5724   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5725   if (EltSize >= 32) {
5726     // Do the expansion with floating-point types, since that is what the VFP
5727     // registers are defined to use, and since i64 is not legal.
5728     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5729     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5730     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5731     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5732     SmallVector<SDValue, 8> Ops;
5733     for (unsigned i = 0; i < NumElts; ++i) {
5734       if (ShuffleMask[i] < 0)
5735         Ops.push_back(DAG.getUNDEF(EltVT));
5736       else
5737         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5738                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5739                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5740                                                   MVT::i32)));
5741     }
5742     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5743     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5744   }
5745
5746   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5747     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5748
5749   if (VT == MVT::v8i8) {
5750     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5751     if (NewOp.getNode())
5752       return NewOp;
5753   }
5754
5755   return SDValue();
5756 }
5757
5758 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5759   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5760   SDValue Lane = Op.getOperand(2);
5761   if (!isa<ConstantSDNode>(Lane))
5762     return SDValue();
5763
5764   return Op;
5765 }
5766
5767 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5768   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5769   SDValue Lane = Op.getOperand(1);
5770   if (!isa<ConstantSDNode>(Lane))
5771     return SDValue();
5772
5773   SDValue Vec = Op.getOperand(0);
5774   if (Op.getValueType() == MVT::i32 &&
5775       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5776     SDLoc dl(Op);
5777     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5778   }
5779
5780   return Op;
5781 }
5782
5783 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5784   // The only time a CONCAT_VECTORS operation can have legal types is when
5785   // two 64-bit vectors are concatenated to a 128-bit vector.
5786   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5787          "unexpected CONCAT_VECTORS");
5788   SDLoc dl(Op);
5789   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5790   SDValue Op0 = Op.getOperand(0);
5791   SDValue Op1 = Op.getOperand(1);
5792   if (Op0.getOpcode() != ISD::UNDEF)
5793     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5794                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5795                       DAG.getIntPtrConstant(0));
5796   if (Op1.getOpcode() != ISD::UNDEF)
5797     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5798                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5799                       DAG.getIntPtrConstant(1));
5800   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5801 }
5802
5803 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5804 /// element has been zero/sign-extended, depending on the isSigned parameter,
5805 /// from an integer type half its size.
5806 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5807                                    bool isSigned) {
5808   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5809   EVT VT = N->getValueType(0);
5810   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5811     SDNode *BVN = N->getOperand(0).getNode();
5812     if (BVN->getValueType(0) != MVT::v4i32 ||
5813         BVN->getOpcode() != ISD::BUILD_VECTOR)
5814       return false;
5815     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5816     unsigned HiElt = 1 - LoElt;
5817     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5818     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5819     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5820     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5821     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5822       return false;
5823     if (isSigned) {
5824       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5825           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5826         return true;
5827     } else {
5828       if (Hi0->isNullValue() && Hi1->isNullValue())
5829         return true;
5830     }
5831     return false;
5832   }
5833
5834   if (N->getOpcode() != ISD::BUILD_VECTOR)
5835     return false;
5836
5837   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5838     SDNode *Elt = N->getOperand(i).getNode();
5839     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5840       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5841       unsigned HalfSize = EltSize / 2;
5842       if (isSigned) {
5843         if (!isIntN(HalfSize, C->getSExtValue()))
5844           return false;
5845       } else {
5846         if (!isUIntN(HalfSize, C->getZExtValue()))
5847           return false;
5848       }
5849       continue;
5850     }
5851     return false;
5852   }
5853
5854   return true;
5855 }
5856
5857 /// isSignExtended - Check if a node is a vector value that is sign-extended
5858 /// or a constant BUILD_VECTOR with sign-extended elements.
5859 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5860   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5861     return true;
5862   if (isExtendedBUILD_VECTOR(N, DAG, true))
5863     return true;
5864   return false;
5865 }
5866
5867 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5868 /// or a constant BUILD_VECTOR with zero-extended elements.
5869 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5870   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5871     return true;
5872   if (isExtendedBUILD_VECTOR(N, DAG, false))
5873     return true;
5874   return false;
5875 }
5876
5877 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5878   if (OrigVT.getSizeInBits() >= 64)
5879     return OrigVT;
5880
5881   assert(OrigVT.isSimple() && "Expecting a simple value type");
5882
5883   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5884   switch (OrigSimpleTy) {
5885   default: llvm_unreachable("Unexpected Vector Type");
5886   case MVT::v2i8:
5887   case MVT::v2i16:
5888      return MVT::v2i32;
5889   case MVT::v4i8:
5890     return  MVT::v4i16;
5891   }
5892 }
5893
5894 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5895 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5896 /// We insert the required extension here to get the vector to fill a D register.
5897 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5898                                             const EVT &OrigTy,
5899                                             const EVT &ExtTy,
5900                                             unsigned ExtOpcode) {
5901   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5902   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5903   // 64-bits we need to insert a new extension so that it will be 64-bits.
5904   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5905   if (OrigTy.getSizeInBits() >= 64)
5906     return N;
5907
5908   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5909   EVT NewVT = getExtensionTo64Bits(OrigTy);
5910
5911   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5912 }
5913
5914 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5915 /// does not do any sign/zero extension. If the original vector is less
5916 /// than 64 bits, an appropriate extension will be added after the load to
5917 /// reach a total size of 64 bits. We have to add the extension separately
5918 /// because ARM does not have a sign/zero extending load for vectors.
5919 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5920   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5921
5922   // The load already has the right type.
5923   if (ExtendedTy == LD->getMemoryVT())
5924     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5925                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5926                 LD->isNonTemporal(), LD->isInvariant(),
5927                 LD->getAlignment());
5928
5929   // We need to create a zextload/sextload. We cannot just create a load
5930   // followed by a zext/zext node because LowerMUL is also run during normal
5931   // operation legalization where we can't create illegal types.
5932   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5933                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5934                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5935                         LD->isNonTemporal(), LD->getAlignment());
5936 }
5937
5938 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5939 /// extending load, or BUILD_VECTOR with extended elements, return the
5940 /// unextended value. The unextended vector should be 64 bits so that it can
5941 /// be used as an operand to a VMULL instruction. If the original vector size
5942 /// before extension is less than 64 bits we add a an extension to resize
5943 /// the vector to 64 bits.
5944 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5945   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5946     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5947                                         N->getOperand(0)->getValueType(0),
5948                                         N->getValueType(0),
5949                                         N->getOpcode());
5950
5951   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5952     return SkipLoadExtensionForVMULL(LD, DAG);
5953
5954   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5955   // have been legalized as a BITCAST from v4i32.
5956   if (N->getOpcode() == ISD::BITCAST) {
5957     SDNode *BVN = N->getOperand(0).getNode();
5958     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5959            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5960     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5961     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5962                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5963   }
5964   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5965   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5966   EVT VT = N->getValueType(0);
5967   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5968   unsigned NumElts = VT.getVectorNumElements();
5969   MVT TruncVT = MVT::getIntegerVT(EltSize);
5970   SmallVector<SDValue, 8> Ops;
5971   for (unsigned i = 0; i != NumElts; ++i) {
5972     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5973     const APInt &CInt = C->getAPIntValue();
5974     // Element types smaller than 32 bits are not legal, so use i32 elements.
5975     // The values are implicitly truncated so sext vs. zext doesn't matter.
5976     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5977   }
5978   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5979                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5980 }
5981
5982 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5983   unsigned Opcode = N->getOpcode();
5984   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5985     SDNode *N0 = N->getOperand(0).getNode();
5986     SDNode *N1 = N->getOperand(1).getNode();
5987     return N0->hasOneUse() && N1->hasOneUse() &&
5988       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5989   }
5990   return false;
5991 }
5992
5993 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5994   unsigned Opcode = N->getOpcode();
5995   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5996     SDNode *N0 = N->getOperand(0).getNode();
5997     SDNode *N1 = N->getOperand(1).getNode();
5998     return N0->hasOneUse() && N1->hasOneUse() &&
5999       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6000   }
6001   return false;
6002 }
6003
6004 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6005   // Multiplications are only custom-lowered for 128-bit vectors so that
6006   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6007   EVT VT = Op.getValueType();
6008   assert(VT.is128BitVector() && VT.isInteger() &&
6009          "unexpected type for custom-lowering ISD::MUL");
6010   SDNode *N0 = Op.getOperand(0).getNode();
6011   SDNode *N1 = Op.getOperand(1).getNode();
6012   unsigned NewOpc = 0;
6013   bool isMLA = false;
6014   bool isN0SExt = isSignExtended(N0, DAG);
6015   bool isN1SExt = isSignExtended(N1, DAG);
6016   if (isN0SExt && isN1SExt)
6017     NewOpc = ARMISD::VMULLs;
6018   else {
6019     bool isN0ZExt = isZeroExtended(N0, DAG);
6020     bool isN1ZExt = isZeroExtended(N1, DAG);
6021     if (isN0ZExt && isN1ZExt)
6022       NewOpc = ARMISD::VMULLu;
6023     else if (isN1SExt || isN1ZExt) {
6024       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6025       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6026       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6027         NewOpc = ARMISD::VMULLs;
6028         isMLA = true;
6029       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6030         NewOpc = ARMISD::VMULLu;
6031         isMLA = true;
6032       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6033         std::swap(N0, N1);
6034         NewOpc = ARMISD::VMULLu;
6035         isMLA = true;
6036       }
6037     }
6038
6039     if (!NewOpc) {
6040       if (VT == MVT::v2i64)
6041         // Fall through to expand this.  It is not legal.
6042         return SDValue();
6043       else
6044         // Other vector multiplications are legal.
6045         return Op;
6046     }
6047   }
6048
6049   // Legalize to a VMULL instruction.
6050   SDLoc DL(Op);
6051   SDValue Op0;
6052   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6053   if (!isMLA) {
6054     Op0 = SkipExtensionForVMULL(N0, DAG);
6055     assert(Op0.getValueType().is64BitVector() &&
6056            Op1.getValueType().is64BitVector() &&
6057            "unexpected types for extended operands to VMULL");
6058     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6059   }
6060
6061   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6062   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6063   //   vmull q0, d4, d6
6064   //   vmlal q0, d5, d6
6065   // is faster than
6066   //   vaddl q0, d4, d5
6067   //   vmovl q1, d6
6068   //   vmul  q0, q0, q1
6069   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6070   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6071   EVT Op1VT = Op1.getValueType();
6072   return DAG.getNode(N0->getOpcode(), DL, VT,
6073                      DAG.getNode(NewOpc, DL, VT,
6074                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6075                      DAG.getNode(NewOpc, DL, VT,
6076                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6077 }
6078
6079 static SDValue
6080 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6081   // Convert to float
6082   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6083   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6084   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6085   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6086   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6087   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6088   // Get reciprocal estimate.
6089   // float4 recip = vrecpeq_f32(yf);
6090   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6091                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
6092   // Because char has a smaller range than uchar, we can actually get away
6093   // without any newton steps.  This requires that we use a weird bias
6094   // of 0xb000, however (again, this has been exhaustively tested).
6095   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6096   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6097   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6098   Y = DAG.getConstant(0xb000, MVT::i32);
6099   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6100   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6101   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6102   // Convert back to short.
6103   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6104   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6105   return X;
6106 }
6107
6108 static SDValue
6109 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6110   SDValue N2;
6111   // Convert to float.
6112   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6113   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6114   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6115   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6116   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6117   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6118
6119   // Use reciprocal estimate and one refinement step.
6120   // float4 recip = vrecpeq_f32(yf);
6121   // recip *= vrecpsq_f32(yf, recip);
6122   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6123                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6124   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6125                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6126                    N1, N2);
6127   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6128   // Because short has a smaller range than ushort, we can actually get away
6129   // with only a single newton step.  This requires that we use a weird bias
6130   // of 89, however (again, this has been exhaustively tested).
6131   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6132   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6133   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6134   N1 = DAG.getConstant(0x89, MVT::i32);
6135   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6136   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6137   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6138   // Convert back to integer and return.
6139   // return vmovn_s32(vcvt_s32_f32(result));
6140   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6141   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6142   return N0;
6143 }
6144
6145 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6146   EVT VT = Op.getValueType();
6147   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6148          "unexpected type for custom-lowering ISD::SDIV");
6149
6150   SDLoc dl(Op);
6151   SDValue N0 = Op.getOperand(0);
6152   SDValue N1 = Op.getOperand(1);
6153   SDValue N2, N3;
6154
6155   if (VT == MVT::v8i8) {
6156     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6157     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6158
6159     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6160                      DAG.getIntPtrConstant(4));
6161     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6162                      DAG.getIntPtrConstant(4));
6163     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6164                      DAG.getIntPtrConstant(0));
6165     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6166                      DAG.getIntPtrConstant(0));
6167
6168     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6169     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6170
6171     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6172     N0 = LowerCONCAT_VECTORS(N0, DAG);
6173
6174     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6175     return N0;
6176   }
6177   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6178 }
6179
6180 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6181   EVT VT = Op.getValueType();
6182   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6183          "unexpected type for custom-lowering ISD::UDIV");
6184
6185   SDLoc dl(Op);
6186   SDValue N0 = Op.getOperand(0);
6187   SDValue N1 = Op.getOperand(1);
6188   SDValue N2, N3;
6189
6190   if (VT == MVT::v8i8) {
6191     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6192     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6193
6194     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6195                      DAG.getIntPtrConstant(4));
6196     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6197                      DAG.getIntPtrConstant(4));
6198     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6199                      DAG.getIntPtrConstant(0));
6200     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6201                      DAG.getIntPtrConstant(0));
6202
6203     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6204     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6205
6206     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6207     N0 = LowerCONCAT_VECTORS(N0, DAG);
6208
6209     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6210                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6211                      N0);
6212     return N0;
6213   }
6214
6215   // v4i16 sdiv ... Convert to float.
6216   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6217   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6218   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6219   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6220   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6221   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6222
6223   // Use reciprocal estimate and two refinement steps.
6224   // float4 recip = vrecpeq_f32(yf);
6225   // recip *= vrecpsq_f32(yf, recip);
6226   // recip *= vrecpsq_f32(yf, recip);
6227   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6228                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6229   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6230                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6231                    BN1, N2);
6232   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6233   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6234                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6235                    BN1, N2);
6236   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6237   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6238   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6239   // and that it will never cause us to return an answer too large).
6240   // float4 result = as_float4(as_int4(xf*recip) + 2);
6241   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6242   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6243   N1 = DAG.getConstant(2, MVT::i32);
6244   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6245   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6246   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6247   // Convert back to integer and return.
6248   // return vmovn_u32(vcvt_s32_f32(result));
6249   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6250   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6251   return N0;
6252 }
6253
6254 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6255   EVT VT = Op.getNode()->getValueType(0);
6256   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6257
6258   unsigned Opc;
6259   bool ExtraOp = false;
6260   switch (Op.getOpcode()) {
6261   default: llvm_unreachable("Invalid code");
6262   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6263   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6264   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6265   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6266   }
6267
6268   if (!ExtraOp)
6269     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6270                        Op.getOperand(1));
6271   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6272                      Op.getOperand(1), Op.getOperand(2));
6273 }
6274
6275 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6276   assert(Subtarget->isTargetDarwin());
6277
6278   // For iOS, we want to call an alternative entry point: __sincos_stret,
6279   // return values are passed via sret.
6280   SDLoc dl(Op);
6281   SDValue Arg = Op.getOperand(0);
6282   EVT ArgVT = Arg.getValueType();
6283   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6284
6285   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6286   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6287
6288   // Pair of floats / doubles used to pass the result.
6289   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6290
6291   // Create stack object for sret.
6292   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6293   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6294   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6295   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6296
6297   ArgListTy Args;
6298   ArgListEntry Entry;
6299
6300   Entry.Node = SRet;
6301   Entry.Ty = RetTy->getPointerTo();
6302   Entry.isSExt = false;
6303   Entry.isZExt = false;
6304   Entry.isSRet = true;
6305   Args.push_back(Entry);
6306
6307   Entry.Node = Arg;
6308   Entry.Ty = ArgTy;
6309   Entry.isSExt = false;
6310   Entry.isZExt = false;
6311   Args.push_back(Entry);
6312
6313   const char *LibcallName  = (ArgVT == MVT::f64)
6314   ? "__sincos_stret" : "__sincosf_stret";
6315   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6316
6317   TargetLowering::CallLoweringInfo CLI(DAG);
6318   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6319     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6320                std::move(Args), 0)
6321     .setDiscardResult();
6322
6323   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6324
6325   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6326                                 MachinePointerInfo(), false, false, false, 0);
6327
6328   // Address of cos field.
6329   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6330                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6331   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6332                                 MachinePointerInfo(), false, false, false, 0);
6333
6334   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6335   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6336                      LoadSin.getValue(0), LoadCos.getValue(0));
6337 }
6338
6339 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6340   // Monotonic load/store is legal for all targets
6341   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6342     return Op;
6343
6344   // Acquire/Release load/store is not legal for targets without a
6345   // dmb or equivalent available.
6346   return SDValue();
6347 }
6348
6349 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6350                                     SmallVectorImpl<SDValue> &Results,
6351                                     SelectionDAG &DAG,
6352                                     const ARMSubtarget *Subtarget) {
6353   SDLoc DL(N);
6354   SDValue Cycles32, OutChain;
6355
6356   if (Subtarget->hasPerfMon()) {
6357     // Under Power Management extensions, the cycle-count is:
6358     //    mrc p15, #0, <Rt>, c9, c13, #0
6359     SDValue Ops[] = { N->getOperand(0), // Chain
6360                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6361                       DAG.getConstant(15, MVT::i32),
6362                       DAG.getConstant(0, MVT::i32),
6363                       DAG.getConstant(9, MVT::i32),
6364                       DAG.getConstant(13, MVT::i32),
6365                       DAG.getConstant(0, MVT::i32)
6366     };
6367
6368     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6369                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6370     OutChain = Cycles32.getValue(1);
6371   } else {
6372     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6373     // there are older ARM CPUs that have implementation-specific ways of
6374     // obtaining this information (FIXME!).
6375     Cycles32 = DAG.getConstant(0, MVT::i32);
6376     OutChain = DAG.getEntryNode();
6377   }
6378
6379
6380   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6381                                  Cycles32, DAG.getConstant(0, MVT::i32));
6382   Results.push_back(Cycles64);
6383   Results.push_back(OutChain);
6384 }
6385
6386 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6387   switch (Op.getOpcode()) {
6388   default: llvm_unreachable("Don't know how to custom lower this!");
6389   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6390   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6391   case ISD::GlobalAddress:
6392     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6393     default: llvm_unreachable("unknown object format");
6394     case Triple::COFF:
6395       return LowerGlobalAddressWindows(Op, DAG);
6396     case Triple::ELF:
6397       return LowerGlobalAddressELF(Op, DAG);
6398     case Triple::MachO:
6399       return LowerGlobalAddressDarwin(Op, DAG);
6400     }
6401   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6402   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6403   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6404   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6405   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6406   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6407   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6408   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6409   case ISD::SINT_TO_FP:
6410   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6411   case ISD::FP_TO_SINT:
6412   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6413   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6414   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6415   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6416   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6417   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6418   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6419   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6420                                                                Subtarget);
6421   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6422   case ISD::SHL:
6423   case ISD::SRL:
6424   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6425   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6426   case ISD::SRL_PARTS:
6427   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6428   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6429   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6430   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6431   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6432   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6433   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6434   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6435   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6436   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6437   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6438   case ISD::MUL:           return LowerMUL(Op, DAG);
6439   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6440   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6441   case ISD::ADDC:
6442   case ISD::ADDE:
6443   case ISD::SUBC:
6444   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6445   case ISD::SADDO:
6446   case ISD::UADDO:
6447   case ISD::SSUBO:
6448   case ISD::USUBO:
6449     return LowerXALUO(Op, DAG);
6450   case ISD::ATOMIC_LOAD:
6451   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6452   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6453   case ISD::SDIVREM:
6454   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6455   case ISD::DYNAMIC_STACKALLOC:
6456     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6457       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6458     llvm_unreachable("Don't know how to custom lower this!");
6459   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6460   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6461   }
6462 }
6463
6464 /// ReplaceNodeResults - Replace the results of node with an illegal result
6465 /// type with new values built out of custom code.
6466 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6467                                            SmallVectorImpl<SDValue>&Results,
6468                                            SelectionDAG &DAG) const {
6469   SDValue Res;
6470   switch (N->getOpcode()) {
6471   default:
6472     llvm_unreachable("Don't know how to custom expand this!");
6473   case ISD::BITCAST:
6474     Res = ExpandBITCAST(N, DAG);
6475     break;
6476   case ISD::SRL:
6477   case ISD::SRA:
6478     Res = Expand64BitShift(N, DAG, Subtarget);
6479     break;
6480   case ISD::READCYCLECOUNTER:
6481     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6482     return;
6483   }
6484   if (Res.getNode())
6485     Results.push_back(Res);
6486 }
6487
6488 //===----------------------------------------------------------------------===//
6489 //                           ARM Scheduler Hooks
6490 //===----------------------------------------------------------------------===//
6491
6492 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6493 /// registers the function context.
6494 void ARMTargetLowering::
6495 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6496                        MachineBasicBlock *DispatchBB, int FI) const {
6497   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6498   DebugLoc dl = MI->getDebugLoc();
6499   MachineFunction *MF = MBB->getParent();
6500   MachineRegisterInfo *MRI = &MF->getRegInfo();
6501   MachineConstantPool *MCP = MF->getConstantPool();
6502   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6503   const Function *F = MF->getFunction();
6504
6505   bool isThumb = Subtarget->isThumb();
6506   bool isThumb2 = Subtarget->isThumb2();
6507
6508   unsigned PCLabelId = AFI->createPICLabelUId();
6509   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6510   ARMConstantPoolValue *CPV =
6511     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6512   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6513
6514   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6515                                            : &ARM::GPRRegClass;
6516
6517   // Grab constant pool and fixed stack memory operands.
6518   MachineMemOperand *CPMMO =
6519     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6520                              MachineMemOperand::MOLoad, 4, 4);
6521
6522   MachineMemOperand *FIMMOSt =
6523     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6524                              MachineMemOperand::MOStore, 4, 4);
6525
6526   // Load the address of the dispatch MBB into the jump buffer.
6527   if (isThumb2) {
6528     // Incoming value: jbuf
6529     //   ldr.n  r5, LCPI1_1
6530     //   orr    r5, r5, #1
6531     //   add    r5, pc
6532     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6533     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6534     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6535                    .addConstantPoolIndex(CPI)
6536                    .addMemOperand(CPMMO));
6537     // Set the low bit because of thumb mode.
6538     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6539     AddDefaultCC(
6540       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6541                      .addReg(NewVReg1, RegState::Kill)
6542                      .addImm(0x01)));
6543     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6544     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6545       .addReg(NewVReg2, RegState::Kill)
6546       .addImm(PCLabelId);
6547     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6548                    .addReg(NewVReg3, RegState::Kill)
6549                    .addFrameIndex(FI)
6550                    .addImm(36)  // &jbuf[1] :: pc
6551                    .addMemOperand(FIMMOSt));
6552   } else if (isThumb) {
6553     // Incoming value: jbuf
6554     //   ldr.n  r1, LCPI1_4
6555     //   add    r1, pc
6556     //   mov    r2, #1
6557     //   orrs   r1, r2
6558     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6559     //   str    r1, [r2]
6560     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6561     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6562                    .addConstantPoolIndex(CPI)
6563                    .addMemOperand(CPMMO));
6564     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6565     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6566       .addReg(NewVReg1, RegState::Kill)
6567       .addImm(PCLabelId);
6568     // Set the low bit because of thumb mode.
6569     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6570     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6571                    .addReg(ARM::CPSR, RegState::Define)
6572                    .addImm(1));
6573     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6574     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6575                    .addReg(ARM::CPSR, RegState::Define)
6576                    .addReg(NewVReg2, RegState::Kill)
6577                    .addReg(NewVReg3, RegState::Kill));
6578     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6579     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6580             .addFrameIndex(FI)
6581             .addImm(36); // &jbuf[1] :: pc
6582     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6583                    .addReg(NewVReg4, RegState::Kill)
6584                    .addReg(NewVReg5, RegState::Kill)
6585                    .addImm(0)
6586                    .addMemOperand(FIMMOSt));
6587   } else {
6588     // Incoming value: jbuf
6589     //   ldr  r1, LCPI1_1
6590     //   add  r1, pc, r1
6591     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6592     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6593     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6594                    .addConstantPoolIndex(CPI)
6595                    .addImm(0)
6596                    .addMemOperand(CPMMO));
6597     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6598     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6599                    .addReg(NewVReg1, RegState::Kill)
6600                    .addImm(PCLabelId));
6601     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6602                    .addReg(NewVReg2, RegState::Kill)
6603                    .addFrameIndex(FI)
6604                    .addImm(36)  // &jbuf[1] :: pc
6605                    .addMemOperand(FIMMOSt));
6606   }
6607 }
6608
6609 MachineBasicBlock *ARMTargetLowering::
6610 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6611   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6612   DebugLoc dl = MI->getDebugLoc();
6613   MachineFunction *MF = MBB->getParent();
6614   MachineRegisterInfo *MRI = &MF->getRegInfo();
6615   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6616   MachineFrameInfo *MFI = MF->getFrameInfo();
6617   int FI = MFI->getFunctionContextIndex();
6618
6619   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6620                                                         : &ARM::GPRnopcRegClass;
6621
6622   // Get a mapping of the call site numbers to all of the landing pads they're
6623   // associated with.
6624   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6625   unsigned MaxCSNum = 0;
6626   MachineModuleInfo &MMI = MF->getMMI();
6627   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6628        ++BB) {
6629     if (!BB->isLandingPad()) continue;
6630
6631     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6632     // pad.
6633     for (MachineBasicBlock::iterator
6634            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6635       if (!II->isEHLabel()) continue;
6636
6637       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6638       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6639
6640       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6641       for (SmallVectorImpl<unsigned>::iterator
6642              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6643            CSI != CSE; ++CSI) {
6644         CallSiteNumToLPad[*CSI].push_back(BB);
6645         MaxCSNum = std::max(MaxCSNum, *CSI);
6646       }
6647       break;
6648     }
6649   }
6650
6651   // Get an ordered list of the machine basic blocks for the jump table.
6652   std::vector<MachineBasicBlock*> LPadList;
6653   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6654   LPadList.reserve(CallSiteNumToLPad.size());
6655   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6656     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6657     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6658            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6659       LPadList.push_back(*II);
6660       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6661     }
6662   }
6663
6664   assert(!LPadList.empty() &&
6665          "No landing pad destinations for the dispatch jump table!");
6666
6667   // Create the jump table and associated information.
6668   MachineJumpTableInfo *JTI =
6669     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6670   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6671   unsigned UId = AFI->createJumpTableUId();
6672   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6673
6674   // Create the MBBs for the dispatch code.
6675
6676   // Shove the dispatch's address into the return slot in the function context.
6677   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6678   DispatchBB->setIsLandingPad();
6679
6680   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6681   unsigned trap_opcode;
6682   if (Subtarget->isThumb())
6683     trap_opcode = ARM::tTRAP;
6684   else
6685     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6686
6687   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6688   DispatchBB->addSuccessor(TrapBB);
6689
6690   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6691   DispatchBB->addSuccessor(DispContBB);
6692
6693   // Insert and MBBs.
6694   MF->insert(MF->end(), DispatchBB);
6695   MF->insert(MF->end(), DispContBB);
6696   MF->insert(MF->end(), TrapBB);
6697
6698   // Insert code into the entry block that creates and registers the function
6699   // context.
6700   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6701
6702   MachineMemOperand *FIMMOLd =
6703     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6704                              MachineMemOperand::MOLoad |
6705                              MachineMemOperand::MOVolatile, 4, 4);
6706
6707   MachineInstrBuilder MIB;
6708   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6709
6710   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6711   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6712
6713   // Add a register mask with no preserved registers.  This results in all
6714   // registers being marked as clobbered.
6715   MIB.addRegMask(RI.getNoPreservedMask());
6716
6717   unsigned NumLPads = LPadList.size();
6718   if (Subtarget->isThumb2()) {
6719     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6720     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6721                    .addFrameIndex(FI)
6722                    .addImm(4)
6723                    .addMemOperand(FIMMOLd));
6724
6725     if (NumLPads < 256) {
6726       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6727                      .addReg(NewVReg1)
6728                      .addImm(LPadList.size()));
6729     } else {
6730       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6731       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6732                      .addImm(NumLPads & 0xFFFF));
6733
6734       unsigned VReg2 = VReg1;
6735       if ((NumLPads & 0xFFFF0000) != 0) {
6736         VReg2 = MRI->createVirtualRegister(TRC);
6737         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6738                        .addReg(VReg1)
6739                        .addImm(NumLPads >> 16));
6740       }
6741
6742       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6743                      .addReg(NewVReg1)
6744                      .addReg(VReg2));
6745     }
6746
6747     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6748       .addMBB(TrapBB)
6749       .addImm(ARMCC::HI)
6750       .addReg(ARM::CPSR);
6751
6752     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6753     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6754                    .addJumpTableIndex(MJTI)
6755                    .addImm(UId));
6756
6757     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6758     AddDefaultCC(
6759       AddDefaultPred(
6760         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6761         .addReg(NewVReg3, RegState::Kill)
6762         .addReg(NewVReg1)
6763         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6764
6765     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6766       .addReg(NewVReg4, RegState::Kill)
6767       .addReg(NewVReg1)
6768       .addJumpTableIndex(MJTI)
6769       .addImm(UId);
6770   } else if (Subtarget->isThumb()) {
6771     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6772     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6773                    .addFrameIndex(FI)
6774                    .addImm(1)
6775                    .addMemOperand(FIMMOLd));
6776
6777     if (NumLPads < 256) {
6778       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6779                      .addReg(NewVReg1)
6780                      .addImm(NumLPads));
6781     } else {
6782       MachineConstantPool *ConstantPool = MF->getConstantPool();
6783       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6784       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6785
6786       // MachineConstantPool wants an explicit alignment.
6787       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6788       if (Align == 0)
6789         Align = getDataLayout()->getTypeAllocSize(C->getType());
6790       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6791
6792       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6793       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6794                      .addReg(VReg1, RegState::Define)
6795                      .addConstantPoolIndex(Idx));
6796       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6797                      .addReg(NewVReg1)
6798                      .addReg(VReg1));
6799     }
6800
6801     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6802       .addMBB(TrapBB)
6803       .addImm(ARMCC::HI)
6804       .addReg(ARM::CPSR);
6805
6806     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6807     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6808                    .addReg(ARM::CPSR, RegState::Define)
6809                    .addReg(NewVReg1)
6810                    .addImm(2));
6811
6812     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6813     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6814                    .addJumpTableIndex(MJTI)
6815                    .addImm(UId));
6816
6817     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6818     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6819                    .addReg(ARM::CPSR, RegState::Define)
6820                    .addReg(NewVReg2, RegState::Kill)
6821                    .addReg(NewVReg3));
6822
6823     MachineMemOperand *JTMMOLd =
6824       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6825                                MachineMemOperand::MOLoad, 4, 4);
6826
6827     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6828     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6829                    .addReg(NewVReg4, RegState::Kill)
6830                    .addImm(0)
6831                    .addMemOperand(JTMMOLd));
6832
6833     unsigned NewVReg6 = NewVReg5;
6834     if (RelocM == Reloc::PIC_) {
6835       NewVReg6 = MRI->createVirtualRegister(TRC);
6836       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6837                      .addReg(ARM::CPSR, RegState::Define)
6838                      .addReg(NewVReg5, RegState::Kill)
6839                      .addReg(NewVReg3));
6840     }
6841
6842     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6843       .addReg(NewVReg6, RegState::Kill)
6844       .addJumpTableIndex(MJTI)
6845       .addImm(UId);
6846   } else {
6847     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6848     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6849                    .addFrameIndex(FI)
6850                    .addImm(4)
6851                    .addMemOperand(FIMMOLd));
6852
6853     if (NumLPads < 256) {
6854       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6855                      .addReg(NewVReg1)
6856                      .addImm(NumLPads));
6857     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6858       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6859       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6860                      .addImm(NumLPads & 0xFFFF));
6861
6862       unsigned VReg2 = VReg1;
6863       if ((NumLPads & 0xFFFF0000) != 0) {
6864         VReg2 = MRI->createVirtualRegister(TRC);
6865         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6866                        .addReg(VReg1)
6867                        .addImm(NumLPads >> 16));
6868       }
6869
6870       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6871                      .addReg(NewVReg1)
6872                      .addReg(VReg2));
6873     } else {
6874       MachineConstantPool *ConstantPool = MF->getConstantPool();
6875       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6876       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6877
6878       // MachineConstantPool wants an explicit alignment.
6879       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6880       if (Align == 0)
6881         Align = getDataLayout()->getTypeAllocSize(C->getType());
6882       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6883
6884       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6885       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6886                      .addReg(VReg1, RegState::Define)
6887                      .addConstantPoolIndex(Idx)
6888                      .addImm(0));
6889       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6890                      .addReg(NewVReg1)
6891                      .addReg(VReg1, RegState::Kill));
6892     }
6893
6894     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6895       .addMBB(TrapBB)
6896       .addImm(ARMCC::HI)
6897       .addReg(ARM::CPSR);
6898
6899     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6900     AddDefaultCC(
6901       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6902                      .addReg(NewVReg1)
6903                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6904     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6905     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6906                    .addJumpTableIndex(MJTI)
6907                    .addImm(UId));
6908
6909     MachineMemOperand *JTMMOLd =
6910       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6911                                MachineMemOperand::MOLoad, 4, 4);
6912     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6913     AddDefaultPred(
6914       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6915       .addReg(NewVReg3, RegState::Kill)
6916       .addReg(NewVReg4)
6917       .addImm(0)
6918       .addMemOperand(JTMMOLd));
6919
6920     if (RelocM == Reloc::PIC_) {
6921       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6922         .addReg(NewVReg5, RegState::Kill)
6923         .addReg(NewVReg4)
6924         .addJumpTableIndex(MJTI)
6925         .addImm(UId);
6926     } else {
6927       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6928         .addReg(NewVReg5, RegState::Kill)
6929         .addJumpTableIndex(MJTI)
6930         .addImm(UId);
6931     }
6932   }
6933
6934   // Add the jump table entries as successors to the MBB.
6935   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6936   for (std::vector<MachineBasicBlock*>::iterator
6937          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6938     MachineBasicBlock *CurMBB = *I;
6939     if (SeenMBBs.insert(CurMBB).second)
6940       DispContBB->addSuccessor(CurMBB);
6941   }
6942
6943   // N.B. the order the invoke BBs are processed in doesn't matter here.
6944   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6945   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6946   for (MachineBasicBlock *BB : InvokeBBs) {
6947
6948     // Remove the landing pad successor from the invoke block and replace it
6949     // with the new dispatch block.
6950     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6951                                                   BB->succ_end());
6952     while (!Successors.empty()) {
6953       MachineBasicBlock *SMBB = Successors.pop_back_val();
6954       if (SMBB->isLandingPad()) {
6955         BB->removeSuccessor(SMBB);
6956         MBBLPads.push_back(SMBB);
6957       }
6958     }
6959
6960     BB->addSuccessor(DispatchBB);
6961
6962     // Find the invoke call and mark all of the callee-saved registers as
6963     // 'implicit defined' so that they're spilled. This prevents code from
6964     // moving instructions to before the EH block, where they will never be
6965     // executed.
6966     for (MachineBasicBlock::reverse_iterator
6967            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6968       if (!II->isCall()) continue;
6969
6970       DenseMap<unsigned, bool> DefRegs;
6971       for (MachineInstr::mop_iterator
6972              OI = II->operands_begin(), OE = II->operands_end();
6973            OI != OE; ++OI) {
6974         if (!OI->isReg()) continue;
6975         DefRegs[OI->getReg()] = true;
6976       }
6977
6978       MachineInstrBuilder MIB(*MF, &*II);
6979
6980       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6981         unsigned Reg = SavedRegs[i];
6982         if (Subtarget->isThumb2() &&
6983             !ARM::tGPRRegClass.contains(Reg) &&
6984             !ARM::hGPRRegClass.contains(Reg))
6985           continue;
6986         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6987           continue;
6988         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6989           continue;
6990         if (!DefRegs[Reg])
6991           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6992       }
6993
6994       break;
6995     }
6996   }
6997
6998   // Mark all former landing pads as non-landing pads. The dispatch is the only
6999   // landing pad now.
7000   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7001          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7002     (*I)->setIsLandingPad(false);
7003
7004   // The instruction is gone now.
7005   MI->eraseFromParent();
7006
7007   return MBB;
7008 }
7009
7010 static
7011 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7012   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7013        E = MBB->succ_end(); I != E; ++I)
7014     if (*I != Succ)
7015       return *I;
7016   llvm_unreachable("Expecting a BB with two successors!");
7017 }
7018
7019 /// Return the load opcode for a given load size. If load size >= 8,
7020 /// neon opcode will be returned.
7021 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7022   if (LdSize >= 8)
7023     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7024                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7025   if (IsThumb1)
7026     return LdSize == 4 ? ARM::tLDRi
7027                        : LdSize == 2 ? ARM::tLDRHi
7028                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7029   if (IsThumb2)
7030     return LdSize == 4 ? ARM::t2LDR_POST
7031                        : LdSize == 2 ? ARM::t2LDRH_POST
7032                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7033   return LdSize == 4 ? ARM::LDR_POST_IMM
7034                      : LdSize == 2 ? ARM::LDRH_POST
7035                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7036 }
7037
7038 /// Return the store opcode for a given store size. If store size >= 8,
7039 /// neon opcode will be returned.
7040 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7041   if (StSize >= 8)
7042     return StSize == 16 ? ARM::VST1q32wb_fixed
7043                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7044   if (IsThumb1)
7045     return StSize == 4 ? ARM::tSTRi
7046                        : StSize == 2 ? ARM::tSTRHi
7047                                      : StSize == 1 ? ARM::tSTRBi : 0;
7048   if (IsThumb2)
7049     return StSize == 4 ? ARM::t2STR_POST
7050                        : StSize == 2 ? ARM::t2STRH_POST
7051                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7052   return StSize == 4 ? ARM::STR_POST_IMM
7053                      : StSize == 2 ? ARM::STRH_POST
7054                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7055 }
7056
7057 /// Emit a post-increment load operation with given size. The instructions
7058 /// will be added to BB at Pos.
7059 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7060                        const TargetInstrInfo *TII, DebugLoc dl,
7061                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7062                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7063   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7064   assert(LdOpc != 0 && "Should have a load opcode");
7065   if (LdSize >= 8) {
7066     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7067                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7068                        .addImm(0));
7069   } else if (IsThumb1) {
7070     // load + update AddrIn
7071     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7072                        .addReg(AddrIn).addImm(0));
7073     MachineInstrBuilder MIB =
7074         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7075     MIB = AddDefaultT1CC(MIB);
7076     MIB.addReg(AddrIn).addImm(LdSize);
7077     AddDefaultPred(MIB);
7078   } else if (IsThumb2) {
7079     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7080                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7081                        .addImm(LdSize));
7082   } else { // arm
7083     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7084                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7085                        .addReg(0).addImm(LdSize));
7086   }
7087 }
7088
7089 /// Emit a post-increment store operation with given size. The instructions
7090 /// will be added to BB at Pos.
7091 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7092                        const TargetInstrInfo *TII, DebugLoc dl,
7093                        unsigned StSize, unsigned Data, unsigned AddrIn,
7094                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7095   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7096   assert(StOpc != 0 && "Should have a store opcode");
7097   if (StSize >= 8) {
7098     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7099                        .addReg(AddrIn).addImm(0).addReg(Data));
7100   } else if (IsThumb1) {
7101     // store + update AddrIn
7102     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7103                        .addReg(AddrIn).addImm(0));
7104     MachineInstrBuilder MIB =
7105         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7106     MIB = AddDefaultT1CC(MIB);
7107     MIB.addReg(AddrIn).addImm(StSize);
7108     AddDefaultPred(MIB);
7109   } else if (IsThumb2) {
7110     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7111                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7112   } else { // arm
7113     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7114                        .addReg(Data).addReg(AddrIn).addReg(0)
7115                        .addImm(StSize));
7116   }
7117 }
7118
7119 MachineBasicBlock *
7120 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7121                                    MachineBasicBlock *BB) const {
7122   // This pseudo instruction has 3 operands: dst, src, size
7123   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7124   // Otherwise, we will generate unrolled scalar copies.
7125   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7126   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7127   MachineFunction::iterator It = BB;
7128   ++It;
7129
7130   unsigned dest = MI->getOperand(0).getReg();
7131   unsigned src = MI->getOperand(1).getReg();
7132   unsigned SizeVal = MI->getOperand(2).getImm();
7133   unsigned Align = MI->getOperand(3).getImm();
7134   DebugLoc dl = MI->getDebugLoc();
7135
7136   MachineFunction *MF = BB->getParent();
7137   MachineRegisterInfo &MRI = MF->getRegInfo();
7138   unsigned UnitSize = 0;
7139   const TargetRegisterClass *TRC = nullptr;
7140   const TargetRegisterClass *VecTRC = nullptr;
7141
7142   bool IsThumb1 = Subtarget->isThumb1Only();
7143   bool IsThumb2 = Subtarget->isThumb2();
7144
7145   if (Align & 1) {
7146     UnitSize = 1;
7147   } else if (Align & 2) {
7148     UnitSize = 2;
7149   } else {
7150     // Check whether we can use NEON instructions.
7151     if (!MF->getFunction()->getAttributes().
7152           hasAttribute(AttributeSet::FunctionIndex,
7153                        Attribute::NoImplicitFloat) &&
7154         Subtarget->hasNEON()) {
7155       if ((Align % 16 == 0) && SizeVal >= 16)
7156         UnitSize = 16;
7157       else if ((Align % 8 == 0) && SizeVal >= 8)
7158         UnitSize = 8;
7159     }
7160     // Can't use NEON instructions.
7161     if (UnitSize == 0)
7162       UnitSize = 4;
7163   }
7164
7165   // Select the correct opcode and register class for unit size load/store
7166   bool IsNeon = UnitSize >= 8;
7167   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7168   if (IsNeon)
7169     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7170                             : UnitSize == 8 ? &ARM::DPRRegClass
7171                                             : nullptr;
7172
7173   unsigned BytesLeft = SizeVal % UnitSize;
7174   unsigned LoopSize = SizeVal - BytesLeft;
7175
7176   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7177     // Use LDR and STR to copy.
7178     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7179     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7180     unsigned srcIn = src;
7181     unsigned destIn = dest;
7182     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7183       unsigned srcOut = MRI.createVirtualRegister(TRC);
7184       unsigned destOut = MRI.createVirtualRegister(TRC);
7185       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7186       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7187                  IsThumb1, IsThumb2);
7188       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7189                  IsThumb1, IsThumb2);
7190       srcIn = srcOut;
7191       destIn = destOut;
7192     }
7193
7194     // Handle the leftover bytes with LDRB and STRB.
7195     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7196     // [destOut] = STRB_POST(scratch, destIn, 1)
7197     for (unsigned i = 0; i < BytesLeft; i++) {
7198       unsigned srcOut = MRI.createVirtualRegister(TRC);
7199       unsigned destOut = MRI.createVirtualRegister(TRC);
7200       unsigned scratch = MRI.createVirtualRegister(TRC);
7201       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7202                  IsThumb1, IsThumb2);
7203       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7204                  IsThumb1, IsThumb2);
7205       srcIn = srcOut;
7206       destIn = destOut;
7207     }
7208     MI->eraseFromParent();   // The instruction is gone now.
7209     return BB;
7210   }
7211
7212   // Expand the pseudo op to a loop.
7213   // thisMBB:
7214   //   ...
7215   //   movw varEnd, # --> with thumb2
7216   //   movt varEnd, #
7217   //   ldrcp varEnd, idx --> without thumb2
7218   //   fallthrough --> loopMBB
7219   // loopMBB:
7220   //   PHI varPhi, varEnd, varLoop
7221   //   PHI srcPhi, src, srcLoop
7222   //   PHI destPhi, dst, destLoop
7223   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7224   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7225   //   subs varLoop, varPhi, #UnitSize
7226   //   bne loopMBB
7227   //   fallthrough --> exitMBB
7228   // exitMBB:
7229   //   epilogue to handle left-over bytes
7230   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7231   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7232   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7233   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7234   MF->insert(It, loopMBB);
7235   MF->insert(It, exitMBB);
7236
7237   // Transfer the remainder of BB and its successor edges to exitMBB.
7238   exitMBB->splice(exitMBB->begin(), BB,
7239                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7240   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7241
7242   // Load an immediate to varEnd.
7243   unsigned varEnd = MRI.createVirtualRegister(TRC);
7244   if (IsThumb2) {
7245     unsigned Vtmp = varEnd;
7246     if ((LoopSize & 0xFFFF0000) != 0)
7247       Vtmp = MRI.createVirtualRegister(TRC);
7248     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7249                        .addImm(LoopSize & 0xFFFF));
7250
7251     if ((LoopSize & 0xFFFF0000) != 0)
7252       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7253                          .addReg(Vtmp).addImm(LoopSize >> 16));
7254   } else {
7255     MachineConstantPool *ConstantPool = MF->getConstantPool();
7256     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7257     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7258
7259     // MachineConstantPool wants an explicit alignment.
7260     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7261     if (Align == 0)
7262       Align = getDataLayout()->getTypeAllocSize(C->getType());
7263     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7264
7265     if (IsThumb1)
7266       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7267           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7268     else
7269       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7270           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7271   }
7272   BB->addSuccessor(loopMBB);
7273
7274   // Generate the loop body:
7275   //   varPhi = PHI(varLoop, varEnd)
7276   //   srcPhi = PHI(srcLoop, src)
7277   //   destPhi = PHI(destLoop, dst)
7278   MachineBasicBlock *entryBB = BB;
7279   BB = loopMBB;
7280   unsigned varLoop = MRI.createVirtualRegister(TRC);
7281   unsigned varPhi = MRI.createVirtualRegister(TRC);
7282   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7283   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7284   unsigned destLoop = MRI.createVirtualRegister(TRC);
7285   unsigned destPhi = MRI.createVirtualRegister(TRC);
7286
7287   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7288     .addReg(varLoop).addMBB(loopMBB)
7289     .addReg(varEnd).addMBB(entryBB);
7290   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7291     .addReg(srcLoop).addMBB(loopMBB)
7292     .addReg(src).addMBB(entryBB);
7293   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7294     .addReg(destLoop).addMBB(loopMBB)
7295     .addReg(dest).addMBB(entryBB);
7296
7297   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7298   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7299   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7300   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7301              IsThumb1, IsThumb2);
7302   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7303              IsThumb1, IsThumb2);
7304
7305   // Decrement loop variable by UnitSize.
7306   if (IsThumb1) {
7307     MachineInstrBuilder MIB =
7308         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7309     MIB = AddDefaultT1CC(MIB);
7310     MIB.addReg(varPhi).addImm(UnitSize);
7311     AddDefaultPred(MIB);
7312   } else {
7313     MachineInstrBuilder MIB =
7314         BuildMI(*BB, BB->end(), dl,
7315                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7316     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7317     MIB->getOperand(5).setReg(ARM::CPSR);
7318     MIB->getOperand(5).setIsDef(true);
7319   }
7320   BuildMI(*BB, BB->end(), dl,
7321           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7322       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7323
7324   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7325   BB->addSuccessor(loopMBB);
7326   BB->addSuccessor(exitMBB);
7327
7328   // Add epilogue to handle BytesLeft.
7329   BB = exitMBB;
7330   MachineInstr *StartOfExit = exitMBB->begin();
7331
7332   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7333   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7334   unsigned srcIn = srcLoop;
7335   unsigned destIn = destLoop;
7336   for (unsigned i = 0; i < BytesLeft; i++) {
7337     unsigned srcOut = MRI.createVirtualRegister(TRC);
7338     unsigned destOut = MRI.createVirtualRegister(TRC);
7339     unsigned scratch = MRI.createVirtualRegister(TRC);
7340     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7341                IsThumb1, IsThumb2);
7342     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7343                IsThumb1, IsThumb2);
7344     srcIn = srcOut;
7345     destIn = destOut;
7346   }
7347
7348   MI->eraseFromParent();   // The instruction is gone now.
7349   return BB;
7350 }
7351
7352 MachineBasicBlock *
7353 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7354                                        MachineBasicBlock *MBB) const {
7355   const TargetMachine &TM = getTargetMachine();
7356   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7357   DebugLoc DL = MI->getDebugLoc();
7358
7359   assert(Subtarget->isTargetWindows() &&
7360          "__chkstk is only supported on Windows");
7361   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7362
7363   // __chkstk takes the number of words to allocate on the stack in R4, and
7364   // returns the stack adjustment in number of bytes in R4.  This will not
7365   // clober any other registers (other than the obvious lr).
7366   //
7367   // Although, technically, IP should be considered a register which may be
7368   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7369   // thumb-2 environment, so there is no interworking required.  As a result, we
7370   // do not expect a veneer to be emitted by the linker, clobbering IP.
7371   //
7372   // Each module receives its own copy of __chkstk, so no import thunk is
7373   // required, again, ensuring that IP is not clobbered.
7374   //
7375   // Finally, although some linkers may theoretically provide a trampoline for
7376   // out of range calls (which is quite common due to a 32M range limitation of
7377   // branches for Thumb), we can generate the long-call version via
7378   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7379   // IP.
7380
7381   switch (TM.getCodeModel()) {
7382   case CodeModel::Small:
7383   case CodeModel::Medium:
7384   case CodeModel::Default:
7385   case CodeModel::Kernel:
7386     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7387       .addImm((unsigned)ARMCC::AL).addReg(0)
7388       .addExternalSymbol("__chkstk")
7389       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7390       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7391       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7392     break;
7393   case CodeModel::Large:
7394   case CodeModel::JITDefault: {
7395     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7396     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7397
7398     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7399       .addExternalSymbol("__chkstk");
7400     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7401       .addImm((unsigned)ARMCC::AL).addReg(0)
7402       .addReg(Reg, RegState::Kill)
7403       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7404       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7405       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7406     break;
7407   }
7408   }
7409
7410   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7411                                       ARM::SP)
7412                               .addReg(ARM::SP).addReg(ARM::R4)));
7413
7414   MI->eraseFromParent();
7415   return MBB;
7416 }
7417
7418 MachineBasicBlock *
7419 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7420                                                MachineBasicBlock *BB) const {
7421   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7422   DebugLoc dl = MI->getDebugLoc();
7423   bool isThumb2 = Subtarget->isThumb2();
7424   switch (MI->getOpcode()) {
7425   default: {
7426     MI->dump();
7427     llvm_unreachable("Unexpected instr type to insert");
7428   }
7429   // The Thumb2 pre-indexed stores have the same MI operands, they just
7430   // define them differently in the .td files from the isel patterns, so
7431   // they need pseudos.
7432   case ARM::t2STR_preidx:
7433     MI->setDesc(TII->get(ARM::t2STR_PRE));
7434     return BB;
7435   case ARM::t2STRB_preidx:
7436     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7437     return BB;
7438   case ARM::t2STRH_preidx:
7439     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7440     return BB;
7441
7442   case ARM::STRi_preidx:
7443   case ARM::STRBi_preidx: {
7444     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7445       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7446     // Decode the offset.
7447     unsigned Offset = MI->getOperand(4).getImm();
7448     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7449     Offset = ARM_AM::getAM2Offset(Offset);
7450     if (isSub)
7451       Offset = -Offset;
7452
7453     MachineMemOperand *MMO = *MI->memoperands_begin();
7454     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7455       .addOperand(MI->getOperand(0))  // Rn_wb
7456       .addOperand(MI->getOperand(1))  // Rt
7457       .addOperand(MI->getOperand(2))  // Rn
7458       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7459       .addOperand(MI->getOperand(5))  // pred
7460       .addOperand(MI->getOperand(6))
7461       .addMemOperand(MMO);
7462     MI->eraseFromParent();
7463     return BB;
7464   }
7465   case ARM::STRr_preidx:
7466   case ARM::STRBr_preidx:
7467   case ARM::STRH_preidx: {
7468     unsigned NewOpc;
7469     switch (MI->getOpcode()) {
7470     default: llvm_unreachable("unexpected opcode!");
7471     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7472     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7473     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7474     }
7475     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7476     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7477       MIB.addOperand(MI->getOperand(i));
7478     MI->eraseFromParent();
7479     return BB;
7480   }
7481
7482   case ARM::tMOVCCr_pseudo: {
7483     // To "insert" a SELECT_CC instruction, we actually have to insert the
7484     // diamond control-flow pattern.  The incoming instruction knows the
7485     // destination vreg to set, the condition code register to branch on, the
7486     // true/false values to select between, and a branch opcode to use.
7487     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7488     MachineFunction::iterator It = BB;
7489     ++It;
7490
7491     //  thisMBB:
7492     //  ...
7493     //   TrueVal = ...
7494     //   cmpTY ccX, r1, r2
7495     //   bCC copy1MBB
7496     //   fallthrough --> copy0MBB
7497     MachineBasicBlock *thisMBB  = BB;
7498     MachineFunction *F = BB->getParent();
7499     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7500     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7501     F->insert(It, copy0MBB);
7502     F->insert(It, sinkMBB);
7503
7504     // Transfer the remainder of BB and its successor edges to sinkMBB.
7505     sinkMBB->splice(sinkMBB->begin(), BB,
7506                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7507     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7508
7509     BB->addSuccessor(copy0MBB);
7510     BB->addSuccessor(sinkMBB);
7511
7512     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7513       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7514
7515     //  copy0MBB:
7516     //   %FalseValue = ...
7517     //   # fallthrough to sinkMBB
7518     BB = copy0MBB;
7519
7520     // Update machine-CFG edges
7521     BB->addSuccessor(sinkMBB);
7522
7523     //  sinkMBB:
7524     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7525     //  ...
7526     BB = sinkMBB;
7527     BuildMI(*BB, BB->begin(), dl,
7528             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7529       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7530       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7531
7532     MI->eraseFromParent();   // The pseudo instruction is gone now.
7533     return BB;
7534   }
7535
7536   case ARM::BCCi64:
7537   case ARM::BCCZi64: {
7538     // If there is an unconditional branch to the other successor, remove it.
7539     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7540
7541     // Compare both parts that make up the double comparison separately for
7542     // equality.
7543     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7544
7545     unsigned LHS1 = MI->getOperand(1).getReg();
7546     unsigned LHS2 = MI->getOperand(2).getReg();
7547     if (RHSisZero) {
7548       AddDefaultPred(BuildMI(BB, dl,
7549                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7550                      .addReg(LHS1).addImm(0));
7551       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7552         .addReg(LHS2).addImm(0)
7553         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7554     } else {
7555       unsigned RHS1 = MI->getOperand(3).getReg();
7556       unsigned RHS2 = MI->getOperand(4).getReg();
7557       AddDefaultPred(BuildMI(BB, dl,
7558                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7559                      .addReg(LHS1).addReg(RHS1));
7560       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7561         .addReg(LHS2).addReg(RHS2)
7562         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7563     }
7564
7565     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7566     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7567     if (MI->getOperand(0).getImm() == ARMCC::NE)
7568       std::swap(destMBB, exitMBB);
7569
7570     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7571       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7572     if (isThumb2)
7573       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7574     else
7575       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7576
7577     MI->eraseFromParent();   // The pseudo instruction is gone now.
7578     return BB;
7579   }
7580
7581   case ARM::Int_eh_sjlj_setjmp:
7582   case ARM::Int_eh_sjlj_setjmp_nofp:
7583   case ARM::tInt_eh_sjlj_setjmp:
7584   case ARM::t2Int_eh_sjlj_setjmp:
7585   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7586     EmitSjLjDispatchBlock(MI, BB);
7587     return BB;
7588
7589   case ARM::ABS:
7590   case ARM::t2ABS: {
7591     // To insert an ABS instruction, we have to insert the
7592     // diamond control-flow pattern.  The incoming instruction knows the
7593     // source vreg to test against 0, the destination vreg to set,
7594     // the condition code register to branch on, the
7595     // true/false values to select between, and a branch opcode to use.
7596     // It transforms
7597     //     V1 = ABS V0
7598     // into
7599     //     V2 = MOVS V0
7600     //     BCC                      (branch to SinkBB if V0 >= 0)
7601     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7602     //     SinkBB: V1 = PHI(V2, V3)
7603     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7604     MachineFunction::iterator BBI = BB;
7605     ++BBI;
7606     MachineFunction *Fn = BB->getParent();
7607     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7608     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7609     Fn->insert(BBI, RSBBB);
7610     Fn->insert(BBI, SinkBB);
7611
7612     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7613     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7614     bool isThumb2 = Subtarget->isThumb2();
7615     MachineRegisterInfo &MRI = Fn->getRegInfo();
7616     // In Thumb mode S must not be specified if source register is the SP or
7617     // PC and if destination register is the SP, so restrict register class
7618     unsigned NewRsbDstReg =
7619       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7620
7621     // Transfer the remainder of BB and its successor edges to sinkMBB.
7622     SinkBB->splice(SinkBB->begin(), BB,
7623                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7624     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7625
7626     BB->addSuccessor(RSBBB);
7627     BB->addSuccessor(SinkBB);
7628
7629     // fall through to SinkMBB
7630     RSBBB->addSuccessor(SinkBB);
7631
7632     // insert a cmp at the end of BB
7633     AddDefaultPred(BuildMI(BB, dl,
7634                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7635                    .addReg(ABSSrcReg).addImm(0));
7636
7637     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7638     BuildMI(BB, dl,
7639       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7640       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7641
7642     // insert rsbri in RSBBB
7643     // Note: BCC and rsbri will be converted into predicated rsbmi
7644     // by if-conversion pass
7645     BuildMI(*RSBBB, RSBBB->begin(), dl,
7646       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7647       .addReg(ABSSrcReg, RegState::Kill)
7648       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7649
7650     // insert PHI in SinkBB,
7651     // reuse ABSDstReg to not change uses of ABS instruction
7652     BuildMI(*SinkBB, SinkBB->begin(), dl,
7653       TII->get(ARM::PHI), ABSDstReg)
7654       .addReg(NewRsbDstReg).addMBB(RSBBB)
7655       .addReg(ABSSrcReg).addMBB(BB);
7656
7657     // remove ABS instruction
7658     MI->eraseFromParent();
7659
7660     // return last added BB
7661     return SinkBB;
7662   }
7663   case ARM::COPY_STRUCT_BYVAL_I32:
7664     ++NumLoopByVals;
7665     return EmitStructByval(MI, BB);
7666   case ARM::WIN__CHKSTK:
7667     return EmitLowered__chkstk(MI, BB);
7668   }
7669 }
7670
7671 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7672                                                       SDNode *Node) const {
7673   const MCInstrDesc *MCID = &MI->getDesc();
7674   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7675   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7676   // operand is still set to noreg. If needed, set the optional operand's
7677   // register to CPSR, and remove the redundant implicit def.
7678   //
7679   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7680
7681   // Rename pseudo opcodes.
7682   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7683   if (NewOpc) {
7684     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7685     MCID = &TII->get(NewOpc);
7686
7687     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7688            "converted opcode should be the same except for cc_out");
7689
7690     MI->setDesc(*MCID);
7691
7692     // Add the optional cc_out operand
7693     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7694   }
7695   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7696
7697   // Any ARM instruction that sets the 's' bit should specify an optional
7698   // "cc_out" operand in the last operand position.
7699   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7700     assert(!NewOpc && "Optional cc_out operand required");
7701     return;
7702   }
7703   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7704   // since we already have an optional CPSR def.
7705   bool definesCPSR = false;
7706   bool deadCPSR = false;
7707   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7708        i != e; ++i) {
7709     const MachineOperand &MO = MI->getOperand(i);
7710     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7711       definesCPSR = true;
7712       if (MO.isDead())
7713         deadCPSR = true;
7714       MI->RemoveOperand(i);
7715       break;
7716     }
7717   }
7718   if (!definesCPSR) {
7719     assert(!NewOpc && "Optional cc_out operand required");
7720     return;
7721   }
7722   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7723   if (deadCPSR) {
7724     assert(!MI->getOperand(ccOutIdx).getReg() &&
7725            "expect uninitialized optional cc_out operand");
7726     return;
7727   }
7728
7729   // If this instruction was defined with an optional CPSR def and its dag node
7730   // had a live implicit CPSR def, then activate the optional CPSR def.
7731   MachineOperand &MO = MI->getOperand(ccOutIdx);
7732   MO.setReg(ARM::CPSR);
7733   MO.setIsDef(true);
7734 }
7735
7736 //===----------------------------------------------------------------------===//
7737 //                           ARM Optimization Hooks
7738 //===----------------------------------------------------------------------===//
7739
7740 // Helper function that checks if N is a null or all ones constant.
7741 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7742   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7743   if (!C)
7744     return false;
7745   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7746 }
7747
7748 // Return true if N is conditionally 0 or all ones.
7749 // Detects these expressions where cc is an i1 value:
7750 //
7751 //   (select cc 0, y)   [AllOnes=0]
7752 //   (select cc y, 0)   [AllOnes=0]
7753 //   (zext cc)          [AllOnes=0]
7754 //   (sext cc)          [AllOnes=0/1]
7755 //   (select cc -1, y)  [AllOnes=1]
7756 //   (select cc y, -1)  [AllOnes=1]
7757 //
7758 // Invert is set when N is the null/all ones constant when CC is false.
7759 // OtherOp is set to the alternative value of N.
7760 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7761                                        SDValue &CC, bool &Invert,
7762                                        SDValue &OtherOp,
7763                                        SelectionDAG &DAG) {
7764   switch (N->getOpcode()) {
7765   default: return false;
7766   case ISD::SELECT: {
7767     CC = N->getOperand(0);
7768     SDValue N1 = N->getOperand(1);
7769     SDValue N2 = N->getOperand(2);
7770     if (isZeroOrAllOnes(N1, AllOnes)) {
7771       Invert = false;
7772       OtherOp = N2;
7773       return true;
7774     }
7775     if (isZeroOrAllOnes(N2, AllOnes)) {
7776       Invert = true;
7777       OtherOp = N1;
7778       return true;
7779     }
7780     return false;
7781   }
7782   case ISD::ZERO_EXTEND:
7783     // (zext cc) can never be the all ones value.
7784     if (AllOnes)
7785       return false;
7786     // Fall through.
7787   case ISD::SIGN_EXTEND: {
7788     EVT VT = N->getValueType(0);
7789     CC = N->getOperand(0);
7790     if (CC.getValueType() != MVT::i1)
7791       return false;
7792     Invert = !AllOnes;
7793     if (AllOnes)
7794       // When looking for an AllOnes constant, N is an sext, and the 'other'
7795       // value is 0.
7796       OtherOp = DAG.getConstant(0, VT);
7797     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7798       // When looking for a 0 constant, N can be zext or sext.
7799       OtherOp = DAG.getConstant(1, VT);
7800     else
7801       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7802     return true;
7803   }
7804   }
7805 }
7806
7807 // Combine a constant select operand into its use:
7808 //
7809 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7810 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7811 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7812 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7813 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7814 //
7815 // The transform is rejected if the select doesn't have a constant operand that
7816 // is null, or all ones when AllOnes is set.
7817 //
7818 // Also recognize sext/zext from i1:
7819 //
7820 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7821 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7822 //
7823 // These transformations eventually create predicated instructions.
7824 //
7825 // @param N       The node to transform.
7826 // @param Slct    The N operand that is a select.
7827 // @param OtherOp The other N operand (x above).
7828 // @param DCI     Context.
7829 // @param AllOnes Require the select constant to be all ones instead of null.
7830 // @returns The new node, or SDValue() on failure.
7831 static
7832 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7833                             TargetLowering::DAGCombinerInfo &DCI,
7834                             bool AllOnes = false) {
7835   SelectionDAG &DAG = DCI.DAG;
7836   EVT VT = N->getValueType(0);
7837   SDValue NonConstantVal;
7838   SDValue CCOp;
7839   bool SwapSelectOps;
7840   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7841                                   NonConstantVal, DAG))
7842     return SDValue();
7843
7844   // Slct is now know to be the desired identity constant when CC is true.
7845   SDValue TrueVal = OtherOp;
7846   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7847                                  OtherOp, NonConstantVal);
7848   // Unless SwapSelectOps says CC should be false.
7849   if (SwapSelectOps)
7850     std::swap(TrueVal, FalseVal);
7851
7852   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7853                      CCOp, TrueVal, FalseVal);
7854 }
7855
7856 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7857 static
7858 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7859                                        TargetLowering::DAGCombinerInfo &DCI) {
7860   SDValue N0 = N->getOperand(0);
7861   SDValue N1 = N->getOperand(1);
7862   if (N0.getNode()->hasOneUse()) {
7863     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7864     if (Result.getNode())
7865       return Result;
7866   }
7867   if (N1.getNode()->hasOneUse()) {
7868     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7869     if (Result.getNode())
7870       return Result;
7871   }
7872   return SDValue();
7873 }
7874
7875 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7876 // (only after legalization).
7877 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7878                                  TargetLowering::DAGCombinerInfo &DCI,
7879                                  const ARMSubtarget *Subtarget) {
7880
7881   // Only perform optimization if after legalize, and if NEON is available. We
7882   // also expected both operands to be BUILD_VECTORs.
7883   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7884       || N0.getOpcode() != ISD::BUILD_VECTOR
7885       || N1.getOpcode() != ISD::BUILD_VECTOR)
7886     return SDValue();
7887
7888   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7889   EVT VT = N->getValueType(0);
7890   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7891     return SDValue();
7892
7893   // Check that the vector operands are of the right form.
7894   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7895   // operands, where N is the size of the formed vector.
7896   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7897   // index such that we have a pair wise add pattern.
7898
7899   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7900   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7901     return SDValue();
7902   SDValue Vec = N0->getOperand(0)->getOperand(0);
7903   SDNode *V = Vec.getNode();
7904   unsigned nextIndex = 0;
7905
7906   // For each operands to the ADD which are BUILD_VECTORs,
7907   // check to see if each of their operands are an EXTRACT_VECTOR with
7908   // the same vector and appropriate index.
7909   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7910     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7911         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7912
7913       SDValue ExtVec0 = N0->getOperand(i);
7914       SDValue ExtVec1 = N1->getOperand(i);
7915
7916       // First operand is the vector, verify its the same.
7917       if (V != ExtVec0->getOperand(0).getNode() ||
7918           V != ExtVec1->getOperand(0).getNode())
7919         return SDValue();
7920
7921       // Second is the constant, verify its correct.
7922       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7923       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7924
7925       // For the constant, we want to see all the even or all the odd.
7926       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7927           || C1->getZExtValue() != nextIndex+1)
7928         return SDValue();
7929
7930       // Increment index.
7931       nextIndex+=2;
7932     } else
7933       return SDValue();
7934   }
7935
7936   // Create VPADDL node.
7937   SelectionDAG &DAG = DCI.DAG;
7938   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7939
7940   // Build operand list.
7941   SmallVector<SDValue, 8> Ops;
7942   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7943                                 TLI.getPointerTy()));
7944
7945   // Input is the vector.
7946   Ops.push_back(Vec);
7947
7948   // Get widened type and narrowed type.
7949   MVT widenType;
7950   unsigned numElem = VT.getVectorNumElements();
7951   
7952   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7953   switch (inputLaneType.getSimpleVT().SimpleTy) {
7954     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7955     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7956     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7957     default:
7958       llvm_unreachable("Invalid vector element type for padd optimization.");
7959   }
7960
7961   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7962   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7963   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7964 }
7965
7966 static SDValue findMUL_LOHI(SDValue V) {
7967   if (V->getOpcode() == ISD::UMUL_LOHI ||
7968       V->getOpcode() == ISD::SMUL_LOHI)
7969     return V;
7970   return SDValue();
7971 }
7972
7973 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7974                                      TargetLowering::DAGCombinerInfo &DCI,
7975                                      const ARMSubtarget *Subtarget) {
7976
7977   if (Subtarget->isThumb1Only()) return SDValue();
7978
7979   // Only perform the checks after legalize when the pattern is available.
7980   if (DCI.isBeforeLegalize()) return SDValue();
7981
7982   // Look for multiply add opportunities.
7983   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7984   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7985   // a glue link from the first add to the second add.
7986   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7987   // a S/UMLAL instruction.
7988   //          loAdd   UMUL_LOHI
7989   //            \    / :lo    \ :hi
7990   //             \  /          \          [no multiline comment]
7991   //              ADDC         |  hiAdd
7992   //                 \ :glue  /  /
7993   //                  \      /  /
7994   //                    ADDE
7995   //
7996   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7997   SDValue AddcOp0 = AddcNode->getOperand(0);
7998   SDValue AddcOp1 = AddcNode->getOperand(1);
7999
8000   // Check if the two operands are from the same mul_lohi node.
8001   if (AddcOp0.getNode() == AddcOp1.getNode())
8002     return SDValue();
8003
8004   assert(AddcNode->getNumValues() == 2 &&
8005          AddcNode->getValueType(0) == MVT::i32 &&
8006          "Expect ADDC with two result values. First: i32");
8007
8008   // Check that we have a glued ADDC node.
8009   if (AddcNode->getValueType(1) != MVT::Glue)
8010     return SDValue();
8011
8012   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8013   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8014       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8015       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8016       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8017     return SDValue();
8018
8019   // Look for the glued ADDE.
8020   SDNode* AddeNode = AddcNode->getGluedUser();
8021   if (!AddeNode)
8022     return SDValue();
8023
8024   // Make sure it is really an ADDE.
8025   if (AddeNode->getOpcode() != ISD::ADDE)
8026     return SDValue();
8027
8028   assert(AddeNode->getNumOperands() == 3 &&
8029          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8030          "ADDE node has the wrong inputs");
8031
8032   // Check for the triangle shape.
8033   SDValue AddeOp0 = AddeNode->getOperand(0);
8034   SDValue AddeOp1 = AddeNode->getOperand(1);
8035
8036   // Make sure that the ADDE operands are not coming from the same node.
8037   if (AddeOp0.getNode() == AddeOp1.getNode())
8038     return SDValue();
8039
8040   // Find the MUL_LOHI node walking up ADDE's operands.
8041   bool IsLeftOperandMUL = false;
8042   SDValue MULOp = findMUL_LOHI(AddeOp0);
8043   if (MULOp == SDValue())
8044    MULOp = findMUL_LOHI(AddeOp1);
8045   else
8046     IsLeftOperandMUL = true;
8047   if (MULOp == SDValue())
8048     return SDValue();
8049
8050   // Figure out the right opcode.
8051   unsigned Opc = MULOp->getOpcode();
8052   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8053
8054   // Figure out the high and low input values to the MLAL node.
8055   SDValue* HiAdd = nullptr;
8056   SDValue* LoMul = nullptr;
8057   SDValue* LowAdd = nullptr;
8058
8059   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8060   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8061     return SDValue();
8062
8063   if (IsLeftOperandMUL)
8064     HiAdd = &AddeOp1;
8065   else
8066     HiAdd = &AddeOp0;
8067
8068
8069   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8070   // whose low result is fed to the ADDC we are checking.
8071
8072   if (AddcOp0 == MULOp.getValue(0)) {
8073     LoMul = &AddcOp0;
8074     LowAdd = &AddcOp1;
8075   }
8076   if (AddcOp1 == MULOp.getValue(0)) {
8077     LoMul = &AddcOp1;
8078     LowAdd = &AddcOp0;
8079   }
8080
8081   if (!LoMul)
8082     return SDValue();
8083
8084   // Create the merged node.
8085   SelectionDAG &DAG = DCI.DAG;
8086
8087   // Build operand list.
8088   SmallVector<SDValue, 8> Ops;
8089   Ops.push_back(LoMul->getOperand(0));
8090   Ops.push_back(LoMul->getOperand(1));
8091   Ops.push_back(*LowAdd);
8092   Ops.push_back(*HiAdd);
8093
8094   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8095                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8096
8097   // Replace the ADDs' nodes uses by the MLA node's values.
8098   SDValue HiMLALResult(MLALNode.getNode(), 1);
8099   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8100
8101   SDValue LoMLALResult(MLALNode.getNode(), 0);
8102   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8103
8104   // Return original node to notify the driver to stop replacing.
8105   SDValue resNode(AddcNode, 0);
8106   return resNode;
8107 }
8108
8109 /// PerformADDCCombine - Target-specific dag combine transform from
8110 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8111 static SDValue PerformADDCCombine(SDNode *N,
8112                                  TargetLowering::DAGCombinerInfo &DCI,
8113                                  const ARMSubtarget *Subtarget) {
8114
8115   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8116
8117 }
8118
8119 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8120 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8121 /// called with the default operands, and if that fails, with commuted
8122 /// operands.
8123 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8124                                           TargetLowering::DAGCombinerInfo &DCI,
8125                                           const ARMSubtarget *Subtarget){
8126
8127   // Attempt to create vpaddl for this add.
8128   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8129   if (Result.getNode())
8130     return Result;
8131
8132   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8133   if (N0.getNode()->hasOneUse()) {
8134     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8135     if (Result.getNode()) return Result;
8136   }
8137   return SDValue();
8138 }
8139
8140 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8141 ///
8142 static SDValue PerformADDCombine(SDNode *N,
8143                                  TargetLowering::DAGCombinerInfo &DCI,
8144                                  const ARMSubtarget *Subtarget) {
8145   SDValue N0 = N->getOperand(0);
8146   SDValue N1 = N->getOperand(1);
8147
8148   // First try with the default operand order.
8149   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8150   if (Result.getNode())
8151     return Result;
8152
8153   // If that didn't work, try again with the operands commuted.
8154   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8155 }
8156
8157 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8158 ///
8159 static SDValue PerformSUBCombine(SDNode *N,
8160                                  TargetLowering::DAGCombinerInfo &DCI) {
8161   SDValue N0 = N->getOperand(0);
8162   SDValue N1 = N->getOperand(1);
8163
8164   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8165   if (N1.getNode()->hasOneUse()) {
8166     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8167     if (Result.getNode()) return Result;
8168   }
8169
8170   return SDValue();
8171 }
8172
8173 /// PerformVMULCombine
8174 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8175 /// special multiplier accumulator forwarding.
8176 ///   vmul d3, d0, d2
8177 ///   vmla d3, d1, d2
8178 /// is faster than
8179 ///   vadd d3, d0, d1
8180 ///   vmul d3, d3, d2
8181 //  However, for (A + B) * (A + B),
8182 //    vadd d2, d0, d1
8183 //    vmul d3, d0, d2
8184 //    vmla d3, d1, d2
8185 //  is slower than
8186 //    vadd d2, d0, d1
8187 //    vmul d3, d2, d2
8188 static SDValue PerformVMULCombine(SDNode *N,
8189                                   TargetLowering::DAGCombinerInfo &DCI,
8190                                   const ARMSubtarget *Subtarget) {
8191   if (!Subtarget->hasVMLxForwarding())
8192     return SDValue();
8193
8194   SelectionDAG &DAG = DCI.DAG;
8195   SDValue N0 = N->getOperand(0);
8196   SDValue N1 = N->getOperand(1);
8197   unsigned Opcode = N0.getOpcode();
8198   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8199       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8200     Opcode = N1.getOpcode();
8201     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8202         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8203       return SDValue();
8204     std::swap(N0, N1);
8205   }
8206
8207   if (N0 == N1)
8208     return SDValue();
8209
8210   EVT VT = N->getValueType(0);
8211   SDLoc DL(N);
8212   SDValue N00 = N0->getOperand(0);
8213   SDValue N01 = N0->getOperand(1);
8214   return DAG.getNode(Opcode, DL, VT,
8215                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8216                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8217 }
8218
8219 static SDValue PerformMULCombine(SDNode *N,
8220                                  TargetLowering::DAGCombinerInfo &DCI,
8221                                  const ARMSubtarget *Subtarget) {
8222   SelectionDAG &DAG = DCI.DAG;
8223
8224   if (Subtarget->isThumb1Only())
8225     return SDValue();
8226
8227   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8228     return SDValue();
8229
8230   EVT VT = N->getValueType(0);
8231   if (VT.is64BitVector() || VT.is128BitVector())
8232     return PerformVMULCombine(N, DCI, Subtarget);
8233   if (VT != MVT::i32)
8234     return SDValue();
8235
8236   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8237   if (!C)
8238     return SDValue();
8239
8240   int64_t MulAmt = C->getSExtValue();
8241   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8242
8243   ShiftAmt = ShiftAmt & (32 - 1);
8244   SDValue V = N->getOperand(0);
8245   SDLoc DL(N);
8246
8247   SDValue Res;
8248   MulAmt >>= ShiftAmt;
8249
8250   if (MulAmt >= 0) {
8251     if (isPowerOf2_32(MulAmt - 1)) {
8252       // (mul x, 2^N + 1) => (add (shl x, N), x)
8253       Res = DAG.getNode(ISD::ADD, DL, VT,
8254                         V,
8255                         DAG.getNode(ISD::SHL, DL, VT,
8256                                     V,
8257                                     DAG.getConstant(Log2_32(MulAmt - 1),
8258                                                     MVT::i32)));
8259     } else if (isPowerOf2_32(MulAmt + 1)) {
8260       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8261       Res = DAG.getNode(ISD::SUB, DL, VT,
8262                         DAG.getNode(ISD::SHL, DL, VT,
8263                                     V,
8264                                     DAG.getConstant(Log2_32(MulAmt + 1),
8265                                                     MVT::i32)),
8266                         V);
8267     } else
8268       return SDValue();
8269   } else {
8270     uint64_t MulAmtAbs = -MulAmt;
8271     if (isPowerOf2_32(MulAmtAbs + 1)) {
8272       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8273       Res = DAG.getNode(ISD::SUB, DL, VT,
8274                         V,
8275                         DAG.getNode(ISD::SHL, DL, VT,
8276                                     V,
8277                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8278                                                     MVT::i32)));
8279     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8280       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8281       Res = DAG.getNode(ISD::ADD, DL, VT,
8282                         V,
8283                         DAG.getNode(ISD::SHL, DL, VT,
8284                                     V,
8285                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8286                                                     MVT::i32)));
8287       Res = DAG.getNode(ISD::SUB, DL, VT,
8288                         DAG.getConstant(0, MVT::i32),Res);
8289
8290     } else
8291       return SDValue();
8292   }
8293
8294   if (ShiftAmt != 0)
8295     Res = DAG.getNode(ISD::SHL, DL, VT,
8296                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8297
8298   // Do not add new nodes to DAG combiner worklist.
8299   DCI.CombineTo(N, Res, false);
8300   return SDValue();
8301 }
8302
8303 static SDValue PerformANDCombine(SDNode *N,
8304                                  TargetLowering::DAGCombinerInfo &DCI,
8305                                  const ARMSubtarget *Subtarget) {
8306
8307   // Attempt to use immediate-form VBIC
8308   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8309   SDLoc dl(N);
8310   EVT VT = N->getValueType(0);
8311   SelectionDAG &DAG = DCI.DAG;
8312
8313   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8314     return SDValue();
8315
8316   APInt SplatBits, SplatUndef;
8317   unsigned SplatBitSize;
8318   bool HasAnyUndefs;
8319   if (BVN &&
8320       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8321     if (SplatBitSize <= 64) {
8322       EVT VbicVT;
8323       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8324                                       SplatUndef.getZExtValue(), SplatBitSize,
8325                                       DAG, VbicVT, VT.is128BitVector(),
8326                                       OtherModImm);
8327       if (Val.getNode()) {
8328         SDValue Input =
8329           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8330         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8331         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8332       }
8333     }
8334   }
8335
8336   if (!Subtarget->isThumb1Only()) {
8337     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8338     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8339     if (Result.getNode())
8340       return Result;
8341   }
8342
8343   return SDValue();
8344 }
8345
8346 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8347 static SDValue PerformORCombine(SDNode *N,
8348                                 TargetLowering::DAGCombinerInfo &DCI,
8349                                 const ARMSubtarget *Subtarget) {
8350   // Attempt to use immediate-form VORR
8351   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8352   SDLoc dl(N);
8353   EVT VT = N->getValueType(0);
8354   SelectionDAG &DAG = DCI.DAG;
8355
8356   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8357     return SDValue();
8358
8359   APInt SplatBits, SplatUndef;
8360   unsigned SplatBitSize;
8361   bool HasAnyUndefs;
8362   if (BVN && Subtarget->hasNEON() &&
8363       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8364     if (SplatBitSize <= 64) {
8365       EVT VorrVT;
8366       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8367                                       SplatUndef.getZExtValue(), SplatBitSize,
8368                                       DAG, VorrVT, VT.is128BitVector(),
8369                                       OtherModImm);
8370       if (Val.getNode()) {
8371         SDValue Input =
8372           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8373         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8374         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8375       }
8376     }
8377   }
8378
8379   if (!Subtarget->isThumb1Only()) {
8380     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8381     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8382     if (Result.getNode())
8383       return Result;
8384   }
8385
8386   // The code below optimizes (or (and X, Y), Z).
8387   // The AND operand needs to have a single user to make these optimizations
8388   // profitable.
8389   SDValue N0 = N->getOperand(0);
8390   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8391     return SDValue();
8392   SDValue N1 = N->getOperand(1);
8393
8394   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8395   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8396       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8397     APInt SplatUndef;
8398     unsigned SplatBitSize;
8399     bool HasAnyUndefs;
8400
8401     APInt SplatBits0, SplatBits1;
8402     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8403     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8404     // Ensure that the second operand of both ands are constants
8405     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8406                                       HasAnyUndefs) && !HasAnyUndefs) {
8407         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8408                                           HasAnyUndefs) && !HasAnyUndefs) {
8409             // Ensure that the bit width of the constants are the same and that
8410             // the splat arguments are logical inverses as per the pattern we
8411             // are trying to simplify.
8412             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8413                 SplatBits0 == ~SplatBits1) {
8414                 // Canonicalize the vector type to make instruction selection
8415                 // simpler.
8416                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8417                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8418                                              N0->getOperand(1),
8419                                              N0->getOperand(0),
8420                                              N1->getOperand(0));
8421                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8422             }
8423         }
8424     }
8425   }
8426
8427   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8428   // reasonable.
8429
8430   // BFI is only available on V6T2+
8431   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8432     return SDValue();
8433
8434   SDLoc DL(N);
8435   // 1) or (and A, mask), val => ARMbfi A, val, mask
8436   //      iff (val & mask) == val
8437   //
8438   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8439   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8440   //          && mask == ~mask2
8441   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8442   //          && ~mask == mask2
8443   //  (i.e., copy a bitfield value into another bitfield of the same width)
8444
8445   if (VT != MVT::i32)
8446     return SDValue();
8447
8448   SDValue N00 = N0.getOperand(0);
8449
8450   // The value and the mask need to be constants so we can verify this is
8451   // actually a bitfield set. If the mask is 0xffff, we can do better
8452   // via a movt instruction, so don't use BFI in that case.
8453   SDValue MaskOp = N0.getOperand(1);
8454   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8455   if (!MaskC)
8456     return SDValue();
8457   unsigned Mask = MaskC->getZExtValue();
8458   if (Mask == 0xffff)
8459     return SDValue();
8460   SDValue Res;
8461   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8462   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8463   if (N1C) {
8464     unsigned Val = N1C->getZExtValue();
8465     if ((Val & ~Mask) != Val)
8466       return SDValue();
8467
8468     if (ARM::isBitFieldInvertedMask(Mask)) {
8469       Val >>= countTrailingZeros(~Mask);
8470
8471       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8472                         DAG.getConstant(Val, MVT::i32),
8473                         DAG.getConstant(Mask, MVT::i32));
8474
8475       // Do not add new nodes to DAG combiner worklist.
8476       DCI.CombineTo(N, Res, false);
8477       return SDValue();
8478     }
8479   } else if (N1.getOpcode() == ISD::AND) {
8480     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8481     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8482     if (!N11C)
8483       return SDValue();
8484     unsigned Mask2 = N11C->getZExtValue();
8485
8486     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8487     // as is to match.
8488     if (ARM::isBitFieldInvertedMask(Mask) &&
8489         (Mask == ~Mask2)) {
8490       // The pack halfword instruction works better for masks that fit it,
8491       // so use that when it's available.
8492       if (Subtarget->hasT2ExtractPack() &&
8493           (Mask == 0xffff || Mask == 0xffff0000))
8494         return SDValue();
8495       // 2a
8496       unsigned amt = countTrailingZeros(Mask2);
8497       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8498                         DAG.getConstant(amt, MVT::i32));
8499       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8500                         DAG.getConstant(Mask, MVT::i32));
8501       // Do not add new nodes to DAG combiner worklist.
8502       DCI.CombineTo(N, Res, false);
8503       return SDValue();
8504     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8505                (~Mask == Mask2)) {
8506       // The pack halfword instruction works better for masks that fit it,
8507       // so use that when it's available.
8508       if (Subtarget->hasT2ExtractPack() &&
8509           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8510         return SDValue();
8511       // 2b
8512       unsigned lsb = countTrailingZeros(Mask);
8513       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8514                         DAG.getConstant(lsb, MVT::i32));
8515       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8516                         DAG.getConstant(Mask2, MVT::i32));
8517       // Do not add new nodes to DAG combiner worklist.
8518       DCI.CombineTo(N, Res, false);
8519       return SDValue();
8520     }
8521   }
8522
8523   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8524       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8525       ARM::isBitFieldInvertedMask(~Mask)) {
8526     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8527     // where lsb(mask) == #shamt and masked bits of B are known zero.
8528     SDValue ShAmt = N00.getOperand(1);
8529     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8530     unsigned LSB = countTrailingZeros(Mask);
8531     if (ShAmtC != LSB)
8532       return SDValue();
8533
8534     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8535                       DAG.getConstant(~Mask, MVT::i32));
8536
8537     // Do not add new nodes to DAG combiner worklist.
8538     DCI.CombineTo(N, Res, false);
8539   }
8540
8541   return SDValue();
8542 }
8543
8544 static SDValue PerformXORCombine(SDNode *N,
8545                                  TargetLowering::DAGCombinerInfo &DCI,
8546                                  const ARMSubtarget *Subtarget) {
8547   EVT VT = N->getValueType(0);
8548   SelectionDAG &DAG = DCI.DAG;
8549
8550   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8551     return SDValue();
8552
8553   if (!Subtarget->isThumb1Only()) {
8554     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8555     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8556     if (Result.getNode())
8557       return Result;
8558   }
8559
8560   return SDValue();
8561 }
8562
8563 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8564 /// the bits being cleared by the AND are not demanded by the BFI.
8565 static SDValue PerformBFICombine(SDNode *N,
8566                                  TargetLowering::DAGCombinerInfo &DCI) {
8567   SDValue N1 = N->getOperand(1);
8568   if (N1.getOpcode() == ISD::AND) {
8569     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8570     if (!N11C)
8571       return SDValue();
8572     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8573     unsigned LSB = countTrailingZeros(~InvMask);
8574     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8575     assert(Width <
8576                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8577            "undefined behavior");
8578     unsigned Mask = (1u << Width) - 1;
8579     unsigned Mask2 = N11C->getZExtValue();
8580     if ((Mask & (~Mask2)) == 0)
8581       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8582                              N->getOperand(0), N1.getOperand(0),
8583                              N->getOperand(2));
8584   }
8585   return SDValue();
8586 }
8587
8588 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8589 /// ARMISD::VMOVRRD.
8590 static SDValue PerformVMOVRRDCombine(SDNode *N,
8591                                      TargetLowering::DAGCombinerInfo &DCI,
8592                                      const ARMSubtarget *Subtarget) {
8593   // vmovrrd(vmovdrr x, y) -> x,y
8594   SDValue InDouble = N->getOperand(0);
8595   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8596     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8597
8598   // vmovrrd(load f64) -> (load i32), (load i32)
8599   SDNode *InNode = InDouble.getNode();
8600   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8601       InNode->getValueType(0) == MVT::f64 &&
8602       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8603       !cast<LoadSDNode>(InNode)->isVolatile()) {
8604     // TODO: Should this be done for non-FrameIndex operands?
8605     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8606
8607     SelectionDAG &DAG = DCI.DAG;
8608     SDLoc DL(LD);
8609     SDValue BasePtr = LD->getBasePtr();
8610     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8611                                  LD->getPointerInfo(), LD->isVolatile(),
8612                                  LD->isNonTemporal(), LD->isInvariant(),
8613                                  LD->getAlignment());
8614
8615     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8616                                     DAG.getConstant(4, MVT::i32));
8617     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8618                                  LD->getPointerInfo(), LD->isVolatile(),
8619                                  LD->isNonTemporal(), LD->isInvariant(),
8620                                  std::min(4U, LD->getAlignment() / 2));
8621
8622     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8623     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8624       std::swap (NewLD1, NewLD2);
8625     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8626     return Result;
8627   }
8628
8629   return SDValue();
8630 }
8631
8632 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8633 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8634 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8635   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8636   SDValue Op0 = N->getOperand(0);
8637   SDValue Op1 = N->getOperand(1);
8638   if (Op0.getOpcode() == ISD::BITCAST)
8639     Op0 = Op0.getOperand(0);
8640   if (Op1.getOpcode() == ISD::BITCAST)
8641     Op1 = Op1.getOperand(0);
8642   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8643       Op0.getNode() == Op1.getNode() &&
8644       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8645     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8646                        N->getValueType(0), Op0.getOperand(0));
8647   return SDValue();
8648 }
8649
8650 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8651 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8652 /// i64 vector to have f64 elements, since the value can then be loaded
8653 /// directly into a VFP register.
8654 static bool hasNormalLoadOperand(SDNode *N) {
8655   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8656   for (unsigned i = 0; i < NumElts; ++i) {
8657     SDNode *Elt = N->getOperand(i).getNode();
8658     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8659       return true;
8660   }
8661   return false;
8662 }
8663
8664 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8665 /// ISD::BUILD_VECTOR.
8666 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8667                                           TargetLowering::DAGCombinerInfo &DCI,
8668                                           const ARMSubtarget *Subtarget) {
8669   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8670   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8671   // into a pair of GPRs, which is fine when the value is used as a scalar,
8672   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8673   SelectionDAG &DAG = DCI.DAG;
8674   if (N->getNumOperands() == 2) {
8675     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8676     if (RV.getNode())
8677       return RV;
8678   }
8679
8680   // Load i64 elements as f64 values so that type legalization does not split
8681   // them up into i32 values.
8682   EVT VT = N->getValueType(0);
8683   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8684     return SDValue();
8685   SDLoc dl(N);
8686   SmallVector<SDValue, 8> Ops;
8687   unsigned NumElts = VT.getVectorNumElements();
8688   for (unsigned i = 0; i < NumElts; ++i) {
8689     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8690     Ops.push_back(V);
8691     // Make the DAGCombiner fold the bitcast.
8692     DCI.AddToWorklist(V.getNode());
8693   }
8694   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8695   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8696   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8697 }
8698
8699 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8700 static SDValue
8701 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8702   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8703   // At that time, we may have inserted bitcasts from integer to float.
8704   // If these bitcasts have survived DAGCombine, change the lowering of this
8705   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8706   // force to use floating point types.
8707
8708   // Make sure we can change the type of the vector.
8709   // This is possible iff:
8710   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8711   //    1.1. Vector is used only once.
8712   //    1.2. Use is a bit convert to an integer type.
8713   // 2. The size of its operands are 32-bits (64-bits are not legal).
8714   EVT VT = N->getValueType(0);
8715   EVT EltVT = VT.getVectorElementType();
8716
8717   // Check 1.1. and 2.
8718   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8719     return SDValue();
8720
8721   // By construction, the input type must be float.
8722   assert(EltVT == MVT::f32 && "Unexpected type!");
8723
8724   // Check 1.2.
8725   SDNode *Use = *N->use_begin();
8726   if (Use->getOpcode() != ISD::BITCAST ||
8727       Use->getValueType(0).isFloatingPoint())
8728     return SDValue();
8729
8730   // Check profitability.
8731   // Model is, if more than half of the relevant operands are bitcast from
8732   // i32, turn the build_vector into a sequence of insert_vector_elt.
8733   // Relevant operands are everything that is not statically
8734   // (i.e., at compile time) bitcasted.
8735   unsigned NumOfBitCastedElts = 0;
8736   unsigned NumElts = VT.getVectorNumElements();
8737   unsigned NumOfRelevantElts = NumElts;
8738   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8739     SDValue Elt = N->getOperand(Idx);
8740     if (Elt->getOpcode() == ISD::BITCAST) {
8741       // Assume only bit cast to i32 will go away.
8742       if (Elt->getOperand(0).getValueType() == MVT::i32)
8743         ++NumOfBitCastedElts;
8744     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8745       // Constants are statically casted, thus do not count them as
8746       // relevant operands.
8747       --NumOfRelevantElts;
8748   }
8749
8750   // Check if more than half of the elements require a non-free bitcast.
8751   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8752     return SDValue();
8753
8754   SelectionDAG &DAG = DCI.DAG;
8755   // Create the new vector type.
8756   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8757   // Check if the type is legal.
8758   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8759   if (!TLI.isTypeLegal(VecVT))
8760     return SDValue();
8761
8762   // Combine:
8763   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8764   // => BITCAST INSERT_VECTOR_ELT
8765   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8766   //                      (BITCAST EN), N.
8767   SDValue Vec = DAG.getUNDEF(VecVT);
8768   SDLoc dl(N);
8769   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8770     SDValue V = N->getOperand(Idx);
8771     if (V.getOpcode() == ISD::UNDEF)
8772       continue;
8773     if (V.getOpcode() == ISD::BITCAST &&
8774         V->getOperand(0).getValueType() == MVT::i32)
8775       // Fold obvious case.
8776       V = V.getOperand(0);
8777     else {
8778       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8779       // Make the DAGCombiner fold the bitcasts.
8780       DCI.AddToWorklist(V.getNode());
8781     }
8782     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8783     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8784   }
8785   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8786   // Make the DAGCombiner fold the bitcasts.
8787   DCI.AddToWorklist(Vec.getNode());
8788   return Vec;
8789 }
8790
8791 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8792 /// ISD::INSERT_VECTOR_ELT.
8793 static SDValue PerformInsertEltCombine(SDNode *N,
8794                                        TargetLowering::DAGCombinerInfo &DCI) {
8795   // Bitcast an i64 load inserted into a vector to f64.
8796   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8797   EVT VT = N->getValueType(0);
8798   SDNode *Elt = N->getOperand(1).getNode();
8799   if (VT.getVectorElementType() != MVT::i64 ||
8800       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8801     return SDValue();
8802
8803   SelectionDAG &DAG = DCI.DAG;
8804   SDLoc dl(N);
8805   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8806                                  VT.getVectorNumElements());
8807   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8808   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8809   // Make the DAGCombiner fold the bitcasts.
8810   DCI.AddToWorklist(Vec.getNode());
8811   DCI.AddToWorklist(V.getNode());
8812   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8813                                Vec, V, N->getOperand(2));
8814   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8815 }
8816
8817 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8818 /// ISD::VECTOR_SHUFFLE.
8819 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8820   // The LLVM shufflevector instruction does not require the shuffle mask
8821   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8822   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8823   // operands do not match the mask length, they are extended by concatenating
8824   // them with undef vectors.  That is probably the right thing for other
8825   // targets, but for NEON it is better to concatenate two double-register
8826   // size vector operands into a single quad-register size vector.  Do that
8827   // transformation here:
8828   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8829   //   shuffle(concat(v1, v2), undef)
8830   SDValue Op0 = N->getOperand(0);
8831   SDValue Op1 = N->getOperand(1);
8832   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8833       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8834       Op0.getNumOperands() != 2 ||
8835       Op1.getNumOperands() != 2)
8836     return SDValue();
8837   SDValue Concat0Op1 = Op0.getOperand(1);
8838   SDValue Concat1Op1 = Op1.getOperand(1);
8839   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8840       Concat1Op1.getOpcode() != ISD::UNDEF)
8841     return SDValue();
8842   // Skip the transformation if any of the types are illegal.
8843   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8844   EVT VT = N->getValueType(0);
8845   if (!TLI.isTypeLegal(VT) ||
8846       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8847       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8848     return SDValue();
8849
8850   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8851                                   Op0.getOperand(0), Op1.getOperand(0));
8852   // Translate the shuffle mask.
8853   SmallVector<int, 16> NewMask;
8854   unsigned NumElts = VT.getVectorNumElements();
8855   unsigned HalfElts = NumElts/2;
8856   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8857   for (unsigned n = 0; n < NumElts; ++n) {
8858     int MaskElt = SVN->getMaskElt(n);
8859     int NewElt = -1;
8860     if (MaskElt < (int)HalfElts)
8861       NewElt = MaskElt;
8862     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8863       NewElt = HalfElts + MaskElt - NumElts;
8864     NewMask.push_back(NewElt);
8865   }
8866   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8867                               DAG.getUNDEF(VT), NewMask.data());
8868 }
8869
8870 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8871 /// NEON load/store intrinsics to merge base address updates.
8872 static SDValue CombineBaseUpdate(SDNode *N,
8873                                  TargetLowering::DAGCombinerInfo &DCI) {
8874   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8875     return SDValue();
8876
8877   SelectionDAG &DAG = DCI.DAG;
8878   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8879                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8880   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8881   SDValue Addr = N->getOperand(AddrOpIdx);
8882
8883   // Search for a use of the address operand that is an increment.
8884   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8885          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8886     SDNode *User = *UI;
8887     if (User->getOpcode() != ISD::ADD ||
8888         UI.getUse().getResNo() != Addr.getResNo())
8889       continue;
8890
8891     // Check that the add is independent of the load/store.  Otherwise, folding
8892     // it would create a cycle.
8893     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8894       continue;
8895
8896     // Find the new opcode for the updating load/store.
8897     bool isLoad = true;
8898     bool isLaneOp = false;
8899     unsigned NewOpc = 0;
8900     unsigned NumVecs = 0;
8901     if (isIntrinsic) {
8902       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8903       switch (IntNo) {
8904       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8905       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8906         NumVecs = 1; break;
8907       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8908         NumVecs = 2; break;
8909       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8910         NumVecs = 3; break;
8911       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8912         NumVecs = 4; break;
8913       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8914         NumVecs = 2; isLaneOp = true; break;
8915       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8916         NumVecs = 3; isLaneOp = true; break;
8917       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8918         NumVecs = 4; isLaneOp = true; break;
8919       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8920         NumVecs = 1; isLoad = false; break;
8921       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8922         NumVecs = 2; isLoad = false; break;
8923       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8924         NumVecs = 3; isLoad = false; break;
8925       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8926         NumVecs = 4; isLoad = false; break;
8927       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8928         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8929       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8930         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8931       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8932         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8933       }
8934     } else {
8935       isLaneOp = true;
8936       switch (N->getOpcode()) {
8937       default: llvm_unreachable("unexpected opcode for Neon base update");
8938       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8939       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8940       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8941       }
8942     }
8943
8944     // Find the size of memory referenced by the load/store.
8945     EVT VecTy;
8946     if (isLoad)
8947       VecTy = N->getValueType(0);
8948     else
8949       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8950     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8951     if (isLaneOp)
8952       NumBytes /= VecTy.getVectorNumElements();
8953
8954     // If the increment is a constant, it must match the memory ref size.
8955     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8956     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8957       uint64_t IncVal = CInc->getZExtValue();
8958       if (IncVal != NumBytes)
8959         continue;
8960     } else if (NumBytes >= 3 * 16) {
8961       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8962       // separate instructions that make it harder to use a non-constant update.
8963       continue;
8964     }
8965
8966     // Create the new updating load/store node.
8967     EVT Tys[6];
8968     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8969     unsigned n;
8970     for (n = 0; n < NumResultVecs; ++n)
8971       Tys[n] = VecTy;
8972     Tys[n++] = MVT::i32;
8973     Tys[n] = MVT::Other;
8974     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
8975     SmallVector<SDValue, 8> Ops;
8976     Ops.push_back(N->getOperand(0)); // incoming chain
8977     Ops.push_back(N->getOperand(AddrOpIdx));
8978     Ops.push_back(Inc);
8979     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8980       Ops.push_back(N->getOperand(i));
8981     }
8982     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8983     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8984                                            Ops, MemInt->getMemoryVT(),
8985                                            MemInt->getMemOperand());
8986
8987     // Update the uses.
8988     std::vector<SDValue> NewResults;
8989     for (unsigned i = 0; i < NumResultVecs; ++i) {
8990       NewResults.push_back(SDValue(UpdN.getNode(), i));
8991     }
8992     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8993     DCI.CombineTo(N, NewResults);
8994     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8995
8996     break;
8997   }
8998   return SDValue();
8999 }
9000
9001 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9002 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9003 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9004 /// return true.
9005 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9006   SelectionDAG &DAG = DCI.DAG;
9007   EVT VT = N->getValueType(0);
9008   // vldN-dup instructions only support 64-bit vectors for N > 1.
9009   if (!VT.is64BitVector())
9010     return false;
9011
9012   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9013   SDNode *VLD = N->getOperand(0).getNode();
9014   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9015     return false;
9016   unsigned NumVecs = 0;
9017   unsigned NewOpc = 0;
9018   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9019   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9020     NumVecs = 2;
9021     NewOpc = ARMISD::VLD2DUP;
9022   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9023     NumVecs = 3;
9024     NewOpc = ARMISD::VLD3DUP;
9025   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9026     NumVecs = 4;
9027     NewOpc = ARMISD::VLD4DUP;
9028   } else {
9029     return false;
9030   }
9031
9032   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9033   // numbers match the load.
9034   unsigned VLDLaneNo =
9035     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9036   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9037        UI != UE; ++UI) {
9038     // Ignore uses of the chain result.
9039     if (UI.getUse().getResNo() == NumVecs)
9040       continue;
9041     SDNode *User = *UI;
9042     if (User->getOpcode() != ARMISD::VDUPLANE ||
9043         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9044       return false;
9045   }
9046
9047   // Create the vldN-dup node.
9048   EVT Tys[5];
9049   unsigned n;
9050   for (n = 0; n < NumVecs; ++n)
9051     Tys[n] = VT;
9052   Tys[n] = MVT::Other;
9053   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9054   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9055   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9056   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9057                                            Ops, VLDMemInt->getMemoryVT(),
9058                                            VLDMemInt->getMemOperand());
9059
9060   // Update the uses.
9061   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9062        UI != UE; ++UI) {
9063     unsigned ResNo = UI.getUse().getResNo();
9064     // Ignore uses of the chain result.
9065     if (ResNo == NumVecs)
9066       continue;
9067     SDNode *User = *UI;
9068     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9069   }
9070
9071   // Now the vldN-lane intrinsic is dead except for its chain result.
9072   // Update uses of the chain.
9073   std::vector<SDValue> VLDDupResults;
9074   for (unsigned n = 0; n < NumVecs; ++n)
9075     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9076   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9077   DCI.CombineTo(VLD, VLDDupResults);
9078
9079   return true;
9080 }
9081
9082 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9083 /// ARMISD::VDUPLANE.
9084 static SDValue PerformVDUPLANECombine(SDNode *N,
9085                                       TargetLowering::DAGCombinerInfo &DCI) {
9086   SDValue Op = N->getOperand(0);
9087
9088   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9089   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9090   if (CombineVLDDUP(N, DCI))
9091     return SDValue(N, 0);
9092
9093   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9094   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9095   while (Op.getOpcode() == ISD::BITCAST)
9096     Op = Op.getOperand(0);
9097   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9098     return SDValue();
9099
9100   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9101   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9102   // The canonical VMOV for a zero vector uses a 32-bit element size.
9103   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9104   unsigned EltBits;
9105   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9106     EltSize = 8;
9107   EVT VT = N->getValueType(0);
9108   if (EltSize > VT.getVectorElementType().getSizeInBits())
9109     return SDValue();
9110
9111   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9112 }
9113
9114 /// PerformSTORECombine - Target-specific dag combine xforms for
9115 /// ISD::STORE.
9116 static SDValue PerformSTORECombine(SDNode *N,
9117                                    TargetLowering::DAGCombinerInfo &DCI) {
9118   StoreSDNode *St = cast<StoreSDNode>(N);
9119   if (St->isVolatile())
9120     return SDValue();
9121
9122   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9123   // pack all of the elements in one place.  Next, store to memory in fewer
9124   // chunks.
9125   SDValue StVal = St->getValue();
9126   EVT VT = StVal.getValueType();
9127   if (St->isTruncatingStore() && VT.isVector()) {
9128     SelectionDAG &DAG = DCI.DAG;
9129     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9130     EVT StVT = St->getMemoryVT();
9131     unsigned NumElems = VT.getVectorNumElements();
9132     assert(StVT != VT && "Cannot truncate to the same type");
9133     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9134     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9135
9136     // From, To sizes and ElemCount must be pow of two
9137     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9138
9139     // We are going to use the original vector elt for storing.
9140     // Accumulated smaller vector elements must be a multiple of the store size.
9141     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9142
9143     unsigned SizeRatio  = FromEltSz / ToEltSz;
9144     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9145
9146     // Create a type on which we perform the shuffle.
9147     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9148                                      NumElems*SizeRatio);
9149     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9150
9151     SDLoc DL(St);
9152     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9153     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9154     for (unsigned i = 0; i < NumElems; ++i)
9155       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9156
9157     // Can't shuffle using an illegal type.
9158     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9159
9160     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9161                                 DAG.getUNDEF(WideVec.getValueType()),
9162                                 ShuffleVec.data());
9163     // At this point all of the data is stored at the bottom of the
9164     // register. We now need to save it to mem.
9165
9166     // Find the largest store unit
9167     MVT StoreType = MVT::i8;
9168     for (MVT Tp : MVT::integer_valuetypes()) {
9169       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9170         StoreType = Tp;
9171     }
9172     // Didn't find a legal store type.
9173     if (!TLI.isTypeLegal(StoreType))
9174       return SDValue();
9175
9176     // Bitcast the original vector into a vector of store-size units
9177     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9178             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9179     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9180     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9181     SmallVector<SDValue, 8> Chains;
9182     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9183                                         TLI.getPointerTy());
9184     SDValue BasePtr = St->getBasePtr();
9185
9186     // Perform one or more big stores into memory.
9187     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9188     for (unsigned I = 0; I < E; I++) {
9189       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9190                                    StoreType, ShuffWide,
9191                                    DAG.getIntPtrConstant(I));
9192       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9193                                 St->getPointerInfo(), St->isVolatile(),
9194                                 St->isNonTemporal(), St->getAlignment());
9195       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9196                             Increment);
9197       Chains.push_back(Ch);
9198     }
9199     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9200   }
9201
9202   if (!ISD::isNormalStore(St))
9203     return SDValue();
9204
9205   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9206   // ARM stores of arguments in the same cache line.
9207   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9208       StVal.getNode()->hasOneUse()) {
9209     SelectionDAG  &DAG = DCI.DAG;
9210     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9211     SDLoc DL(St);
9212     SDValue BasePtr = St->getBasePtr();
9213     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9214                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9215                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9216                                   St->isNonTemporal(), St->getAlignment());
9217
9218     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9219                                     DAG.getConstant(4, MVT::i32));
9220     return DAG.getStore(NewST1.getValue(0), DL,
9221                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9222                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9223                         St->isNonTemporal(),
9224                         std::min(4U, St->getAlignment() / 2));
9225   }
9226
9227   if (StVal.getValueType() == MVT::i64 &&
9228       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9229
9230     // Bitcast an i64 store extracted from a vector to f64.
9231     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9232     SelectionDAG &DAG = DCI.DAG;
9233     SDLoc dl(StVal);
9234     SDValue IntVec = StVal.getOperand(0);
9235     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9236                                    IntVec.getValueType().getVectorNumElements());
9237     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9238     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9239                                  Vec, StVal.getOperand(1));
9240     dl = SDLoc(N);
9241     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9242     // Make the DAGCombiner fold the bitcasts.
9243     DCI.AddToWorklist(Vec.getNode());
9244     DCI.AddToWorklist(ExtElt.getNode());
9245     DCI.AddToWorklist(V.getNode());
9246     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9247                         St->getPointerInfo(), St->isVolatile(),
9248                         St->isNonTemporal(), St->getAlignment(),
9249                         St->getAAInfo());
9250   }
9251
9252   return SDValue();
9253 }
9254
9255 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9256 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9257 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9258 {
9259   integerPart cN;
9260   integerPart c0 = 0;
9261   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9262        I != E; I++) {
9263     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9264     if (!C)
9265       return false;
9266
9267     bool isExact;
9268     APFloat APF = C->getValueAPF();
9269     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9270         != APFloat::opOK || !isExact)
9271       return false;
9272
9273     c0 = (I == 0) ? cN : c0;
9274     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9275       return false;
9276   }
9277   C = c0;
9278   return true;
9279 }
9280
9281 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9282 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9283 /// when the VMUL has a constant operand that is a power of 2.
9284 ///
9285 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9286 ///  vmul.f32        d16, d17, d16
9287 ///  vcvt.s32.f32    d16, d16
9288 /// becomes:
9289 ///  vcvt.s32.f32    d16, d16, #3
9290 static SDValue PerformVCVTCombine(SDNode *N,
9291                                   TargetLowering::DAGCombinerInfo &DCI,
9292                                   const ARMSubtarget *Subtarget) {
9293   SelectionDAG &DAG = DCI.DAG;
9294   SDValue Op = N->getOperand(0);
9295
9296   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9297       Op.getOpcode() != ISD::FMUL)
9298     return SDValue();
9299
9300   uint64_t C;
9301   SDValue N0 = Op->getOperand(0);
9302   SDValue ConstVec = Op->getOperand(1);
9303   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9304
9305   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9306       !isConstVecPow2(ConstVec, isSigned, C))
9307     return SDValue();
9308
9309   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9310   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9311   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9312   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9313       NumLanes > 4) {
9314     // These instructions only exist converting from f32 to i32. We can handle
9315     // smaller integers by generating an extra truncate, but larger ones would
9316     // be lossy. We also can't handle more then 4 lanes, since these intructions
9317     // only support v2i32/v4i32 types.
9318     return SDValue();
9319   }
9320
9321   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9322     Intrinsic::arm_neon_vcvtfp2fxu;
9323   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9324                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9325                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9326                                  DAG.getConstant(Log2_64(C), MVT::i32));
9327
9328   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9329     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9330
9331   return FixConv;
9332 }
9333
9334 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9335 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9336 /// when the VDIV has a constant operand that is a power of 2.
9337 ///
9338 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9339 ///  vcvt.f32.s32    d16, d16
9340 ///  vdiv.f32        d16, d17, d16
9341 /// becomes:
9342 ///  vcvt.f32.s32    d16, d16, #3
9343 static SDValue PerformVDIVCombine(SDNode *N,
9344                                   TargetLowering::DAGCombinerInfo &DCI,
9345                                   const ARMSubtarget *Subtarget) {
9346   SelectionDAG &DAG = DCI.DAG;
9347   SDValue Op = N->getOperand(0);
9348   unsigned OpOpcode = Op.getNode()->getOpcode();
9349
9350   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9351       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9352     return SDValue();
9353
9354   uint64_t C;
9355   SDValue ConstVec = N->getOperand(1);
9356   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9357
9358   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9359       !isConstVecPow2(ConstVec, isSigned, C))
9360     return SDValue();
9361
9362   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9363   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9364   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9365     // These instructions only exist converting from i32 to f32. We can handle
9366     // smaller integers by generating an extra extend, but larger ones would
9367     // be lossy.
9368     return SDValue();
9369   }
9370
9371   SDValue ConvInput = Op.getOperand(0);
9372   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9373   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9374     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9375                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9376                             ConvInput);
9377
9378   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9379     Intrinsic::arm_neon_vcvtfxu2fp;
9380   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9381                      Op.getValueType(),
9382                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9383                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9384 }
9385
9386 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9387 /// operand of a vector shift operation, where all the elements of the
9388 /// build_vector must have the same constant integer value.
9389 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9390   // Ignore bit_converts.
9391   while (Op.getOpcode() == ISD::BITCAST)
9392     Op = Op.getOperand(0);
9393   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9394   APInt SplatBits, SplatUndef;
9395   unsigned SplatBitSize;
9396   bool HasAnyUndefs;
9397   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9398                                       HasAnyUndefs, ElementBits) ||
9399       SplatBitSize > ElementBits)
9400     return false;
9401   Cnt = SplatBits.getSExtValue();
9402   return true;
9403 }
9404
9405 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9406 /// operand of a vector shift left operation.  That value must be in the range:
9407 ///   0 <= Value < ElementBits for a left shift; or
9408 ///   0 <= Value <= ElementBits for a long left shift.
9409 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9410   assert(VT.isVector() && "vector shift count is not a vector type");
9411   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9412   if (! getVShiftImm(Op, ElementBits, Cnt))
9413     return false;
9414   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9415 }
9416
9417 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9418 /// operand of a vector shift right operation.  For a shift opcode, the value
9419 /// is positive, but for an intrinsic the value count must be negative. The
9420 /// absolute value must be in the range:
9421 ///   1 <= |Value| <= ElementBits for a right shift; or
9422 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9423 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9424                          int64_t &Cnt) {
9425   assert(VT.isVector() && "vector shift count is not a vector type");
9426   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9427   if (! getVShiftImm(Op, ElementBits, Cnt))
9428     return false;
9429   if (isIntrinsic)
9430     Cnt = -Cnt;
9431   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9432 }
9433
9434 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9435 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9436   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9437   switch (IntNo) {
9438   default:
9439     // Don't do anything for most intrinsics.
9440     break;
9441
9442   // Vector shifts: check for immediate versions and lower them.
9443   // Note: This is done during DAG combining instead of DAG legalizing because
9444   // the build_vectors for 64-bit vector element shift counts are generally
9445   // not legal, and it is hard to see their values after they get legalized to
9446   // loads from a constant pool.
9447   case Intrinsic::arm_neon_vshifts:
9448   case Intrinsic::arm_neon_vshiftu:
9449   case Intrinsic::arm_neon_vrshifts:
9450   case Intrinsic::arm_neon_vrshiftu:
9451   case Intrinsic::arm_neon_vrshiftn:
9452   case Intrinsic::arm_neon_vqshifts:
9453   case Intrinsic::arm_neon_vqshiftu:
9454   case Intrinsic::arm_neon_vqshiftsu:
9455   case Intrinsic::arm_neon_vqshiftns:
9456   case Intrinsic::arm_neon_vqshiftnu:
9457   case Intrinsic::arm_neon_vqshiftnsu:
9458   case Intrinsic::arm_neon_vqrshiftns:
9459   case Intrinsic::arm_neon_vqrshiftnu:
9460   case Intrinsic::arm_neon_vqrshiftnsu: {
9461     EVT VT = N->getOperand(1).getValueType();
9462     int64_t Cnt;
9463     unsigned VShiftOpc = 0;
9464
9465     switch (IntNo) {
9466     case Intrinsic::arm_neon_vshifts:
9467     case Intrinsic::arm_neon_vshiftu:
9468       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9469         VShiftOpc = ARMISD::VSHL;
9470         break;
9471       }
9472       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9473         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9474                      ARMISD::VSHRs : ARMISD::VSHRu);
9475         break;
9476       }
9477       return SDValue();
9478
9479     case Intrinsic::arm_neon_vrshifts:
9480     case Intrinsic::arm_neon_vrshiftu:
9481       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9482         break;
9483       return SDValue();
9484
9485     case Intrinsic::arm_neon_vqshifts:
9486     case Intrinsic::arm_neon_vqshiftu:
9487       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9488         break;
9489       return SDValue();
9490
9491     case Intrinsic::arm_neon_vqshiftsu:
9492       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9493         break;
9494       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9495
9496     case Intrinsic::arm_neon_vrshiftn:
9497     case Intrinsic::arm_neon_vqshiftns:
9498     case Intrinsic::arm_neon_vqshiftnu:
9499     case Intrinsic::arm_neon_vqshiftnsu:
9500     case Intrinsic::arm_neon_vqrshiftns:
9501     case Intrinsic::arm_neon_vqrshiftnu:
9502     case Intrinsic::arm_neon_vqrshiftnsu:
9503       // Narrowing shifts require an immediate right shift.
9504       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9505         break;
9506       llvm_unreachable("invalid shift count for narrowing vector shift "
9507                        "intrinsic");
9508
9509     default:
9510       llvm_unreachable("unhandled vector shift");
9511     }
9512
9513     switch (IntNo) {
9514     case Intrinsic::arm_neon_vshifts:
9515     case Intrinsic::arm_neon_vshiftu:
9516       // Opcode already set above.
9517       break;
9518     case Intrinsic::arm_neon_vrshifts:
9519       VShiftOpc = ARMISD::VRSHRs; break;
9520     case Intrinsic::arm_neon_vrshiftu:
9521       VShiftOpc = ARMISD::VRSHRu; break;
9522     case Intrinsic::arm_neon_vrshiftn:
9523       VShiftOpc = ARMISD::VRSHRN; break;
9524     case Intrinsic::arm_neon_vqshifts:
9525       VShiftOpc = ARMISD::VQSHLs; break;
9526     case Intrinsic::arm_neon_vqshiftu:
9527       VShiftOpc = ARMISD::VQSHLu; break;
9528     case Intrinsic::arm_neon_vqshiftsu:
9529       VShiftOpc = ARMISD::VQSHLsu; break;
9530     case Intrinsic::arm_neon_vqshiftns:
9531       VShiftOpc = ARMISD::VQSHRNs; break;
9532     case Intrinsic::arm_neon_vqshiftnu:
9533       VShiftOpc = ARMISD::VQSHRNu; break;
9534     case Intrinsic::arm_neon_vqshiftnsu:
9535       VShiftOpc = ARMISD::VQSHRNsu; break;
9536     case Intrinsic::arm_neon_vqrshiftns:
9537       VShiftOpc = ARMISD::VQRSHRNs; break;
9538     case Intrinsic::arm_neon_vqrshiftnu:
9539       VShiftOpc = ARMISD::VQRSHRNu; break;
9540     case Intrinsic::arm_neon_vqrshiftnsu:
9541       VShiftOpc = ARMISD::VQRSHRNsu; break;
9542     }
9543
9544     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9545                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9546   }
9547
9548   case Intrinsic::arm_neon_vshiftins: {
9549     EVT VT = N->getOperand(1).getValueType();
9550     int64_t Cnt;
9551     unsigned VShiftOpc = 0;
9552
9553     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9554       VShiftOpc = ARMISD::VSLI;
9555     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9556       VShiftOpc = ARMISD::VSRI;
9557     else {
9558       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9559     }
9560
9561     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9562                        N->getOperand(1), N->getOperand(2),
9563                        DAG.getConstant(Cnt, MVT::i32));
9564   }
9565
9566   case Intrinsic::arm_neon_vqrshifts:
9567   case Intrinsic::arm_neon_vqrshiftu:
9568     // No immediate versions of these to check for.
9569     break;
9570   }
9571
9572   return SDValue();
9573 }
9574
9575 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9576 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9577 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9578 /// vector element shift counts are generally not legal, and it is hard to see
9579 /// their values after they get legalized to loads from a constant pool.
9580 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9581                                    const ARMSubtarget *ST) {
9582   EVT VT = N->getValueType(0);
9583   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9584     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9585     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9586     SDValue N1 = N->getOperand(1);
9587     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9588       SDValue N0 = N->getOperand(0);
9589       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9590           DAG.MaskedValueIsZero(N0.getOperand(0),
9591                                 APInt::getHighBitsSet(32, 16)))
9592         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9593     }
9594   }
9595
9596   // Nothing to be done for scalar shifts.
9597   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9598   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9599     return SDValue();
9600
9601   assert(ST->hasNEON() && "unexpected vector shift");
9602   int64_t Cnt;
9603
9604   switch (N->getOpcode()) {
9605   default: llvm_unreachable("unexpected shift opcode");
9606
9607   case ISD::SHL:
9608     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9609       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9610                          DAG.getConstant(Cnt, MVT::i32));
9611     break;
9612
9613   case ISD::SRA:
9614   case ISD::SRL:
9615     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9616       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9617                             ARMISD::VSHRs : ARMISD::VSHRu);
9618       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9619                          DAG.getConstant(Cnt, MVT::i32));
9620     }
9621   }
9622   return SDValue();
9623 }
9624
9625 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9626 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9627 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9628                                     const ARMSubtarget *ST) {
9629   SDValue N0 = N->getOperand(0);
9630
9631   // Check for sign- and zero-extensions of vector extract operations of 8-
9632   // and 16-bit vector elements.  NEON supports these directly.  They are
9633   // handled during DAG combining because type legalization will promote them
9634   // to 32-bit types and it is messy to recognize the operations after that.
9635   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9636     SDValue Vec = N0.getOperand(0);
9637     SDValue Lane = N0.getOperand(1);
9638     EVT VT = N->getValueType(0);
9639     EVT EltVT = N0.getValueType();
9640     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9641
9642     if (VT == MVT::i32 &&
9643         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9644         TLI.isTypeLegal(Vec.getValueType()) &&
9645         isa<ConstantSDNode>(Lane)) {
9646
9647       unsigned Opc = 0;
9648       switch (N->getOpcode()) {
9649       default: llvm_unreachable("unexpected opcode");
9650       case ISD::SIGN_EXTEND:
9651         Opc = ARMISD::VGETLANEs;
9652         break;
9653       case ISD::ZERO_EXTEND:
9654       case ISD::ANY_EXTEND:
9655         Opc = ARMISD::VGETLANEu;
9656         break;
9657       }
9658       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9659     }
9660   }
9661
9662   return SDValue();
9663 }
9664
9665 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9666 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9667 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9668                                        const ARMSubtarget *ST) {
9669   // If the target supports NEON, try to use vmax/vmin instructions for f32
9670   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9671   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9672   // a NaN; only do the transformation when it matches that behavior.
9673
9674   // For now only do this when using NEON for FP operations; if using VFP, it
9675   // is not obvious that the benefit outweighs the cost of switching to the
9676   // NEON pipeline.
9677   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9678       N->getValueType(0) != MVT::f32)
9679     return SDValue();
9680
9681   SDValue CondLHS = N->getOperand(0);
9682   SDValue CondRHS = N->getOperand(1);
9683   SDValue LHS = N->getOperand(2);
9684   SDValue RHS = N->getOperand(3);
9685   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9686
9687   unsigned Opcode = 0;
9688   bool IsReversed;
9689   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9690     IsReversed = false; // x CC y ? x : y
9691   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9692     IsReversed = true ; // x CC y ? y : x
9693   } else {
9694     return SDValue();
9695   }
9696
9697   bool IsUnordered;
9698   switch (CC) {
9699   default: break;
9700   case ISD::SETOLT:
9701   case ISD::SETOLE:
9702   case ISD::SETLT:
9703   case ISD::SETLE:
9704   case ISD::SETULT:
9705   case ISD::SETULE:
9706     // If LHS is NaN, an ordered comparison will be false and the result will
9707     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9708     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9709     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9710     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9711       break;
9712     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9713     // will return -0, so vmin can only be used for unsafe math or if one of
9714     // the operands is known to be nonzero.
9715     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9716         !DAG.getTarget().Options.UnsafeFPMath &&
9717         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9718       break;
9719     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9720     break;
9721
9722   case ISD::SETOGT:
9723   case ISD::SETOGE:
9724   case ISD::SETGT:
9725   case ISD::SETGE:
9726   case ISD::SETUGT:
9727   case ISD::SETUGE:
9728     // If LHS is NaN, an ordered comparison will be false and the result will
9729     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9730     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9731     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9732     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9733       break;
9734     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9735     // will return +0, so vmax can only be used for unsafe math or if one of
9736     // the operands is known to be nonzero.
9737     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9738         !DAG.getTarget().Options.UnsafeFPMath &&
9739         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9740       break;
9741     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9742     break;
9743   }
9744
9745   if (!Opcode)
9746     return SDValue();
9747   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9748 }
9749
9750 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9751 SDValue
9752 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9753   SDValue Cmp = N->getOperand(4);
9754   if (Cmp.getOpcode() != ARMISD::CMPZ)
9755     // Only looking at EQ and NE cases.
9756     return SDValue();
9757
9758   EVT VT = N->getValueType(0);
9759   SDLoc dl(N);
9760   SDValue LHS = Cmp.getOperand(0);
9761   SDValue RHS = Cmp.getOperand(1);
9762   SDValue FalseVal = N->getOperand(0);
9763   SDValue TrueVal = N->getOperand(1);
9764   SDValue ARMcc = N->getOperand(2);
9765   ARMCC::CondCodes CC =
9766     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9767
9768   // Simplify
9769   //   mov     r1, r0
9770   //   cmp     r1, x
9771   //   mov     r0, y
9772   //   moveq   r0, x
9773   // to
9774   //   cmp     r0, x
9775   //   movne   r0, y
9776   //
9777   //   mov     r1, r0
9778   //   cmp     r1, x
9779   //   mov     r0, x
9780   //   movne   r0, y
9781   // to
9782   //   cmp     r0, x
9783   //   movne   r0, y
9784   /// FIXME: Turn this into a target neutral optimization?
9785   SDValue Res;
9786   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9787     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9788                       N->getOperand(3), Cmp);
9789   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9790     SDValue ARMcc;
9791     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9792     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9793                       N->getOperand(3), NewCmp);
9794   }
9795
9796   if (Res.getNode()) {
9797     APInt KnownZero, KnownOne;
9798     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9799     // Capture demanded bits information that would be otherwise lost.
9800     if (KnownZero == 0xfffffffe)
9801       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9802                         DAG.getValueType(MVT::i1));
9803     else if (KnownZero == 0xffffff00)
9804       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9805                         DAG.getValueType(MVT::i8));
9806     else if (KnownZero == 0xffff0000)
9807       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9808                         DAG.getValueType(MVT::i16));
9809   }
9810
9811   return Res;
9812 }
9813
9814 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9815                                              DAGCombinerInfo &DCI) const {
9816   switch (N->getOpcode()) {
9817   default: break;
9818   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9819   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9820   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9821   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9822   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9823   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9824   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9825   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9826   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9827   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9828   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9829   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9830   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9831   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9832   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9833   case ISD::FP_TO_SINT:
9834   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9835   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9836   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9837   case ISD::SHL:
9838   case ISD::SRA:
9839   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9840   case ISD::SIGN_EXTEND:
9841   case ISD::ZERO_EXTEND:
9842   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9843   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9844   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9845   case ARMISD::VLD2DUP:
9846   case ARMISD::VLD3DUP:
9847   case ARMISD::VLD4DUP:
9848     return CombineBaseUpdate(N, DCI);
9849   case ARMISD::BUILD_VECTOR:
9850     return PerformARMBUILD_VECTORCombine(N, DCI);
9851   case ISD::INTRINSIC_VOID:
9852   case ISD::INTRINSIC_W_CHAIN:
9853     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9854     case Intrinsic::arm_neon_vld1:
9855     case Intrinsic::arm_neon_vld2:
9856     case Intrinsic::arm_neon_vld3:
9857     case Intrinsic::arm_neon_vld4:
9858     case Intrinsic::arm_neon_vld2lane:
9859     case Intrinsic::arm_neon_vld3lane:
9860     case Intrinsic::arm_neon_vld4lane:
9861     case Intrinsic::arm_neon_vst1:
9862     case Intrinsic::arm_neon_vst2:
9863     case Intrinsic::arm_neon_vst3:
9864     case Intrinsic::arm_neon_vst4:
9865     case Intrinsic::arm_neon_vst2lane:
9866     case Intrinsic::arm_neon_vst3lane:
9867     case Intrinsic::arm_neon_vst4lane:
9868       return CombineBaseUpdate(N, DCI);
9869     default: break;
9870     }
9871     break;
9872   }
9873   return SDValue();
9874 }
9875
9876 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9877                                                           EVT VT) const {
9878   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9879 }
9880
9881 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9882                                                        unsigned,
9883                                                        unsigned,
9884                                                        bool *Fast) const {
9885   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9886   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9887
9888   switch (VT.getSimpleVT().SimpleTy) {
9889   default:
9890     return false;
9891   case MVT::i8:
9892   case MVT::i16:
9893   case MVT::i32: {
9894     // Unaligned access can use (for example) LRDB, LRDH, LDR
9895     if (AllowsUnaligned) {
9896       if (Fast)
9897         *Fast = Subtarget->hasV7Ops();
9898       return true;
9899     }
9900     return false;
9901   }
9902   case MVT::f64:
9903   case MVT::v2f64: {
9904     // For any little-endian targets with neon, we can support unaligned ld/st
9905     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9906     // A big-endian target may also explicitly support unaligned accesses
9907     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9908       if (Fast)
9909         *Fast = true;
9910       return true;
9911     }
9912     return false;
9913   }
9914   }
9915 }
9916
9917 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9918                        unsigned AlignCheck) {
9919   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9920           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9921 }
9922
9923 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9924                                            unsigned DstAlign, unsigned SrcAlign,
9925                                            bool IsMemset, bool ZeroMemset,
9926                                            bool MemcpyStrSrc,
9927                                            MachineFunction &MF) const {
9928   const Function *F = MF.getFunction();
9929
9930   // See if we can use NEON instructions for this...
9931   if ((!IsMemset || ZeroMemset) &&
9932       Subtarget->hasNEON() &&
9933       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9934                                        Attribute::NoImplicitFloat)) {
9935     bool Fast;
9936     if (Size >= 16 &&
9937         (memOpAlign(SrcAlign, DstAlign, 16) ||
9938          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9939       return MVT::v2f64;
9940     } else if (Size >= 8 &&
9941                (memOpAlign(SrcAlign, DstAlign, 8) ||
9942                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9943                  Fast))) {
9944       return MVT::f64;
9945     }
9946   }
9947
9948   // Lowering to i32/i16 if the size permits.
9949   if (Size >= 4)
9950     return MVT::i32;
9951   else if (Size >= 2)
9952     return MVT::i16;
9953
9954   // Let the target-independent logic figure it out.
9955   return MVT::Other;
9956 }
9957
9958 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9959   if (Val.getOpcode() != ISD::LOAD)
9960     return false;
9961
9962   EVT VT1 = Val.getValueType();
9963   if (!VT1.isSimple() || !VT1.isInteger() ||
9964       !VT2.isSimple() || !VT2.isInteger())
9965     return false;
9966
9967   switch (VT1.getSimpleVT().SimpleTy) {
9968   default: break;
9969   case MVT::i1:
9970   case MVT::i8:
9971   case MVT::i16:
9972     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9973     return true;
9974   }
9975
9976   return false;
9977 }
9978
9979 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9980   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9981     return false;
9982
9983   if (!isTypeLegal(EVT::getEVT(Ty1)))
9984     return false;
9985
9986   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9987
9988   // Assuming the caller doesn't have a zeroext or signext return parameter,
9989   // truncation all the way down to i1 is valid.
9990   return true;
9991 }
9992
9993
9994 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9995   if (V < 0)
9996     return false;
9997
9998   unsigned Scale = 1;
9999   switch (VT.getSimpleVT().SimpleTy) {
10000   default: return false;
10001   case MVT::i1:
10002   case MVT::i8:
10003     // Scale == 1;
10004     break;
10005   case MVT::i16:
10006     // Scale == 2;
10007     Scale = 2;
10008     break;
10009   case MVT::i32:
10010     // Scale == 4;
10011     Scale = 4;
10012     break;
10013   }
10014
10015   if ((V & (Scale - 1)) != 0)
10016     return false;
10017   V /= Scale;
10018   return V == (V & ((1LL << 5) - 1));
10019 }
10020
10021 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10022                                       const ARMSubtarget *Subtarget) {
10023   bool isNeg = false;
10024   if (V < 0) {
10025     isNeg = true;
10026     V = - V;
10027   }
10028
10029   switch (VT.getSimpleVT().SimpleTy) {
10030   default: return false;
10031   case MVT::i1:
10032   case MVT::i8:
10033   case MVT::i16:
10034   case MVT::i32:
10035     // + imm12 or - imm8
10036     if (isNeg)
10037       return V == (V & ((1LL << 8) - 1));
10038     return V == (V & ((1LL << 12) - 1));
10039   case MVT::f32:
10040   case MVT::f64:
10041     // Same as ARM mode. FIXME: NEON?
10042     if (!Subtarget->hasVFP2())
10043       return false;
10044     if ((V & 3) != 0)
10045       return false;
10046     V >>= 2;
10047     return V == (V & ((1LL << 8) - 1));
10048   }
10049 }
10050
10051 /// isLegalAddressImmediate - Return true if the integer value can be used
10052 /// as the offset of the target addressing mode for load / store of the
10053 /// given type.
10054 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10055                                     const ARMSubtarget *Subtarget) {
10056   if (V == 0)
10057     return true;
10058
10059   if (!VT.isSimple())
10060     return false;
10061
10062   if (Subtarget->isThumb1Only())
10063     return isLegalT1AddressImmediate(V, VT);
10064   else if (Subtarget->isThumb2())
10065     return isLegalT2AddressImmediate(V, VT, Subtarget);
10066
10067   // ARM mode.
10068   if (V < 0)
10069     V = - V;
10070   switch (VT.getSimpleVT().SimpleTy) {
10071   default: return false;
10072   case MVT::i1:
10073   case MVT::i8:
10074   case MVT::i32:
10075     // +- imm12
10076     return V == (V & ((1LL << 12) - 1));
10077   case MVT::i16:
10078     // +- imm8
10079     return V == (V & ((1LL << 8) - 1));
10080   case MVT::f32:
10081   case MVT::f64:
10082     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10083       return false;
10084     if ((V & 3) != 0)
10085       return false;
10086     V >>= 2;
10087     return V == (V & ((1LL << 8) - 1));
10088   }
10089 }
10090
10091 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10092                                                       EVT VT) const {
10093   int Scale = AM.Scale;
10094   if (Scale < 0)
10095     return false;
10096
10097   switch (VT.getSimpleVT().SimpleTy) {
10098   default: return false;
10099   case MVT::i1:
10100   case MVT::i8:
10101   case MVT::i16:
10102   case MVT::i32:
10103     if (Scale == 1)
10104       return true;
10105     // r + r << imm
10106     Scale = Scale & ~1;
10107     return Scale == 2 || Scale == 4 || Scale == 8;
10108   case MVT::i64:
10109     // r + r
10110     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10111       return true;
10112     return false;
10113   case MVT::isVoid:
10114     // Note, we allow "void" uses (basically, uses that aren't loads or
10115     // stores), because arm allows folding a scale into many arithmetic
10116     // operations.  This should be made more precise and revisited later.
10117
10118     // Allow r << imm, but the imm has to be a multiple of two.
10119     if (Scale & 1) return false;
10120     return isPowerOf2_32(Scale);
10121   }
10122 }
10123
10124 /// isLegalAddressingMode - Return true if the addressing mode represented
10125 /// by AM is legal for this target, for a load/store of the specified type.
10126 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10127                                               Type *Ty) const {
10128   EVT VT = getValueType(Ty, true);
10129   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10130     return false;
10131
10132   // Can never fold addr of global into load/store.
10133   if (AM.BaseGV)
10134     return false;
10135
10136   switch (AM.Scale) {
10137   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10138     break;
10139   case 1:
10140     if (Subtarget->isThumb1Only())
10141       return false;
10142     // FALL THROUGH.
10143   default:
10144     // ARM doesn't support any R+R*scale+imm addr modes.
10145     if (AM.BaseOffs)
10146       return false;
10147
10148     if (!VT.isSimple())
10149       return false;
10150
10151     if (Subtarget->isThumb2())
10152       return isLegalT2ScaledAddressingMode(AM, VT);
10153
10154     int Scale = AM.Scale;
10155     switch (VT.getSimpleVT().SimpleTy) {
10156     default: return false;
10157     case MVT::i1:
10158     case MVT::i8:
10159     case MVT::i32:
10160       if (Scale < 0) Scale = -Scale;
10161       if (Scale == 1)
10162         return true;
10163       // r + r << imm
10164       return isPowerOf2_32(Scale & ~1);
10165     case MVT::i16:
10166     case MVT::i64:
10167       // r + r
10168       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10169         return true;
10170       return false;
10171
10172     case MVT::isVoid:
10173       // Note, we allow "void" uses (basically, uses that aren't loads or
10174       // stores), because arm allows folding a scale into many arithmetic
10175       // operations.  This should be made more precise and revisited later.
10176
10177       // Allow r << imm, but the imm has to be a multiple of two.
10178       if (Scale & 1) return false;
10179       return isPowerOf2_32(Scale);
10180     }
10181   }
10182   return true;
10183 }
10184
10185 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10186 /// icmp immediate, that is the target has icmp instructions which can compare
10187 /// a register against the immediate without having to materialize the
10188 /// immediate into a register.
10189 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10190   // Thumb2 and ARM modes can use cmn for negative immediates.
10191   if (!Subtarget->isThumb())
10192     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10193   if (Subtarget->isThumb2())
10194     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10195   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10196   return Imm >= 0 && Imm <= 255;
10197 }
10198
10199 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10200 /// *or sub* immediate, that is the target has add or sub instructions which can
10201 /// add a register with the immediate without having to materialize the
10202 /// immediate into a register.
10203 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10204   // Same encoding for add/sub, just flip the sign.
10205   int64_t AbsImm = llvm::abs64(Imm);
10206   if (!Subtarget->isThumb())
10207     return ARM_AM::getSOImmVal(AbsImm) != -1;
10208   if (Subtarget->isThumb2())
10209     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10210   // Thumb1 only has 8-bit unsigned immediate.
10211   return AbsImm >= 0 && AbsImm <= 255;
10212 }
10213
10214 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10215                                       bool isSEXTLoad, SDValue &Base,
10216                                       SDValue &Offset, bool &isInc,
10217                                       SelectionDAG &DAG) {
10218   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10219     return false;
10220
10221   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10222     // AddressingMode 3
10223     Base = Ptr->getOperand(0);
10224     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10225       int RHSC = (int)RHS->getZExtValue();
10226       if (RHSC < 0 && RHSC > -256) {
10227         assert(Ptr->getOpcode() == ISD::ADD);
10228         isInc = false;
10229         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10230         return true;
10231       }
10232     }
10233     isInc = (Ptr->getOpcode() == ISD::ADD);
10234     Offset = Ptr->getOperand(1);
10235     return true;
10236   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10237     // AddressingMode 2
10238     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10239       int RHSC = (int)RHS->getZExtValue();
10240       if (RHSC < 0 && RHSC > -0x1000) {
10241         assert(Ptr->getOpcode() == ISD::ADD);
10242         isInc = false;
10243         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10244         Base = Ptr->getOperand(0);
10245         return true;
10246       }
10247     }
10248
10249     if (Ptr->getOpcode() == ISD::ADD) {
10250       isInc = true;
10251       ARM_AM::ShiftOpc ShOpcVal=
10252         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10253       if (ShOpcVal != ARM_AM::no_shift) {
10254         Base = Ptr->getOperand(1);
10255         Offset = Ptr->getOperand(0);
10256       } else {
10257         Base = Ptr->getOperand(0);
10258         Offset = Ptr->getOperand(1);
10259       }
10260       return true;
10261     }
10262
10263     isInc = (Ptr->getOpcode() == ISD::ADD);
10264     Base = Ptr->getOperand(0);
10265     Offset = Ptr->getOperand(1);
10266     return true;
10267   }
10268
10269   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10270   return false;
10271 }
10272
10273 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10274                                      bool isSEXTLoad, SDValue &Base,
10275                                      SDValue &Offset, bool &isInc,
10276                                      SelectionDAG &DAG) {
10277   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10278     return false;
10279
10280   Base = Ptr->getOperand(0);
10281   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10282     int RHSC = (int)RHS->getZExtValue();
10283     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10284       assert(Ptr->getOpcode() == ISD::ADD);
10285       isInc = false;
10286       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10287       return true;
10288     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10289       isInc = Ptr->getOpcode() == ISD::ADD;
10290       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10291       return true;
10292     }
10293   }
10294
10295   return false;
10296 }
10297
10298 /// getPreIndexedAddressParts - returns true by value, base pointer and
10299 /// offset pointer and addressing mode by reference if the node's address
10300 /// can be legally represented as pre-indexed load / store address.
10301 bool
10302 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10303                                              SDValue &Offset,
10304                                              ISD::MemIndexedMode &AM,
10305                                              SelectionDAG &DAG) const {
10306   if (Subtarget->isThumb1Only())
10307     return false;
10308
10309   EVT VT;
10310   SDValue Ptr;
10311   bool isSEXTLoad = false;
10312   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10313     Ptr = LD->getBasePtr();
10314     VT  = LD->getMemoryVT();
10315     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10316   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10317     Ptr = ST->getBasePtr();
10318     VT  = ST->getMemoryVT();
10319   } else
10320     return false;
10321
10322   bool isInc;
10323   bool isLegal = false;
10324   if (Subtarget->isThumb2())
10325     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10326                                        Offset, isInc, DAG);
10327   else
10328     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10329                                         Offset, isInc, DAG);
10330   if (!isLegal)
10331     return false;
10332
10333   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10334   return true;
10335 }
10336
10337 /// getPostIndexedAddressParts - returns true by value, base pointer and
10338 /// offset pointer and addressing mode by reference if this node can be
10339 /// combined with a load / store to form a post-indexed load / store.
10340 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10341                                                    SDValue &Base,
10342                                                    SDValue &Offset,
10343                                                    ISD::MemIndexedMode &AM,
10344                                                    SelectionDAG &DAG) const {
10345   if (Subtarget->isThumb1Only())
10346     return false;
10347
10348   EVT VT;
10349   SDValue Ptr;
10350   bool isSEXTLoad = false;
10351   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10352     VT  = LD->getMemoryVT();
10353     Ptr = LD->getBasePtr();
10354     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10355   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10356     VT  = ST->getMemoryVT();
10357     Ptr = ST->getBasePtr();
10358   } else
10359     return false;
10360
10361   bool isInc;
10362   bool isLegal = false;
10363   if (Subtarget->isThumb2())
10364     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10365                                        isInc, DAG);
10366   else
10367     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10368                                         isInc, DAG);
10369   if (!isLegal)
10370     return false;
10371
10372   if (Ptr != Base) {
10373     // Swap base ptr and offset to catch more post-index load / store when
10374     // it's legal. In Thumb2 mode, offset must be an immediate.
10375     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10376         !Subtarget->isThumb2())
10377       std::swap(Base, Offset);
10378
10379     // Post-indexed load / store update the base pointer.
10380     if (Ptr != Base)
10381       return false;
10382   }
10383
10384   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10385   return true;
10386 }
10387
10388 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10389                                                       APInt &KnownZero,
10390                                                       APInt &KnownOne,
10391                                                       const SelectionDAG &DAG,
10392                                                       unsigned Depth) const {
10393   unsigned BitWidth = KnownOne.getBitWidth();
10394   KnownZero = KnownOne = APInt(BitWidth, 0);
10395   switch (Op.getOpcode()) {
10396   default: break;
10397   case ARMISD::ADDC:
10398   case ARMISD::ADDE:
10399   case ARMISD::SUBC:
10400   case ARMISD::SUBE:
10401     // These nodes' second result is a boolean
10402     if (Op.getResNo() == 0)
10403       break;
10404     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10405     break;
10406   case ARMISD::CMOV: {
10407     // Bits are known zero/one if known on the LHS and RHS.
10408     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10409     if (KnownZero == 0 && KnownOne == 0) return;
10410
10411     APInt KnownZeroRHS, KnownOneRHS;
10412     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10413     KnownZero &= KnownZeroRHS;
10414     KnownOne  &= KnownOneRHS;
10415     return;
10416   }
10417   case ISD::INTRINSIC_W_CHAIN: {
10418     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10419     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10420     switch (IntID) {
10421     default: return;
10422     case Intrinsic::arm_ldaex:
10423     case Intrinsic::arm_ldrex: {
10424       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10425       unsigned MemBits = VT.getScalarType().getSizeInBits();
10426       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10427       return;
10428     }
10429     }
10430   }
10431   }
10432 }
10433
10434 //===----------------------------------------------------------------------===//
10435 //                           ARM Inline Assembly Support
10436 //===----------------------------------------------------------------------===//
10437
10438 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10439   // Looking for "rev" which is V6+.
10440   if (!Subtarget->hasV6Ops())
10441     return false;
10442
10443   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10444   std::string AsmStr = IA->getAsmString();
10445   SmallVector<StringRef, 4> AsmPieces;
10446   SplitString(AsmStr, AsmPieces, ";\n");
10447
10448   switch (AsmPieces.size()) {
10449   default: return false;
10450   case 1:
10451     AsmStr = AsmPieces[0];
10452     AsmPieces.clear();
10453     SplitString(AsmStr, AsmPieces, " \t,");
10454
10455     // rev $0, $1
10456     if (AsmPieces.size() == 3 &&
10457         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10458         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10459       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10460       if (Ty && Ty->getBitWidth() == 32)
10461         return IntrinsicLowering::LowerToByteSwap(CI);
10462     }
10463     break;
10464   }
10465
10466   return false;
10467 }
10468
10469 /// getConstraintType - Given a constraint letter, return the type of
10470 /// constraint it is for this target.
10471 ARMTargetLowering::ConstraintType
10472 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10473   if (Constraint.size() == 1) {
10474     switch (Constraint[0]) {
10475     default:  break;
10476     case 'l': return C_RegisterClass;
10477     case 'w': return C_RegisterClass;
10478     case 'h': return C_RegisterClass;
10479     case 'x': return C_RegisterClass;
10480     case 't': return C_RegisterClass;
10481     case 'j': return C_Other; // Constant for movw.
10482       // An address with a single base register. Due to the way we
10483       // currently handle addresses it is the same as an 'r' memory constraint.
10484     case 'Q': return C_Memory;
10485     }
10486   } else if (Constraint.size() == 2) {
10487     switch (Constraint[0]) {
10488     default: break;
10489     // All 'U+' constraints are addresses.
10490     case 'U': return C_Memory;
10491     }
10492   }
10493   return TargetLowering::getConstraintType(Constraint);
10494 }
10495
10496 /// Examine constraint type and operand type and determine a weight value.
10497 /// This object must already have been set up with the operand type
10498 /// and the current alternative constraint selected.
10499 TargetLowering::ConstraintWeight
10500 ARMTargetLowering::getSingleConstraintMatchWeight(
10501     AsmOperandInfo &info, const char *constraint) const {
10502   ConstraintWeight weight = CW_Invalid;
10503   Value *CallOperandVal = info.CallOperandVal;
10504     // If we don't have a value, we can't do a match,
10505     // but allow it at the lowest weight.
10506   if (!CallOperandVal)
10507     return CW_Default;
10508   Type *type = CallOperandVal->getType();
10509   // Look at the constraint type.
10510   switch (*constraint) {
10511   default:
10512     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10513     break;
10514   case 'l':
10515     if (type->isIntegerTy()) {
10516       if (Subtarget->isThumb())
10517         weight = CW_SpecificReg;
10518       else
10519         weight = CW_Register;
10520     }
10521     break;
10522   case 'w':
10523     if (type->isFloatingPointTy())
10524       weight = CW_Register;
10525     break;
10526   }
10527   return weight;
10528 }
10529
10530 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10531 RCPair
10532 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10533                                                 MVT VT) const {
10534   if (Constraint.size() == 1) {
10535     // GCC ARM Constraint Letters
10536     switch (Constraint[0]) {
10537     case 'l': // Low regs or general regs.
10538       if (Subtarget->isThumb())
10539         return RCPair(0U, &ARM::tGPRRegClass);
10540       return RCPair(0U, &ARM::GPRRegClass);
10541     case 'h': // High regs or no regs.
10542       if (Subtarget->isThumb())
10543         return RCPair(0U, &ARM::hGPRRegClass);
10544       break;
10545     case 'r':
10546       if (Subtarget->isThumb1Only())
10547         return RCPair(0U, &ARM::tGPRRegClass);
10548       return RCPair(0U, &ARM::GPRRegClass);
10549     case 'w':
10550       if (VT == MVT::Other)
10551         break;
10552       if (VT == MVT::f32)
10553         return RCPair(0U, &ARM::SPRRegClass);
10554       if (VT.getSizeInBits() == 64)
10555         return RCPair(0U, &ARM::DPRRegClass);
10556       if (VT.getSizeInBits() == 128)
10557         return RCPair(0U, &ARM::QPRRegClass);
10558       break;
10559     case 'x':
10560       if (VT == MVT::Other)
10561         break;
10562       if (VT == MVT::f32)
10563         return RCPair(0U, &ARM::SPR_8RegClass);
10564       if (VT.getSizeInBits() == 64)
10565         return RCPair(0U, &ARM::DPR_8RegClass);
10566       if (VT.getSizeInBits() == 128)
10567         return RCPair(0U, &ARM::QPR_8RegClass);
10568       break;
10569     case 't':
10570       if (VT == MVT::f32)
10571         return RCPair(0U, &ARM::SPRRegClass);
10572       break;
10573     }
10574   }
10575   if (StringRef("{cc}").equals_lower(Constraint))
10576     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10577
10578   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10579 }
10580
10581 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10582 /// vector.  If it is invalid, don't add anything to Ops.
10583 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10584                                                      std::string &Constraint,
10585                                                      std::vector<SDValue>&Ops,
10586                                                      SelectionDAG &DAG) const {
10587   SDValue Result;
10588
10589   // Currently only support length 1 constraints.
10590   if (Constraint.length() != 1) return;
10591
10592   char ConstraintLetter = Constraint[0];
10593   switch (ConstraintLetter) {
10594   default: break;
10595   case 'j':
10596   case 'I': case 'J': case 'K': case 'L':
10597   case 'M': case 'N': case 'O':
10598     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10599     if (!C)
10600       return;
10601
10602     int64_t CVal64 = C->getSExtValue();
10603     int CVal = (int) CVal64;
10604     // None of these constraints allow values larger than 32 bits.  Check
10605     // that the value fits in an int.
10606     if (CVal != CVal64)
10607       return;
10608
10609     switch (ConstraintLetter) {
10610       case 'j':
10611         // Constant suitable for movw, must be between 0 and
10612         // 65535.
10613         if (Subtarget->hasV6T2Ops())
10614           if (CVal >= 0 && CVal <= 65535)
10615             break;
10616         return;
10617       case 'I':
10618         if (Subtarget->isThumb1Only()) {
10619           // This must be a constant between 0 and 255, for ADD
10620           // immediates.
10621           if (CVal >= 0 && CVal <= 255)
10622             break;
10623         } else if (Subtarget->isThumb2()) {
10624           // A constant that can be used as an immediate value in a
10625           // data-processing instruction.
10626           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10627             break;
10628         } else {
10629           // A constant that can be used as an immediate value in a
10630           // data-processing instruction.
10631           if (ARM_AM::getSOImmVal(CVal) != -1)
10632             break;
10633         }
10634         return;
10635
10636       case 'J':
10637         if (Subtarget->isThumb()) {  // FIXME thumb2
10638           // This must be a constant between -255 and -1, for negated ADD
10639           // immediates. This can be used in GCC with an "n" modifier that
10640           // prints the negated value, for use with SUB instructions. It is
10641           // not useful otherwise but is implemented for compatibility.
10642           if (CVal >= -255 && CVal <= -1)
10643             break;
10644         } else {
10645           // This must be a constant between -4095 and 4095. It is not clear
10646           // what this constraint is intended for. Implemented for
10647           // compatibility with GCC.
10648           if (CVal >= -4095 && CVal <= 4095)
10649             break;
10650         }
10651         return;
10652
10653       case 'K':
10654         if (Subtarget->isThumb1Only()) {
10655           // A 32-bit value where only one byte has a nonzero value. Exclude
10656           // zero to match GCC. This constraint is used by GCC internally for
10657           // constants that can be loaded with a move/shift combination.
10658           // It is not useful otherwise but is implemented for compatibility.
10659           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10660             break;
10661         } else if (Subtarget->isThumb2()) {
10662           // A constant whose bitwise inverse can be used as an immediate
10663           // value in a data-processing instruction. This can be used in GCC
10664           // with a "B" modifier that prints the inverted value, for use with
10665           // BIC and MVN instructions. It is not useful otherwise but is
10666           // implemented for compatibility.
10667           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10668             break;
10669         } else {
10670           // A constant whose bitwise inverse can be used as an immediate
10671           // value in a data-processing instruction. This can be used in GCC
10672           // with a "B" modifier that prints the inverted value, for use with
10673           // BIC and MVN instructions. It is not useful otherwise but is
10674           // implemented for compatibility.
10675           if (ARM_AM::getSOImmVal(~CVal) != -1)
10676             break;
10677         }
10678         return;
10679
10680       case 'L':
10681         if (Subtarget->isThumb1Only()) {
10682           // This must be a constant between -7 and 7,
10683           // for 3-operand ADD/SUB immediate instructions.
10684           if (CVal >= -7 && CVal < 7)
10685             break;
10686         } else if (Subtarget->isThumb2()) {
10687           // A constant whose negation can be used as an immediate value in a
10688           // data-processing instruction. This can be used in GCC with an "n"
10689           // modifier that prints the negated value, for use with SUB
10690           // instructions. It is not useful otherwise but is implemented for
10691           // compatibility.
10692           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10693             break;
10694         } else {
10695           // A constant whose negation can be used as an immediate value in a
10696           // data-processing instruction. This can be used in GCC with an "n"
10697           // modifier that prints the negated value, for use with SUB
10698           // instructions. It is not useful otherwise but is implemented for
10699           // compatibility.
10700           if (ARM_AM::getSOImmVal(-CVal) != -1)
10701             break;
10702         }
10703         return;
10704
10705       case 'M':
10706         if (Subtarget->isThumb()) { // FIXME thumb2
10707           // This must be a multiple of 4 between 0 and 1020, for
10708           // ADD sp + immediate.
10709           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10710             break;
10711         } else {
10712           // A power of two or a constant between 0 and 32.  This is used in
10713           // GCC for the shift amount on shifted register operands, but it is
10714           // useful in general for any shift amounts.
10715           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10716             break;
10717         }
10718         return;
10719
10720       case 'N':
10721         if (Subtarget->isThumb()) {  // FIXME thumb2
10722           // This must be a constant between 0 and 31, for shift amounts.
10723           if (CVal >= 0 && CVal <= 31)
10724             break;
10725         }
10726         return;
10727
10728       case 'O':
10729         if (Subtarget->isThumb()) {  // FIXME thumb2
10730           // This must be a multiple of 4 between -508 and 508, for
10731           // ADD/SUB sp = sp + immediate.
10732           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10733             break;
10734         }
10735         return;
10736     }
10737     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10738     break;
10739   }
10740
10741   if (Result.getNode()) {
10742     Ops.push_back(Result);
10743     return;
10744   }
10745   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10746 }
10747
10748 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10749   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10750   unsigned Opcode = Op->getOpcode();
10751   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10752          "Invalid opcode for Div/Rem lowering");
10753   bool isSigned = (Opcode == ISD::SDIVREM);
10754   EVT VT = Op->getValueType(0);
10755   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10756
10757   RTLIB::Libcall LC;
10758   switch (VT.getSimpleVT().SimpleTy) {
10759   default: llvm_unreachable("Unexpected request for libcall!");
10760   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10761   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10762   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10763   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10764   }
10765
10766   SDValue InChain = DAG.getEntryNode();
10767
10768   TargetLowering::ArgListTy Args;
10769   TargetLowering::ArgListEntry Entry;
10770   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10771     EVT ArgVT = Op->getOperand(i).getValueType();
10772     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10773     Entry.Node = Op->getOperand(i);
10774     Entry.Ty = ArgTy;
10775     Entry.isSExt = isSigned;
10776     Entry.isZExt = !isSigned;
10777     Args.push_back(Entry);
10778   }
10779
10780   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10781                                          getPointerTy());
10782
10783   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10784
10785   SDLoc dl(Op);
10786   TargetLowering::CallLoweringInfo CLI(DAG);
10787   CLI.setDebugLoc(dl).setChain(InChain)
10788     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10789     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10790
10791   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10792   return CallInfo.first;
10793 }
10794
10795 SDValue
10796 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10797   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10798   SDLoc DL(Op);
10799
10800   // Get the inputs.
10801   SDValue Chain = Op.getOperand(0);
10802   SDValue Size  = Op.getOperand(1);
10803
10804   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10805                               DAG.getConstant(2, MVT::i32));
10806
10807   SDValue Flag;
10808   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10809   Flag = Chain.getValue(1);
10810
10811   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10812   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10813
10814   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10815   Chain = NewSP.getValue(1);
10816
10817   SDValue Ops[2] = { NewSP, Chain };
10818   return DAG.getMergeValues(Ops, DL);
10819 }
10820
10821 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10822   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10823          "Unexpected type for custom-lowering FP_EXTEND");
10824
10825   RTLIB::Libcall LC;
10826   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10827
10828   SDValue SrcVal = Op.getOperand(0);
10829   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10830                      /*isSigned*/ false, SDLoc(Op)).first;
10831 }
10832
10833 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10834   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10835          Subtarget->isFPOnlySP() &&
10836          "Unexpected type for custom-lowering FP_ROUND");
10837
10838   RTLIB::Libcall LC;
10839   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10840
10841   SDValue SrcVal = Op.getOperand(0);
10842   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10843                      /*isSigned*/ false, SDLoc(Op)).first;
10844 }
10845
10846 bool
10847 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10848   // The ARM target isn't yet aware of offsets.
10849   return false;
10850 }
10851
10852 bool ARM::isBitFieldInvertedMask(unsigned v) {
10853   if (v == 0xffffffff)
10854     return false;
10855
10856   // there can be 1's on either or both "outsides", all the "inside"
10857   // bits must be 0's
10858   unsigned TO = CountTrailingOnes_32(v);
10859   unsigned LO = CountLeadingOnes_32(v);
10860   v = (v >> TO) << TO;
10861   v = (v << LO) >> LO;
10862   return v == 0;
10863 }
10864
10865 /// isFPImmLegal - Returns true if the target can instruction select the
10866 /// specified FP immediate natively. If false, the legalizer will
10867 /// materialize the FP immediate as a load from a constant pool.
10868 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10869   if (!Subtarget->hasVFP3())
10870     return false;
10871   if (VT == MVT::f32)
10872     return ARM_AM::getFP32Imm(Imm) != -1;
10873   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10874     return ARM_AM::getFP64Imm(Imm) != -1;
10875   return false;
10876 }
10877
10878 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10879 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10880 /// specified in the intrinsic calls.
10881 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10882                                            const CallInst &I,
10883                                            unsigned Intrinsic) const {
10884   switch (Intrinsic) {
10885   case Intrinsic::arm_neon_vld1:
10886   case Intrinsic::arm_neon_vld2:
10887   case Intrinsic::arm_neon_vld3:
10888   case Intrinsic::arm_neon_vld4:
10889   case Intrinsic::arm_neon_vld2lane:
10890   case Intrinsic::arm_neon_vld3lane:
10891   case Intrinsic::arm_neon_vld4lane: {
10892     Info.opc = ISD::INTRINSIC_W_CHAIN;
10893     // Conservatively set memVT to the entire set of vectors loaded.
10894     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10895     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10896     Info.ptrVal = I.getArgOperand(0);
10897     Info.offset = 0;
10898     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10899     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10900     Info.vol = false; // volatile loads with NEON intrinsics not supported
10901     Info.readMem = true;
10902     Info.writeMem = false;
10903     return true;
10904   }
10905   case Intrinsic::arm_neon_vst1:
10906   case Intrinsic::arm_neon_vst2:
10907   case Intrinsic::arm_neon_vst3:
10908   case Intrinsic::arm_neon_vst4:
10909   case Intrinsic::arm_neon_vst2lane:
10910   case Intrinsic::arm_neon_vst3lane:
10911   case Intrinsic::arm_neon_vst4lane: {
10912     Info.opc = ISD::INTRINSIC_VOID;
10913     // Conservatively set memVT to the entire set of vectors stored.
10914     unsigned NumElts = 0;
10915     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10916       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10917       if (!ArgTy->isVectorTy())
10918         break;
10919       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10920     }
10921     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10922     Info.ptrVal = I.getArgOperand(0);
10923     Info.offset = 0;
10924     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10925     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10926     Info.vol = false; // volatile stores with NEON intrinsics not supported
10927     Info.readMem = false;
10928     Info.writeMem = true;
10929     return true;
10930   }
10931   case Intrinsic::arm_ldaex:
10932   case Intrinsic::arm_ldrex: {
10933     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10934     Info.opc = ISD::INTRINSIC_W_CHAIN;
10935     Info.memVT = MVT::getVT(PtrTy->getElementType());
10936     Info.ptrVal = I.getArgOperand(0);
10937     Info.offset = 0;
10938     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10939     Info.vol = true;
10940     Info.readMem = true;
10941     Info.writeMem = false;
10942     return true;
10943   }
10944   case Intrinsic::arm_stlex:
10945   case Intrinsic::arm_strex: {
10946     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10947     Info.opc = ISD::INTRINSIC_W_CHAIN;
10948     Info.memVT = MVT::getVT(PtrTy->getElementType());
10949     Info.ptrVal = I.getArgOperand(1);
10950     Info.offset = 0;
10951     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10952     Info.vol = true;
10953     Info.readMem = false;
10954     Info.writeMem = true;
10955     return true;
10956   }
10957   case Intrinsic::arm_stlexd:
10958   case Intrinsic::arm_strexd: {
10959     Info.opc = ISD::INTRINSIC_W_CHAIN;
10960     Info.memVT = MVT::i64;
10961     Info.ptrVal = I.getArgOperand(2);
10962     Info.offset = 0;
10963     Info.align = 8;
10964     Info.vol = true;
10965     Info.readMem = false;
10966     Info.writeMem = true;
10967     return true;
10968   }
10969   case Intrinsic::arm_ldaexd:
10970   case Intrinsic::arm_ldrexd: {
10971     Info.opc = ISD::INTRINSIC_W_CHAIN;
10972     Info.memVT = MVT::i64;
10973     Info.ptrVal = I.getArgOperand(0);
10974     Info.offset = 0;
10975     Info.align = 8;
10976     Info.vol = true;
10977     Info.readMem = true;
10978     Info.writeMem = false;
10979     return true;
10980   }
10981   default:
10982     break;
10983   }
10984
10985   return false;
10986 }
10987
10988 /// \brief Returns true if it is beneficial to convert a load of a constant
10989 /// to just the constant itself.
10990 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10991                                                           Type *Ty) const {
10992   assert(Ty->isIntegerTy());
10993
10994   unsigned Bits = Ty->getPrimitiveSizeInBits();
10995   if (Bits == 0 || Bits > 32)
10996     return false;
10997   return true;
10998 }
10999
11000 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11001
11002 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11003                                         ARM_MB::MemBOpt Domain) const {
11004   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11005
11006   // First, if the target has no DMB, see what fallback we can use.
11007   if (!Subtarget->hasDataBarrier()) {
11008     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11009     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11010     // here.
11011     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11012       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11013       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11014                         Builder.getInt32(0), Builder.getInt32(7),
11015                         Builder.getInt32(10), Builder.getInt32(5)};
11016       return Builder.CreateCall(MCR, args);
11017     } else {
11018       // Instead of using barriers, atomic accesses on these subtargets use
11019       // libcalls.
11020       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11021     }
11022   } else {
11023     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11024     // Only a full system barrier exists in the M-class architectures.
11025     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11026     Constant *CDomain = Builder.getInt32(Domain);
11027     return Builder.CreateCall(DMB, CDomain);
11028   }
11029 }
11030
11031 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11032 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11033                                          AtomicOrdering Ord, bool IsStore,
11034                                          bool IsLoad) const {
11035   if (!getInsertFencesForAtomic())
11036     return nullptr;
11037
11038   switch (Ord) {
11039   case NotAtomic:
11040   case Unordered:
11041     llvm_unreachable("Invalid fence: unordered/non-atomic");
11042   case Monotonic:
11043   case Acquire:
11044     return nullptr; // Nothing to do
11045   case SequentiallyConsistent:
11046     if (!IsStore)
11047       return nullptr; // Nothing to do
11048     /*FALLTHROUGH*/
11049   case Release:
11050   case AcquireRelease:
11051     if (Subtarget->isSwift())
11052       return makeDMB(Builder, ARM_MB::ISHST);
11053     // FIXME: add a comment with a link to documentation justifying this.
11054     else
11055       return makeDMB(Builder, ARM_MB::ISH);
11056   }
11057   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11058 }
11059
11060 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11061                                           AtomicOrdering Ord, bool IsStore,
11062                                           bool IsLoad) const {
11063   if (!getInsertFencesForAtomic())
11064     return nullptr;
11065
11066   switch (Ord) {
11067   case NotAtomic:
11068   case Unordered:
11069     llvm_unreachable("Invalid fence: unordered/not-atomic");
11070   case Monotonic:
11071   case Release:
11072     return nullptr; // Nothing to do
11073   case Acquire:
11074   case AcquireRelease:
11075   case SequentiallyConsistent:
11076     return makeDMB(Builder, ARM_MB::ISH);
11077   }
11078   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11079 }
11080
11081 // Loads and stores less than 64-bits are already atomic; ones above that
11082 // are doomed anyway, so defer to the default libcall and blame the OS when
11083 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11084 // anything for those.
11085 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11086   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11087   return (Size == 64) && !Subtarget->isMClass();
11088 }
11089
11090 // Loads and stores less than 64-bits are already atomic; ones above that
11091 // are doomed anyway, so defer to the default libcall and blame the OS when
11092 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11093 // anything for those.
11094 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11095 // guarantee, see DDI0406C ARM architecture reference manual,
11096 // sections A8.8.72-74 LDRD)
11097 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11098   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11099   return (Size == 64) && !Subtarget->isMClass();
11100 }
11101
11102 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11103 // and up to 64 bits on the non-M profiles
11104 bool ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11105   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11106   return Size <= (Subtarget->isMClass() ? 32U : 64U);
11107 }
11108
11109 // This has so far only been implemented for MachO.
11110 bool ARMTargetLowering::useLoadStackGuardNode() const {
11111   return Subtarget->isTargetMachO();
11112 }
11113
11114 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11115                                                   unsigned &Cost) const {
11116   // If we do not have NEON, vector types are not natively supported.
11117   if (!Subtarget->hasNEON())
11118     return false;
11119
11120   // Floating point values and vector values map to the same register file.
11121   // Therefore, althought we could do a store extract of a vector type, this is
11122   // better to leave at float as we have more freedom in the addressing mode for
11123   // those.
11124   if (VectorTy->isFPOrFPVectorTy())
11125     return false;
11126
11127   // If the index is unknown at compile time, this is very expensive to lower
11128   // and it is not possible to combine the store with the extract.
11129   if (!isa<ConstantInt>(Idx))
11130     return false;
11131
11132   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11133   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11134   // We can do a store + vector extract on any vector that fits perfectly in a D
11135   // or Q register.
11136   if (BitWidth == 64 || BitWidth == 128) {
11137     Cost = 0;
11138     return true;
11139   }
11140   return false;
11141 }
11142
11143 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11144                                          AtomicOrdering Ord) const {
11145   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11146   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11147   bool IsAcquire = isAtLeastAcquire(Ord);
11148
11149   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11150   // intrinsic must return {i32, i32} and we have to recombine them into a
11151   // single i64 here.
11152   if (ValTy->getPrimitiveSizeInBits() == 64) {
11153     Intrinsic::ID Int =
11154         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11155     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11156
11157     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11158     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11159
11160     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11161     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11162     if (!Subtarget->isLittle())
11163       std::swap (Lo, Hi);
11164     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11165     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11166     return Builder.CreateOr(
11167         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11168   }
11169
11170   Type *Tys[] = { Addr->getType() };
11171   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11172   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11173
11174   return Builder.CreateTruncOrBitCast(
11175       Builder.CreateCall(Ldrex, Addr),
11176       cast<PointerType>(Addr->getType())->getElementType());
11177 }
11178
11179 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11180                                                Value *Addr,
11181                                                AtomicOrdering Ord) const {
11182   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11183   bool IsRelease = isAtLeastRelease(Ord);
11184
11185   // Since the intrinsics must have legal type, the i64 intrinsics take two
11186   // parameters: "i32, i32". We must marshal Val into the appropriate form
11187   // before the call.
11188   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11189     Intrinsic::ID Int =
11190         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11191     Function *Strex = Intrinsic::getDeclaration(M, Int);
11192     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11193
11194     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11195     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11196     if (!Subtarget->isLittle())
11197       std::swap (Lo, Hi);
11198     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11199     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11200   }
11201
11202   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11203   Type *Tys[] = { Addr->getType() };
11204   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11205
11206   return Builder.CreateCall2(
11207       Strex, Builder.CreateZExtOrBitCast(
11208                  Val, Strex->getFunctionType()->getParamType(0)),
11209       Addr);
11210 }
11211
11212 enum HABaseType {
11213   HA_UNKNOWN = 0,
11214   HA_FLOAT,
11215   HA_DOUBLE,
11216   HA_VECT64,
11217   HA_VECT128
11218 };
11219
11220 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11221                                    uint64_t &Members) {
11222   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11223     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11224       uint64_t SubMembers = 0;
11225       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11226         return false;
11227       Members += SubMembers;
11228     }
11229   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11230     uint64_t SubMembers = 0;
11231     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11232       return false;
11233     Members += SubMembers * AT->getNumElements();
11234   } else if (Ty->isFloatTy()) {
11235     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11236       return false;
11237     Members = 1;
11238     Base = HA_FLOAT;
11239   } else if (Ty->isDoubleTy()) {
11240     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11241       return false;
11242     Members = 1;
11243     Base = HA_DOUBLE;
11244   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11245     Members = 1;
11246     switch (Base) {
11247     case HA_FLOAT:
11248     case HA_DOUBLE:
11249       return false;
11250     case HA_VECT64:
11251       return VT->getBitWidth() == 64;
11252     case HA_VECT128:
11253       return VT->getBitWidth() == 128;
11254     case HA_UNKNOWN:
11255       switch (VT->getBitWidth()) {
11256       case 64:
11257         Base = HA_VECT64;
11258         return true;
11259       case 128:
11260         Base = HA_VECT128;
11261         return true;
11262       default:
11263         return false;
11264       }
11265     }
11266   }
11267
11268   return (Members > 0 && Members <= 4);
11269 }
11270
11271 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
11272 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11273     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11274   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11275       CallingConv::ARM_AAPCS_VFP)
11276     return false;
11277
11278   HABaseType Base = HA_UNKNOWN;
11279   uint64_t Members = 0;
11280   bool result = isHomogeneousAggregate(Ty, Base, Members);
11281   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());
11282   return result;
11283 }