Remove an argument-less call to getSubtargetImpl from TargetLoweringBase.
[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     setTargetDAGCombine(ISD::LOAD);
569
570     // It is legal to extload from v4i8 to v4i16 or v4i32.
571     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
572                   MVT::v4i16, MVT::v2i16,
573                   MVT::v2i32};
574     for (unsigned i = 0; i < 6; ++i) {
575       for (MVT VT : MVT::integer_vector_valuetypes()) {
576         setLoadExtAction(ISD::EXTLOAD, VT, Tys[i], Legal);
577         setLoadExtAction(ISD::ZEXTLOAD, VT, Tys[i], Legal);
578         setLoadExtAction(ISD::SEXTLOAD, VT, Tys[i], Legal);
579       }
580     }
581   }
582
583   // ARM and Thumb2 support UMLAL/SMLAL.
584   if (!Subtarget->isThumb1Only())
585     setTargetDAGCombine(ISD::ADDC);
586
587   if (Subtarget->isFPOnlySP()) {
588     // When targetting a floating-point unit with only single-precision
589     // operations, f64 is legal for the few double-precision instructions which
590     // are present However, no double-precision operations other than moves,
591     // loads and stores are provided by the hardware.
592     setOperationAction(ISD::FADD,       MVT::f64, Expand);
593     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
594     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
595     setOperationAction(ISD::FMA,        MVT::f64, Expand);
596     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
597     setOperationAction(ISD::FREM,       MVT::f64, Expand);
598     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
599     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
600     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
601     setOperationAction(ISD::FABS,       MVT::f64, Expand);
602     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
603     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
604     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
605     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
606     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
607     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
608     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
609     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
610     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
611     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
612     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
613     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
614     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
615     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
616     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
617     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
618     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
619   }
620
621   computeRegisterProperties(Subtarget->getRegisterInfo());
622
623   // ARM does not have floating-point extending loads.
624   for (MVT VT : MVT::fp_valuetypes()) {
625     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
626     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
627   }
628
629   // ... or truncating stores
630   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
631   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
632   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
633
634   // ARM does not have i1 sign extending load.
635   for (MVT VT : MVT::integer_valuetypes())
636     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
637
638   // ARM supports all 4 flavors of integer indexed load / store.
639   if (!Subtarget->isThumb1Only()) {
640     for (unsigned im = (unsigned)ISD::PRE_INC;
641          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
642       setIndexedLoadAction(im,  MVT::i1,  Legal);
643       setIndexedLoadAction(im,  MVT::i8,  Legal);
644       setIndexedLoadAction(im,  MVT::i16, Legal);
645       setIndexedLoadAction(im,  MVT::i32, Legal);
646       setIndexedStoreAction(im, MVT::i1,  Legal);
647       setIndexedStoreAction(im, MVT::i8,  Legal);
648       setIndexedStoreAction(im, MVT::i16, Legal);
649       setIndexedStoreAction(im, MVT::i32, Legal);
650     }
651   }
652
653   setOperationAction(ISD::SADDO, MVT::i32, Custom);
654   setOperationAction(ISD::UADDO, MVT::i32, Custom);
655   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
656   setOperationAction(ISD::USUBO, MVT::i32, Custom);
657
658   // i64 operation support.
659   setOperationAction(ISD::MUL,     MVT::i64, Expand);
660   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
661   if (Subtarget->isThumb1Only()) {
662     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
663     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
664   }
665   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
666       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
667     setOperationAction(ISD::MULHS, MVT::i32, Expand);
668
669   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
670   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
671   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
672   setOperationAction(ISD::SRL,       MVT::i64, Custom);
673   setOperationAction(ISD::SRA,       MVT::i64, Custom);
674
675   if (!Subtarget->isThumb1Only()) {
676     // FIXME: We should do this for Thumb1 as well.
677     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
678     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
679     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
680     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
681   }
682
683   // ARM does not have ROTL.
684   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
685   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
686   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
687   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
688     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
689
690   // These just redirect to CTTZ and CTLZ on ARM.
691   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
692   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
693
694   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
695
696   // Only ARMv6 has BSWAP.
697   if (!Subtarget->hasV6Ops())
698     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
699
700   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
701       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
702     // These are expanded into libcalls if the cpu doesn't have HW divider.
703     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
704     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
705   }
706
707   // FIXME: Also set divmod for SREM on EABI
708   setOperationAction(ISD::SREM,  MVT::i32, Expand);
709   setOperationAction(ISD::UREM,  MVT::i32, Expand);
710   // Register based DivRem for AEABI (RTABI 4.2)
711   if (Subtarget->isTargetAEABI()) {
712     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
713     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
714     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
715     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
716     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
717     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
718     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
719     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
720
721     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
722     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
723     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
724     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
725     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
726     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
727     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
728     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
729
730     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
731     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
732   } else {
733     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
734     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
735   }
736
737   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
738   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
739   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
740   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
741   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
742
743   setOperationAction(ISD::TRAP, MVT::Other, Legal);
744
745   // Use the default implementation.
746   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
747   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
748   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
749   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
750   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
751   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
752
753   if (!Subtarget->isTargetMachO()) {
754     // Non-MachO platforms may return values in these registers via the
755     // personality function.
756     setExceptionPointerRegister(ARM::R0);
757     setExceptionSelectorRegister(ARM::R1);
758   }
759
760   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
761     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
762   else
763     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
764
765   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
766   // the default expansion. If we are targeting a single threaded system,
767   // then set them all for expand so we can lower them later into their
768   // non-atomic form.
769   if (TM.Options.ThreadModel == ThreadModel::Single)
770     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
771   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
772     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
773     // to ldrex/strex loops already.
774     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
775
776     // On v8, we have particularly efficient implementations of atomic fences
777     // if they can be combined with nearby atomic loads and stores.
778     if (!Subtarget->hasV8Ops()) {
779       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
780       setInsertFencesForAtomic(true);
781     }
782   } else {
783     // If there's anything we can use as a barrier, go through custom lowering
784     // for ATOMIC_FENCE.
785     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
786                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
787
788     // Set them all for expansion, which will force libcalls.
789     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
790     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
791     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
792     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
793     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
794     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
795     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
796     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
801     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
802     // Unordered/Monotonic case.
803     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
804     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
805   }
806
807   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
808
809   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
810   if (!Subtarget->hasV6Ops()) {
811     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
812     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
813   }
814   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
815
816   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
817       !Subtarget->isThumb1Only()) {
818     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
819     // iff target supports vfp2.
820     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
821     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
822   }
823
824   // We want to custom lower some of our intrinsics.
825   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
826   if (Subtarget->isTargetDarwin()) {
827     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
828     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
829     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
830   }
831
832   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
833   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
834   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
835   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
836   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
837   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
838   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
839   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
840   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
841
842   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
843   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
844   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
845   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
846   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
847
848   // We don't support sin/cos/fmod/copysign/pow
849   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
850   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
851   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
852   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
853   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
854   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
855   setOperationAction(ISD::FREM,      MVT::f64, Expand);
856   setOperationAction(ISD::FREM,      MVT::f32, Expand);
857   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
858       !Subtarget->isThumb1Only()) {
859     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
860     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
861   }
862   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
863   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
864
865   if (!Subtarget->hasVFP4()) {
866     setOperationAction(ISD::FMA, MVT::f64, Expand);
867     setOperationAction(ISD::FMA, MVT::f32, Expand);
868   }
869
870   // Various VFP goodness
871   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
872     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
873     if (Subtarget->hasVFP2()) {
874       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
875       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
876       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
877       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
878     }
879
880     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
881     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
882       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
883       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
884     }
885
886     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
887     if (!Subtarget->hasFP16()) {
888       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
889       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
890     }
891   }
892
893   // Combine sin / cos into one node or libcall if possible.
894   if (Subtarget->hasSinCos()) {
895     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
896     setLibcallName(RTLIB::SINCOS_F64, "sincos");
897     if (Subtarget->getTargetTriple().isiOS()) {
898       // For iOS, we don't want to the normal expansion of a libcall to
899       // sincos. We want to issue a libcall to __sincos_stret.
900       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
901       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
902     }
903   }
904
905   // FP-ARMv8 implements a lot of rounding-like FP operations.
906   if (Subtarget->hasFPARMv8()) {
907     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
908     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
909     setOperationAction(ISD::FROUND, MVT::f32, Legal);
910     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
911     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
912     setOperationAction(ISD::FRINT, MVT::f32, Legal);
913     if (!Subtarget->isFPOnlySP()) {
914       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
915       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
916       setOperationAction(ISD::FROUND, MVT::f64, Legal);
917       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
918       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
919       setOperationAction(ISD::FRINT, MVT::f64, Legal);
920     }
921   }
922   // We have target-specific dag combine patterns for the following nodes:
923   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
924   setTargetDAGCombine(ISD::ADD);
925   setTargetDAGCombine(ISD::SUB);
926   setTargetDAGCombine(ISD::MUL);
927   setTargetDAGCombine(ISD::AND);
928   setTargetDAGCombine(ISD::OR);
929   setTargetDAGCombine(ISD::XOR);
930
931   if (Subtarget->hasV6Ops())
932     setTargetDAGCombine(ISD::SRL);
933
934   setStackPointerRegisterToSaveRestore(ARM::SP);
935
936   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
937       !Subtarget->hasVFP2())
938     setSchedulingPreference(Sched::RegPressure);
939   else
940     setSchedulingPreference(Sched::Hybrid);
941
942   //// temporary - rewrite interface to use type
943   MaxStoresPerMemset = 8;
944   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
945   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
946   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
947   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
948   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
949
950   // On ARM arguments smaller than 4 bytes are extended, so all arguments
951   // are at least 4 bytes aligned.
952   setMinStackArgumentAlignment(4);
953
954   // Prefer likely predicted branches to selects on out-of-order cores.
955   PredictableSelectIsExpensive = Subtarget->isLikeA9();
956
957   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
958 }
959
960 // FIXME: It might make sense to define the representative register class as the
961 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
962 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
963 // SPR's representative would be DPR_VFP2. This should work well if register
964 // pressure tracking were modified such that a register use would increment the
965 // pressure of the register class's representative and all of it's super
966 // classes' representatives transitively. We have not implemented this because
967 // of the difficulty prior to coalescing of modeling operand register classes
968 // due to the common occurrence of cross class copies and subregister insertions
969 // and extractions.
970 std::pair<const TargetRegisterClass *, uint8_t>
971 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
972                                            MVT VT) const {
973   const TargetRegisterClass *RRC = nullptr;
974   uint8_t Cost = 1;
975   switch (VT.SimpleTy) {
976   default:
977     return TargetLowering::findRepresentativeClass(TRI, VT);
978   // Use DPR as representative register class for all floating point
979   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
980   // the cost is 1 for both f32 and f64.
981   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
982   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
983     RRC = &ARM::DPRRegClass;
984     // When NEON is used for SP, only half of the register file is available
985     // because operations that define both SP and DP results will be constrained
986     // to the VFP2 class (D0-D15). We currently model this constraint prior to
987     // coalescing by double-counting the SP regs. See the FIXME above.
988     if (Subtarget->useNEONForSinglePrecisionFP())
989       Cost = 2;
990     break;
991   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
992   case MVT::v4f32: case MVT::v2f64:
993     RRC = &ARM::DPRRegClass;
994     Cost = 2;
995     break;
996   case MVT::v4i64:
997     RRC = &ARM::DPRRegClass;
998     Cost = 4;
999     break;
1000   case MVT::v8i64:
1001     RRC = &ARM::DPRRegClass;
1002     Cost = 8;
1003     break;
1004   }
1005   return std::make_pair(RRC, Cost);
1006 }
1007
1008 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1009   switch (Opcode) {
1010   default: return nullptr;
1011   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1012   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1013   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1014   case ARMISD::CALL:          return "ARMISD::CALL";
1015   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1016   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1017   case ARMISD::tCALL:         return "ARMISD::tCALL";
1018   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1019   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1020   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1021   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1022   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1023   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1024   case ARMISD::CMP:           return "ARMISD::CMP";
1025   case ARMISD::CMN:           return "ARMISD::CMN";
1026   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1027   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1028   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1029   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1030   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1031
1032   case ARMISD::CMOV:          return "ARMISD::CMOV";
1033
1034   case ARMISD::RBIT:          return "ARMISD::RBIT";
1035
1036   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1037   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1038   case ARMISD::SITOF:         return "ARMISD::SITOF";
1039   case ARMISD::UITOF:         return "ARMISD::UITOF";
1040
1041   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1042   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1043   case ARMISD::RRX:           return "ARMISD::RRX";
1044
1045   case ARMISD::ADDC:          return "ARMISD::ADDC";
1046   case ARMISD::ADDE:          return "ARMISD::ADDE";
1047   case ARMISD::SUBC:          return "ARMISD::SUBC";
1048   case ARMISD::SUBE:          return "ARMISD::SUBE";
1049
1050   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1051   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1052
1053   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1054   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1055
1056   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1057
1058   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1059
1060   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1061
1062   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1063
1064   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1065
1066   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1067
1068   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1069   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1070   case ARMISD::VCGE:          return "ARMISD::VCGE";
1071   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1072   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1073   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1074   case ARMISD::VCGT:          return "ARMISD::VCGT";
1075   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1076   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1077   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1078   case ARMISD::VTST:          return "ARMISD::VTST";
1079
1080   case ARMISD::VSHL:          return "ARMISD::VSHL";
1081   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1082   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1083   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1084   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1085   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1086   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1087   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1088   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1089   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1090   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1091   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1092   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1093   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1094   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1095   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1096   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1097   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1098   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1099   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1100   case ARMISD::VDUP:          return "ARMISD::VDUP";
1101   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1102   case ARMISD::VEXT:          return "ARMISD::VEXT";
1103   case ARMISD::VREV64:        return "ARMISD::VREV64";
1104   case ARMISD::VREV32:        return "ARMISD::VREV32";
1105   case ARMISD::VREV16:        return "ARMISD::VREV16";
1106   case ARMISD::VZIP:          return "ARMISD::VZIP";
1107   case ARMISD::VUZP:          return "ARMISD::VUZP";
1108   case ARMISD::VTRN:          return "ARMISD::VTRN";
1109   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1110   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1111   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1112   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1113   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1114   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1115   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1116   case ARMISD::FMAX:          return "ARMISD::FMAX";
1117   case ARMISD::FMIN:          return "ARMISD::FMIN";
1118   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1119   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1120   case ARMISD::BFI:           return "ARMISD::BFI";
1121   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1122   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1123   case ARMISD::VBSL:          return "ARMISD::VBSL";
1124   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1125   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1126   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1127   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1128   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1129   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1130   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1131   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1132   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1133   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1134   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1135   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1136   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1137   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1138   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1139   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1140   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1141   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1142   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1143   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1144   }
1145 }
1146
1147 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1148   if (!VT.isVector()) return getPointerTy();
1149   return VT.changeVectorElementTypeToInteger();
1150 }
1151
1152 /// getRegClassFor - Return the register class that should be used for the
1153 /// specified value type.
1154 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1155   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1156   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1157   // load / store 4 to 8 consecutive D registers.
1158   if (Subtarget->hasNEON()) {
1159     if (VT == MVT::v4i64)
1160       return &ARM::QQPRRegClass;
1161     if (VT == MVT::v8i64)
1162       return &ARM::QQQQPRRegClass;
1163   }
1164   return TargetLowering::getRegClassFor(VT);
1165 }
1166
1167 // Create a fast isel object.
1168 FastISel *
1169 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1170                                   const TargetLibraryInfo *libInfo) const {
1171   return ARM::createFastISel(funcInfo, libInfo);
1172 }
1173
1174 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1175   unsigned NumVals = N->getNumValues();
1176   if (!NumVals)
1177     return Sched::RegPressure;
1178
1179   for (unsigned i = 0; i != NumVals; ++i) {
1180     EVT VT = N->getValueType(i);
1181     if (VT == MVT::Glue || VT == MVT::Other)
1182       continue;
1183     if (VT.isFloatingPoint() || VT.isVector())
1184       return Sched::ILP;
1185   }
1186
1187   if (!N->isMachineOpcode())
1188     return Sched::RegPressure;
1189
1190   // Load are scheduled for latency even if there instruction itinerary
1191   // is not available.
1192   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1193   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1194
1195   if (MCID.getNumDefs() == 0)
1196     return Sched::RegPressure;
1197   if (!Itins->isEmpty() &&
1198       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1199     return Sched::ILP;
1200
1201   return Sched::RegPressure;
1202 }
1203
1204 //===----------------------------------------------------------------------===//
1205 // Lowering Code
1206 //===----------------------------------------------------------------------===//
1207
1208 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1209 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1210   switch (CC) {
1211   default: llvm_unreachable("Unknown condition code!");
1212   case ISD::SETNE:  return ARMCC::NE;
1213   case ISD::SETEQ:  return ARMCC::EQ;
1214   case ISD::SETGT:  return ARMCC::GT;
1215   case ISD::SETGE:  return ARMCC::GE;
1216   case ISD::SETLT:  return ARMCC::LT;
1217   case ISD::SETLE:  return ARMCC::LE;
1218   case ISD::SETUGT: return ARMCC::HI;
1219   case ISD::SETUGE: return ARMCC::HS;
1220   case ISD::SETULT: return ARMCC::LO;
1221   case ISD::SETULE: return ARMCC::LS;
1222   }
1223 }
1224
1225 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1226 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1227                         ARMCC::CondCodes &CondCode2) {
1228   CondCode2 = ARMCC::AL;
1229   switch (CC) {
1230   default: llvm_unreachable("Unknown FP condition!");
1231   case ISD::SETEQ:
1232   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1233   case ISD::SETGT:
1234   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1235   case ISD::SETGE:
1236   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1237   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1238   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1239   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1240   case ISD::SETO:   CondCode = ARMCC::VC; break;
1241   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1242   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1243   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1244   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1245   case ISD::SETLT:
1246   case ISD::SETULT: CondCode = ARMCC::LT; break;
1247   case ISD::SETLE:
1248   case ISD::SETULE: CondCode = ARMCC::LE; break;
1249   case ISD::SETNE:
1250   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1251   }
1252 }
1253
1254 //===----------------------------------------------------------------------===//
1255 //                      Calling Convention Implementation
1256 //===----------------------------------------------------------------------===//
1257
1258 #include "ARMGenCallingConv.inc"
1259
1260 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1261 /// account presence of floating point hardware and calling convention
1262 /// limitations, such as support for variadic functions.
1263 CallingConv::ID
1264 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1265                                            bool isVarArg) const {
1266   switch (CC) {
1267   default:
1268     llvm_unreachable("Unsupported calling convention");
1269   case CallingConv::ARM_AAPCS:
1270   case CallingConv::ARM_APCS:
1271   case CallingConv::GHC:
1272     return CC;
1273   case CallingConv::ARM_AAPCS_VFP:
1274     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1275   case CallingConv::C:
1276     if (!Subtarget->isAAPCS_ABI())
1277       return CallingConv::ARM_APCS;
1278     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1279              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1280              !isVarArg)
1281       return CallingConv::ARM_AAPCS_VFP;
1282     else
1283       return CallingConv::ARM_AAPCS;
1284   case CallingConv::Fast:
1285     if (!Subtarget->isAAPCS_ABI()) {
1286       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1287         return CallingConv::Fast;
1288       return CallingConv::ARM_APCS;
1289     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1290       return CallingConv::ARM_AAPCS_VFP;
1291     else
1292       return CallingConv::ARM_AAPCS;
1293   }
1294 }
1295
1296 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1297 /// CallingConvention.
1298 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1299                                                  bool Return,
1300                                                  bool isVarArg) const {
1301   switch (getEffectiveCallingConv(CC, isVarArg)) {
1302   default:
1303     llvm_unreachable("Unsupported calling convention");
1304   case CallingConv::ARM_APCS:
1305     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1306   case CallingConv::ARM_AAPCS:
1307     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1308   case CallingConv::ARM_AAPCS_VFP:
1309     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1310   case CallingConv::Fast:
1311     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1312   case CallingConv::GHC:
1313     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1314   }
1315 }
1316
1317 /// LowerCallResult - Lower the result values of a call into the
1318 /// appropriate copies out of appropriate physical registers.
1319 SDValue
1320 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1321                                    CallingConv::ID CallConv, bool isVarArg,
1322                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1323                                    SDLoc dl, SelectionDAG &DAG,
1324                                    SmallVectorImpl<SDValue> &InVals,
1325                                    bool isThisReturn, SDValue ThisVal) const {
1326
1327   // Assign locations to each value returned by this call.
1328   SmallVector<CCValAssign, 16> RVLocs;
1329   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1330                     *DAG.getContext(), Call);
1331   CCInfo.AnalyzeCallResult(Ins,
1332                            CCAssignFnForNode(CallConv, /* Return*/ true,
1333                                              isVarArg));
1334
1335   // Copy all of the result registers out of their specified physreg.
1336   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1337     CCValAssign VA = RVLocs[i];
1338
1339     // Pass 'this' value directly from the argument to return value, to avoid
1340     // reg unit interference
1341     if (i == 0 && isThisReturn) {
1342       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1343              "unexpected return calling convention register assignment");
1344       InVals.push_back(ThisVal);
1345       continue;
1346     }
1347
1348     SDValue Val;
1349     if (VA.needsCustom()) {
1350       // Handle f64 or half of a v2f64.
1351       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1352                                       InFlag);
1353       Chain = Lo.getValue(1);
1354       InFlag = Lo.getValue(2);
1355       VA = RVLocs[++i]; // skip ahead to next loc
1356       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1357                                       InFlag);
1358       Chain = Hi.getValue(1);
1359       InFlag = Hi.getValue(2);
1360       if (!Subtarget->isLittle())
1361         std::swap (Lo, Hi);
1362       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1363
1364       if (VA.getLocVT() == MVT::v2f64) {
1365         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1366         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1367                           DAG.getConstant(0, MVT::i32));
1368
1369         VA = RVLocs[++i]; // skip ahead to next loc
1370         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1371         Chain = Lo.getValue(1);
1372         InFlag = Lo.getValue(2);
1373         VA = RVLocs[++i]; // skip ahead to next loc
1374         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1375         Chain = Hi.getValue(1);
1376         InFlag = Hi.getValue(2);
1377         if (!Subtarget->isLittle())
1378           std::swap (Lo, Hi);
1379         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1380         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1381                           DAG.getConstant(1, MVT::i32));
1382       }
1383     } else {
1384       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1385                                InFlag);
1386       Chain = Val.getValue(1);
1387       InFlag = Val.getValue(2);
1388     }
1389
1390     switch (VA.getLocInfo()) {
1391     default: llvm_unreachable("Unknown loc info!");
1392     case CCValAssign::Full: break;
1393     case CCValAssign::BCvt:
1394       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1395       break;
1396     }
1397
1398     InVals.push_back(Val);
1399   }
1400
1401   return Chain;
1402 }
1403
1404 /// LowerMemOpCallTo - Store the argument to the stack.
1405 SDValue
1406 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1407                                     SDValue StackPtr, SDValue Arg,
1408                                     SDLoc dl, SelectionDAG &DAG,
1409                                     const CCValAssign &VA,
1410                                     ISD::ArgFlagsTy Flags) const {
1411   unsigned LocMemOffset = VA.getLocMemOffset();
1412   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1413   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1414   return DAG.getStore(Chain, dl, Arg, PtrOff,
1415                       MachinePointerInfo::getStack(LocMemOffset),
1416                       false, false, 0);
1417 }
1418
1419 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1420                                          SDValue Chain, SDValue &Arg,
1421                                          RegsToPassVector &RegsToPass,
1422                                          CCValAssign &VA, CCValAssign &NextVA,
1423                                          SDValue &StackPtr,
1424                                          SmallVectorImpl<SDValue> &MemOpChains,
1425                                          ISD::ArgFlagsTy Flags) const {
1426
1427   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1428                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1429   unsigned id = Subtarget->isLittle() ? 0 : 1;
1430   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1431
1432   if (NextVA.isRegLoc())
1433     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1434   else {
1435     assert(NextVA.isMemLoc());
1436     if (!StackPtr.getNode())
1437       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1438
1439     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1440                                            dl, DAG, NextVA,
1441                                            Flags));
1442   }
1443 }
1444
1445 /// LowerCall - Lowering a call into a callseq_start <-
1446 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1447 /// nodes.
1448 SDValue
1449 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1450                              SmallVectorImpl<SDValue> &InVals) const {
1451   SelectionDAG &DAG                     = CLI.DAG;
1452   SDLoc &dl                          = CLI.DL;
1453   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1454   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1455   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1456   SDValue Chain                         = CLI.Chain;
1457   SDValue Callee                        = CLI.Callee;
1458   bool &isTailCall                      = CLI.IsTailCall;
1459   CallingConv::ID CallConv              = CLI.CallConv;
1460   bool doesNotRet                       = CLI.DoesNotReturn;
1461   bool isVarArg                         = CLI.IsVarArg;
1462
1463   MachineFunction &MF = DAG.getMachineFunction();
1464   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1465   bool isThisReturn   = false;
1466   bool isSibCall      = false;
1467
1468   // Disable tail calls if they're not supported.
1469   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1470     isTailCall = false;
1471
1472   if (isTailCall) {
1473     // Check if it's really possible to do a tail call.
1474     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1475                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1476                                                    Outs, OutVals, Ins, DAG);
1477     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1478       report_fatal_error("failed to perform tail call elimination on a call "
1479                          "site marked musttail");
1480     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1481     // detected sibcalls.
1482     if (isTailCall) {
1483       ++NumTailCalls;
1484       isSibCall = true;
1485     }
1486   }
1487
1488   // Analyze operands of the call, assigning locations to each operand.
1489   SmallVector<CCValAssign, 16> ArgLocs;
1490   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1491                     *DAG.getContext(), Call);
1492   CCInfo.AnalyzeCallOperands(Outs,
1493                              CCAssignFnForNode(CallConv, /* Return*/ false,
1494                                                isVarArg));
1495
1496   // Get a count of how many bytes are to be pushed on the stack.
1497   unsigned NumBytes = CCInfo.getNextStackOffset();
1498
1499   // For tail calls, memory operands are available in our caller's stack.
1500   if (isSibCall)
1501     NumBytes = 0;
1502
1503   // Adjust the stack pointer for the new arguments...
1504   // These operations are automatically eliminated by the prolog/epilog pass
1505   if (!isSibCall)
1506     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1507                                  dl);
1508
1509   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1510
1511   RegsToPassVector RegsToPass;
1512   SmallVector<SDValue, 8> MemOpChains;
1513
1514   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1515   // of tail call optimization, arguments are handled later.
1516   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1517        i != e;
1518        ++i, ++realArgIdx) {
1519     CCValAssign &VA = ArgLocs[i];
1520     SDValue Arg = OutVals[realArgIdx];
1521     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1522     bool isByVal = Flags.isByVal();
1523
1524     // Promote the value if needed.
1525     switch (VA.getLocInfo()) {
1526     default: llvm_unreachable("Unknown loc info!");
1527     case CCValAssign::Full: break;
1528     case CCValAssign::SExt:
1529       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1530       break;
1531     case CCValAssign::ZExt:
1532       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1533       break;
1534     case CCValAssign::AExt:
1535       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1536       break;
1537     case CCValAssign::BCvt:
1538       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1539       break;
1540     }
1541
1542     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1543     if (VA.needsCustom()) {
1544       if (VA.getLocVT() == MVT::v2f64) {
1545         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1546                                   DAG.getConstant(0, MVT::i32));
1547         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1548                                   DAG.getConstant(1, MVT::i32));
1549
1550         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1551                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1552
1553         VA = ArgLocs[++i]; // skip ahead to next loc
1554         if (VA.isRegLoc()) {
1555           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1556                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1557         } else {
1558           assert(VA.isMemLoc());
1559
1560           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1561                                                  dl, DAG, VA, Flags));
1562         }
1563       } else {
1564         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1565                          StackPtr, MemOpChains, Flags);
1566       }
1567     } else if (VA.isRegLoc()) {
1568       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1569         assert(VA.getLocVT() == MVT::i32 &&
1570                "unexpected calling convention register assignment");
1571         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1572                "unexpected use of 'returned'");
1573         isThisReturn = true;
1574       }
1575       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1576     } else if (isByVal) {
1577       assert(VA.isMemLoc());
1578       unsigned offset = 0;
1579
1580       // True if this byval aggregate will be split between registers
1581       // and memory.
1582       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1583       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1584
1585       if (CurByValIdx < ByValArgsCount) {
1586
1587         unsigned RegBegin, RegEnd;
1588         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1589
1590         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1591         unsigned int i, j;
1592         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1593           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1594           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1595           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1596                                      MachinePointerInfo(),
1597                                      false, false, false,
1598                                      DAG.InferPtrAlignment(AddArg));
1599           MemOpChains.push_back(Load.getValue(1));
1600           RegsToPass.push_back(std::make_pair(j, Load));
1601         }
1602
1603         // If parameter size outsides register area, "offset" value
1604         // helps us to calculate stack slot for remained part properly.
1605         offset = RegEnd - RegBegin;
1606
1607         CCInfo.nextInRegsParam();
1608       }
1609
1610       if (Flags.getByValSize() > 4*offset) {
1611         unsigned LocMemOffset = VA.getLocMemOffset();
1612         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1613         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1614                                   StkPtrOff);
1615         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1616         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1617         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1618                                            MVT::i32);
1619         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1620
1621         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1622         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1623         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1624                                           Ops));
1625       }
1626     } else if (!isSibCall) {
1627       assert(VA.isMemLoc());
1628
1629       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1630                                              dl, DAG, VA, Flags));
1631     }
1632   }
1633
1634   if (!MemOpChains.empty())
1635     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1636
1637   // Build a sequence of copy-to-reg nodes chained together with token chain
1638   // and flag operands which copy the outgoing args into the appropriate regs.
1639   SDValue InFlag;
1640   // Tail call byval lowering might overwrite argument registers so in case of
1641   // tail call optimization the copies to registers are lowered later.
1642   if (!isTailCall)
1643     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1644       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1645                                RegsToPass[i].second, InFlag);
1646       InFlag = Chain.getValue(1);
1647     }
1648
1649   // For tail calls lower the arguments to the 'real' stack slot.
1650   if (isTailCall) {
1651     // Force all the incoming stack arguments to be loaded from the stack
1652     // before any new outgoing arguments are stored to the stack, because the
1653     // outgoing stack slots may alias the incoming argument stack slots, and
1654     // the alias isn't otherwise explicit. This is slightly more conservative
1655     // than necessary, because it means that each store effectively depends
1656     // on every argument instead of just those arguments it would clobber.
1657
1658     // Do not flag preceding copytoreg stuff together with the following stuff.
1659     InFlag = SDValue();
1660     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1661       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1662                                RegsToPass[i].second, InFlag);
1663       InFlag = Chain.getValue(1);
1664     }
1665     InFlag = SDValue();
1666   }
1667
1668   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1669   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1670   // node so that legalize doesn't hack it.
1671   bool isDirect = false;
1672   bool isARMFunc = false;
1673   bool isLocalARMFunc = false;
1674   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1675
1676   if (EnableARMLongCalls) {
1677     assert((Subtarget->isTargetWindows() ||
1678             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1679            "long-calls with non-static relocation model!");
1680     // Handle a global address or an external symbol. If it's not one of
1681     // those, the target's already in a register, so we don't need to do
1682     // anything extra.
1683     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1684       const GlobalValue *GV = G->getGlobal();
1685       // Create a constant pool entry for the callee address
1686       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1687       ARMConstantPoolValue *CPV =
1688         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1689
1690       // Get the address of the callee into a register
1691       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1692       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1693       Callee = DAG.getLoad(getPointerTy(), dl,
1694                            DAG.getEntryNode(), CPAddr,
1695                            MachinePointerInfo::getConstantPool(),
1696                            false, false, false, 0);
1697     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1698       const char *Sym = S->getSymbol();
1699
1700       // Create a constant pool entry for the callee address
1701       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1702       ARMConstantPoolValue *CPV =
1703         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1704                                       ARMPCLabelIndex, 0);
1705       // Get the address of the callee into a register
1706       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1707       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1708       Callee = DAG.getLoad(getPointerTy(), dl,
1709                            DAG.getEntryNode(), CPAddr,
1710                            MachinePointerInfo::getConstantPool(),
1711                            false, false, false, 0);
1712     }
1713   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1714     const GlobalValue *GV = G->getGlobal();
1715     isDirect = true;
1716     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1717     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1718                    getTargetMachine().getRelocationModel() != Reloc::Static;
1719     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1720     // ARM call to a local ARM function is predicable.
1721     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1722     // tBX takes a register source operand.
1723     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1724       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1725       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1726                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1727                                                       0, ARMII::MO_NONLAZY));
1728       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1729                            MachinePointerInfo::getGOT(), false, false, true, 0);
1730     } else if (Subtarget->isTargetCOFF()) {
1731       assert(Subtarget->isTargetWindows() &&
1732              "Windows is the only supported COFF target");
1733       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1734                                  ? ARMII::MO_DLLIMPORT
1735                                  : ARMII::MO_NO_FLAG;
1736       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1737                                           TargetFlags);
1738       if (GV->hasDLLImportStorageClass())
1739         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1740                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1741                                          Callee), MachinePointerInfo::getGOT(),
1742                              false, false, false, 0);
1743     } else {
1744       // On ELF targets for PIC code, direct calls should go through the PLT
1745       unsigned OpFlags = 0;
1746       if (Subtarget->isTargetELF() &&
1747           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1748         OpFlags = ARMII::MO_PLT;
1749       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1750     }
1751   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1752     isDirect = true;
1753     bool isStub = Subtarget->isTargetMachO() &&
1754                   getTargetMachine().getRelocationModel() != Reloc::Static;
1755     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1756     // tBX takes a register source operand.
1757     const char *Sym = S->getSymbol();
1758     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1759       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1760       ARMConstantPoolValue *CPV =
1761         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1762                                       ARMPCLabelIndex, 4);
1763       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1764       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1765       Callee = DAG.getLoad(getPointerTy(), dl,
1766                            DAG.getEntryNode(), CPAddr,
1767                            MachinePointerInfo::getConstantPool(),
1768                            false, false, false, 0);
1769       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1770       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1771                            getPointerTy(), Callee, PICLabel);
1772     } else {
1773       unsigned OpFlags = 0;
1774       // On ELF targets for PIC code, direct calls should go through the PLT
1775       if (Subtarget->isTargetELF() &&
1776                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1777         OpFlags = ARMII::MO_PLT;
1778       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1779     }
1780   }
1781
1782   // FIXME: handle tail calls differently.
1783   unsigned CallOpc;
1784   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1785   if (Subtarget->isThumb()) {
1786     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1787       CallOpc = ARMISD::CALL_NOLINK;
1788     else
1789       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1790   } else {
1791     if (!isDirect && !Subtarget->hasV5TOps())
1792       CallOpc = ARMISD::CALL_NOLINK;
1793     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1794                // Emit regular call when code size is the priority
1795                !HasMinSizeAttr)
1796       // "mov lr, pc; b _foo" to avoid confusing the RSP
1797       CallOpc = ARMISD::CALL_NOLINK;
1798     else
1799       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1800   }
1801
1802   std::vector<SDValue> Ops;
1803   Ops.push_back(Chain);
1804   Ops.push_back(Callee);
1805
1806   // Add argument registers to the end of the list so that they are known live
1807   // into the call.
1808   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1809     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1810                                   RegsToPass[i].second.getValueType()));
1811
1812   // Add a register mask operand representing the call-preserved registers.
1813   if (!isTailCall) {
1814     const uint32_t *Mask;
1815     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1816     if (isThisReturn) {
1817       // For 'this' returns, use the R0-preserving mask if applicable
1818       Mask = ARI->getThisReturnPreservedMask(CallConv);
1819       if (!Mask) {
1820         // Set isThisReturn to false if the calling convention is not one that
1821         // allows 'returned' to be modeled in this way, so LowerCallResult does
1822         // not try to pass 'this' straight through
1823         isThisReturn = false;
1824         Mask = ARI->getCallPreservedMask(CallConv);
1825       }
1826     } else
1827       Mask = ARI->getCallPreservedMask(CallConv);
1828
1829     assert(Mask && "Missing call preserved mask for calling convention");
1830     Ops.push_back(DAG.getRegisterMask(Mask));
1831   }
1832
1833   if (InFlag.getNode())
1834     Ops.push_back(InFlag);
1835
1836   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1837   if (isTailCall)
1838     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1839
1840   // Returns a chain and a flag for retval copy to use.
1841   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1842   InFlag = Chain.getValue(1);
1843
1844   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1845                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1846   if (!Ins.empty())
1847     InFlag = Chain.getValue(1);
1848
1849   // Handle result values, copying them out of physregs into vregs that we
1850   // return.
1851   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1852                          InVals, isThisReturn,
1853                          isThisReturn ? OutVals[0] : SDValue());
1854 }
1855
1856 /// HandleByVal - Every parameter *after* a byval parameter is passed
1857 /// on the stack.  Remember the next parameter register to allocate,
1858 /// and then confiscate the rest of the parameter registers to insure
1859 /// this.
1860 void
1861 ARMTargetLowering::HandleByVal(
1862     CCState *State, unsigned &size, unsigned Align) const {
1863   unsigned reg = State->AllocateReg(GPRArgRegs);
1864   assert((State->getCallOrPrologue() == Prologue ||
1865           State->getCallOrPrologue() == Call) &&
1866          "unhandled ParmContext");
1867
1868   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1869     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1870       unsigned AlignInRegs = Align / 4;
1871       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1872       for (unsigned i = 0; i < Waste; ++i)
1873         reg = State->AllocateReg(GPRArgRegs);
1874     }
1875     if (reg != 0) {
1876       unsigned excess = 4 * (ARM::R4 - reg);
1877
1878       // Special case when NSAA != SP and parameter size greater than size of
1879       // all remained GPR regs. In that case we can't split parameter, we must
1880       // send it to stack. We also must set NCRN to R4, so waste all
1881       // remained registers.
1882       const unsigned NSAAOffset = State->getNextStackOffset();
1883       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1884         while (State->AllocateReg(GPRArgRegs))
1885           ;
1886         return;
1887       }
1888
1889       // First register for byval parameter is the first register that wasn't
1890       // allocated before this method call, so it would be "reg".
1891       // If parameter is small enough to be saved in range [reg, r4), then
1892       // the end (first after last) register would be reg + param-size-in-regs,
1893       // else parameter would be splitted between registers and stack,
1894       // end register would be r4 in this case.
1895       unsigned ByValRegBegin = reg;
1896       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1897       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1898       // Note, first register is allocated in the beginning of function already,
1899       // allocate remained amount of registers we need.
1900       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1901         State->AllocateReg(GPRArgRegs);
1902       // A byval parameter that is split between registers and memory needs its
1903       // size truncated here.
1904       // In the case where the entire structure fits in registers, we set the
1905       // size in memory to zero.
1906       if (size < excess)
1907         size = 0;
1908       else
1909         size -= excess;
1910     }
1911   }
1912 }
1913
1914 /// MatchingStackOffset - Return true if the given stack call argument is
1915 /// already available in the same position (relatively) of the caller's
1916 /// incoming argument stack.
1917 static
1918 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1919                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1920                          const TargetInstrInfo *TII) {
1921   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1922   int FI = INT_MAX;
1923   if (Arg.getOpcode() == ISD::CopyFromReg) {
1924     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1925     if (!TargetRegisterInfo::isVirtualRegister(VR))
1926       return false;
1927     MachineInstr *Def = MRI->getVRegDef(VR);
1928     if (!Def)
1929       return false;
1930     if (!Flags.isByVal()) {
1931       if (!TII->isLoadFromStackSlot(Def, FI))
1932         return false;
1933     } else {
1934       return false;
1935     }
1936   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1937     if (Flags.isByVal())
1938       // ByVal argument is passed in as a pointer but it's now being
1939       // dereferenced. e.g.
1940       // define @foo(%struct.X* %A) {
1941       //   tail call @bar(%struct.X* byval %A)
1942       // }
1943       return false;
1944     SDValue Ptr = Ld->getBasePtr();
1945     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1946     if (!FINode)
1947       return false;
1948     FI = FINode->getIndex();
1949   } else
1950     return false;
1951
1952   assert(FI != INT_MAX);
1953   if (!MFI->isFixedObjectIndex(FI))
1954     return false;
1955   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1956 }
1957
1958 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1959 /// for tail call optimization. Targets which want to do tail call
1960 /// optimization should implement this function.
1961 bool
1962 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1963                                                      CallingConv::ID CalleeCC,
1964                                                      bool isVarArg,
1965                                                      bool isCalleeStructRet,
1966                                                      bool isCallerStructRet,
1967                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1968                                     const SmallVectorImpl<SDValue> &OutVals,
1969                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1970                                                      SelectionDAG& DAG) const {
1971   const Function *CallerF = DAG.getMachineFunction().getFunction();
1972   CallingConv::ID CallerCC = CallerF->getCallingConv();
1973   bool CCMatch = CallerCC == CalleeCC;
1974
1975   // Look for obvious safe cases to perform tail call optimization that do not
1976   // require ABI changes. This is what gcc calls sibcall.
1977
1978   // Do not sibcall optimize vararg calls unless the call site is not passing
1979   // any arguments.
1980   if (isVarArg && !Outs.empty())
1981     return false;
1982
1983   // Exception-handling functions need a special set of instructions to indicate
1984   // a return to the hardware. Tail-calling another function would probably
1985   // break this.
1986   if (CallerF->hasFnAttribute("interrupt"))
1987     return false;
1988
1989   // Also avoid sibcall optimization if either caller or callee uses struct
1990   // return semantics.
1991   if (isCalleeStructRet || isCallerStructRet)
1992     return false;
1993
1994   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1995   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1996   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1997   // support in the assembler and linker to be used. This would need to be
1998   // fixed to fully support tail calls in Thumb1.
1999   //
2000   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2001   // LR.  This means if we need to reload LR, it takes an extra instructions,
2002   // which outweighs the value of the tail call; but here we don't know yet
2003   // whether LR is going to be used.  Probably the right approach is to
2004   // generate the tail call here and turn it back into CALL/RET in
2005   // emitEpilogue if LR is used.
2006
2007   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2008   // but we need to make sure there are enough registers; the only valid
2009   // registers are the 4 used for parameters.  We don't currently do this
2010   // case.
2011   if (Subtarget->isThumb1Only())
2012     return false;
2013
2014   // Externally-defined functions with weak linkage should not be
2015   // tail-called on ARM when the OS does not support dynamic
2016   // pre-emption of symbols, as the AAELF spec requires normal calls
2017   // to undefined weak functions to be replaced with a NOP or jump to the
2018   // next instruction. The behaviour of branch instructions in this
2019   // situation (as used for tail calls) is implementation-defined, so we
2020   // cannot rely on the linker replacing the tail call with a return.
2021   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2022     const GlobalValue *GV = G->getGlobal();
2023     const Triple TT(getTargetMachine().getTargetTriple());
2024     if (GV->hasExternalWeakLinkage() &&
2025         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2026       return false;
2027   }
2028
2029   // If the calling conventions do not match, then we'd better make sure the
2030   // results are returned in the same way as what the caller expects.
2031   if (!CCMatch) {
2032     SmallVector<CCValAssign, 16> RVLocs1;
2033     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2034                        *DAG.getContext(), Call);
2035     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2036
2037     SmallVector<CCValAssign, 16> RVLocs2;
2038     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2039                        *DAG.getContext(), Call);
2040     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2041
2042     if (RVLocs1.size() != RVLocs2.size())
2043       return false;
2044     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2045       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2046         return false;
2047       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2048         return false;
2049       if (RVLocs1[i].isRegLoc()) {
2050         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2051           return false;
2052       } else {
2053         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2054           return false;
2055       }
2056     }
2057   }
2058
2059   // If Caller's vararg or byval argument has been split between registers and
2060   // stack, do not perform tail call, since part of the argument is in caller's
2061   // local frame.
2062   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2063                                       getInfo<ARMFunctionInfo>();
2064   if (AFI_Caller->getArgRegsSaveSize())
2065     return false;
2066
2067   // If the callee takes no arguments then go on to check the results of the
2068   // call.
2069   if (!Outs.empty()) {
2070     // Check if stack adjustment is needed. For now, do not do this if any
2071     // argument is passed on the stack.
2072     SmallVector<CCValAssign, 16> ArgLocs;
2073     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2074                       *DAG.getContext(), Call);
2075     CCInfo.AnalyzeCallOperands(Outs,
2076                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2077     if (CCInfo.getNextStackOffset()) {
2078       MachineFunction &MF = DAG.getMachineFunction();
2079
2080       // Check if the arguments are already laid out in the right way as
2081       // the caller's fixed stack objects.
2082       MachineFrameInfo *MFI = MF.getFrameInfo();
2083       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2084       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2085       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2086            i != e;
2087            ++i, ++realArgIdx) {
2088         CCValAssign &VA = ArgLocs[i];
2089         EVT RegVT = VA.getLocVT();
2090         SDValue Arg = OutVals[realArgIdx];
2091         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2092         if (VA.getLocInfo() == CCValAssign::Indirect)
2093           return false;
2094         if (VA.needsCustom()) {
2095           // f64 and vector types are split into multiple registers or
2096           // register/stack-slot combinations.  The types will not match
2097           // the registers; give up on memory f64 refs until we figure
2098           // out what to do about this.
2099           if (!VA.isRegLoc())
2100             return false;
2101           if (!ArgLocs[++i].isRegLoc())
2102             return false;
2103           if (RegVT == MVT::v2f64) {
2104             if (!ArgLocs[++i].isRegLoc())
2105               return false;
2106             if (!ArgLocs[++i].isRegLoc())
2107               return false;
2108           }
2109         } else if (!VA.isRegLoc()) {
2110           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2111                                    MFI, MRI, TII))
2112             return false;
2113         }
2114       }
2115     }
2116   }
2117
2118   return true;
2119 }
2120
2121 bool
2122 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2123                                   MachineFunction &MF, bool isVarArg,
2124                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2125                                   LLVMContext &Context) const {
2126   SmallVector<CCValAssign, 16> RVLocs;
2127   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2128   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2129                                                     isVarArg));
2130 }
2131
2132 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2133                                     SDLoc DL, SelectionDAG &DAG) {
2134   const MachineFunction &MF = DAG.getMachineFunction();
2135   const Function *F = MF.getFunction();
2136
2137   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2138
2139   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2140   // version of the "preferred return address". These offsets affect the return
2141   // instruction if this is a return from PL1 without hypervisor extensions.
2142   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2143   //    SWI:     0      "subs pc, lr, #0"
2144   //    ABORT:   +4     "subs pc, lr, #4"
2145   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2146   // UNDEF varies depending on where the exception came from ARM or Thumb
2147   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2148
2149   int64_t LROffset;
2150   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2151       IntKind == "ABORT")
2152     LROffset = 4;
2153   else if (IntKind == "SWI" || IntKind == "UNDEF")
2154     LROffset = 0;
2155   else
2156     report_fatal_error("Unsupported interrupt attribute. If present, value "
2157                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2158
2159   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2160
2161   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2162 }
2163
2164 SDValue
2165 ARMTargetLowering::LowerReturn(SDValue Chain,
2166                                CallingConv::ID CallConv, bool isVarArg,
2167                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2168                                const SmallVectorImpl<SDValue> &OutVals,
2169                                SDLoc dl, SelectionDAG &DAG) const {
2170
2171   // CCValAssign - represent the assignment of the return value to a location.
2172   SmallVector<CCValAssign, 16> RVLocs;
2173
2174   // CCState - Info about the registers and stack slots.
2175   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2176                     *DAG.getContext(), Call);
2177
2178   // Analyze outgoing return values.
2179   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2180                                                isVarArg));
2181
2182   SDValue Flag;
2183   SmallVector<SDValue, 4> RetOps;
2184   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2185   bool isLittleEndian = Subtarget->isLittle();
2186
2187   MachineFunction &MF = DAG.getMachineFunction();
2188   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2189   AFI->setReturnRegsCount(RVLocs.size());
2190
2191   // Copy the result values into the output registers.
2192   for (unsigned i = 0, realRVLocIdx = 0;
2193        i != RVLocs.size();
2194        ++i, ++realRVLocIdx) {
2195     CCValAssign &VA = RVLocs[i];
2196     assert(VA.isRegLoc() && "Can only return in registers!");
2197
2198     SDValue Arg = OutVals[realRVLocIdx];
2199
2200     switch (VA.getLocInfo()) {
2201     default: llvm_unreachable("Unknown loc info!");
2202     case CCValAssign::Full: break;
2203     case CCValAssign::BCvt:
2204       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2205       break;
2206     }
2207
2208     if (VA.needsCustom()) {
2209       if (VA.getLocVT() == MVT::v2f64) {
2210         // Extract the first half and return it in two registers.
2211         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2212                                    DAG.getConstant(0, MVT::i32));
2213         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2214                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2215
2216         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2217                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2218                                  Flag);
2219         Flag = Chain.getValue(1);
2220         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2221         VA = RVLocs[++i]; // skip ahead to next loc
2222         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2223                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2224                                  Flag);
2225         Flag = Chain.getValue(1);
2226         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2227         VA = RVLocs[++i]; // skip ahead to next loc
2228
2229         // Extract the 2nd half and fall through to handle it as an f64 value.
2230         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2231                           DAG.getConstant(1, MVT::i32));
2232       }
2233       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2234       // available.
2235       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2236                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2237       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2238                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2239                                Flag);
2240       Flag = Chain.getValue(1);
2241       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2242       VA = RVLocs[++i]; // skip ahead to next loc
2243       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2244                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2245                                Flag);
2246     } else
2247       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2248
2249     // Guarantee that all emitted copies are
2250     // stuck together, avoiding something bad.
2251     Flag = Chain.getValue(1);
2252     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2253   }
2254
2255   // Update chain and glue.
2256   RetOps[0] = Chain;
2257   if (Flag.getNode())
2258     RetOps.push_back(Flag);
2259
2260   // CPUs which aren't M-class use a special sequence to return from
2261   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2262   // though we use "subs pc, lr, #N").
2263   //
2264   // M-class CPUs actually use a normal return sequence with a special
2265   // (hardware-provided) value in LR, so the normal code path works.
2266   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2267       !Subtarget->isMClass()) {
2268     if (Subtarget->isThumb1Only())
2269       report_fatal_error("interrupt attribute is not supported in Thumb1");
2270     return LowerInterruptReturn(RetOps, dl, DAG);
2271   }
2272
2273   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2274 }
2275
2276 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2277   if (N->getNumValues() != 1)
2278     return false;
2279   if (!N->hasNUsesOfValue(1, 0))
2280     return false;
2281
2282   SDValue TCChain = Chain;
2283   SDNode *Copy = *N->use_begin();
2284   if (Copy->getOpcode() == ISD::CopyToReg) {
2285     // If the copy has a glue operand, we conservatively assume it isn't safe to
2286     // perform a tail call.
2287     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2288       return false;
2289     TCChain = Copy->getOperand(0);
2290   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2291     SDNode *VMov = Copy;
2292     // f64 returned in a pair of GPRs.
2293     SmallPtrSet<SDNode*, 2> Copies;
2294     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2295          UI != UE; ++UI) {
2296       if (UI->getOpcode() != ISD::CopyToReg)
2297         return false;
2298       Copies.insert(*UI);
2299     }
2300     if (Copies.size() > 2)
2301       return false;
2302
2303     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2304          UI != UE; ++UI) {
2305       SDValue UseChain = UI->getOperand(0);
2306       if (Copies.count(UseChain.getNode()))
2307         // Second CopyToReg
2308         Copy = *UI;
2309       else {
2310         // We are at the top of this chain.
2311         // If the copy has a glue operand, we conservatively assume it
2312         // isn't safe to perform a tail call.
2313         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2314           return false;
2315         // First CopyToReg
2316         TCChain = UseChain;
2317       }
2318     }
2319   } else if (Copy->getOpcode() == ISD::BITCAST) {
2320     // f32 returned in a single GPR.
2321     if (!Copy->hasOneUse())
2322       return false;
2323     Copy = *Copy->use_begin();
2324     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2325       return false;
2326     // If the copy has a glue operand, we conservatively assume it isn't safe to
2327     // perform a tail call.
2328     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2329       return false;
2330     TCChain = Copy->getOperand(0);
2331   } else {
2332     return false;
2333   }
2334
2335   bool HasRet = false;
2336   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2337        UI != UE; ++UI) {
2338     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2339         UI->getOpcode() != ARMISD::INTRET_FLAG)
2340       return false;
2341     HasRet = true;
2342   }
2343
2344   if (!HasRet)
2345     return false;
2346
2347   Chain = TCChain;
2348   return true;
2349 }
2350
2351 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2352   if (!Subtarget->supportsTailCall())
2353     return false;
2354
2355   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2356     return false;
2357
2358   return !Subtarget->isThumb1Only();
2359 }
2360
2361 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2362 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2363 // one of the above mentioned nodes. It has to be wrapped because otherwise
2364 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2365 // be used to form addressing mode. These wrapped nodes will be selected
2366 // into MOVi.
2367 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2368   EVT PtrVT = Op.getValueType();
2369   // FIXME there is no actual debug info here
2370   SDLoc dl(Op);
2371   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2372   SDValue Res;
2373   if (CP->isMachineConstantPoolEntry())
2374     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2375                                     CP->getAlignment());
2376   else
2377     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2378                                     CP->getAlignment());
2379   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2380 }
2381
2382 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2383   return MachineJumpTableInfo::EK_Inline;
2384 }
2385
2386 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2387                                              SelectionDAG &DAG) const {
2388   MachineFunction &MF = DAG.getMachineFunction();
2389   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2390   unsigned ARMPCLabelIndex = 0;
2391   SDLoc DL(Op);
2392   EVT PtrVT = getPointerTy();
2393   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2394   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2395   SDValue CPAddr;
2396   if (RelocM == Reloc::Static) {
2397     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2398   } else {
2399     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2400     ARMPCLabelIndex = AFI->createPICLabelUId();
2401     ARMConstantPoolValue *CPV =
2402       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2403                                       ARMCP::CPBlockAddress, PCAdj);
2404     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2405   }
2406   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2407   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2408                                MachinePointerInfo::getConstantPool(),
2409                                false, false, false, 0);
2410   if (RelocM == Reloc::Static)
2411     return Result;
2412   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2413   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2414 }
2415
2416 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2417 SDValue
2418 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2419                                                  SelectionDAG &DAG) const {
2420   SDLoc dl(GA);
2421   EVT PtrVT = getPointerTy();
2422   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2423   MachineFunction &MF = DAG.getMachineFunction();
2424   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2425   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2426   ARMConstantPoolValue *CPV =
2427     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2428                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2429   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2430   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2431   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2432                          MachinePointerInfo::getConstantPool(),
2433                          false, false, false, 0);
2434   SDValue Chain = Argument.getValue(1);
2435
2436   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2437   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2438
2439   // call __tls_get_addr.
2440   ArgListTy Args;
2441   ArgListEntry Entry;
2442   Entry.Node = Argument;
2443   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2444   Args.push_back(Entry);
2445
2446   // FIXME: is there useful debug info available here?
2447   TargetLowering::CallLoweringInfo CLI(DAG);
2448   CLI.setDebugLoc(dl).setChain(Chain)
2449     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2450                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2451                0);
2452
2453   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2454   return CallResult.first;
2455 }
2456
2457 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2458 // "local exec" model.
2459 SDValue
2460 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2461                                         SelectionDAG &DAG,
2462                                         TLSModel::Model model) const {
2463   const GlobalValue *GV = GA->getGlobal();
2464   SDLoc dl(GA);
2465   SDValue Offset;
2466   SDValue Chain = DAG.getEntryNode();
2467   EVT PtrVT = getPointerTy();
2468   // Get the Thread Pointer
2469   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2470
2471   if (model == TLSModel::InitialExec) {
2472     MachineFunction &MF = DAG.getMachineFunction();
2473     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2474     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2475     // Initial exec model.
2476     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2477     ARMConstantPoolValue *CPV =
2478       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2479                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2480                                       true);
2481     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2482     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2483     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2484                          MachinePointerInfo::getConstantPool(),
2485                          false, false, false, 0);
2486     Chain = Offset.getValue(1);
2487
2488     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2489     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2490
2491     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2492                          MachinePointerInfo::getConstantPool(),
2493                          false, false, false, 0);
2494   } else {
2495     // local exec model
2496     assert(model == TLSModel::LocalExec);
2497     ARMConstantPoolValue *CPV =
2498       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2499     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2500     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2501     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2502                          MachinePointerInfo::getConstantPool(),
2503                          false, false, false, 0);
2504   }
2505
2506   // The address of the thread local variable is the add of the thread
2507   // pointer with the offset of the variable.
2508   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2509 }
2510
2511 SDValue
2512 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2513   // TODO: implement the "local dynamic" model
2514   assert(Subtarget->isTargetELF() &&
2515          "TLS not implemented for non-ELF targets");
2516   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2517
2518   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2519
2520   switch (model) {
2521     case TLSModel::GeneralDynamic:
2522     case TLSModel::LocalDynamic:
2523       return LowerToTLSGeneralDynamicModel(GA, DAG);
2524     case TLSModel::InitialExec:
2525     case TLSModel::LocalExec:
2526       return LowerToTLSExecModels(GA, DAG, model);
2527   }
2528   llvm_unreachable("bogus TLS model");
2529 }
2530
2531 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2532                                                  SelectionDAG &DAG) const {
2533   EVT PtrVT = getPointerTy();
2534   SDLoc dl(Op);
2535   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2536   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2537     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2538     ARMConstantPoolValue *CPV =
2539       ARMConstantPoolConstant::Create(GV,
2540                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2541     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2542     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2543     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2544                                  CPAddr,
2545                                  MachinePointerInfo::getConstantPool(),
2546                                  false, false, false, 0);
2547     SDValue Chain = Result.getValue(1);
2548     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2549     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2550     if (!UseGOTOFF)
2551       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2552                            MachinePointerInfo::getGOT(),
2553                            false, false, false, 0);
2554     return Result;
2555   }
2556
2557   // If we have T2 ops, we can materialize the address directly via movt/movw
2558   // pair. This is always cheaper.
2559   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2560     ++NumMovwMovt;
2561     // FIXME: Once remat is capable of dealing with instructions with register
2562     // operands, expand this into two nodes.
2563     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2564                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2565   } else {
2566     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2567     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2568     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2569                        MachinePointerInfo::getConstantPool(),
2570                        false, false, false, 0);
2571   }
2572 }
2573
2574 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2575                                                     SelectionDAG &DAG) const {
2576   EVT PtrVT = getPointerTy();
2577   SDLoc dl(Op);
2578   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2579   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2580
2581   if (Subtarget->useMovt(DAG.getMachineFunction()))
2582     ++NumMovwMovt;
2583
2584   // FIXME: Once remat is capable of dealing with instructions with register
2585   // operands, expand this into multiple nodes
2586   unsigned Wrapper =
2587       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2588
2589   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2590   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2591
2592   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2593     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2594                          MachinePointerInfo::getGOT(), false, false, false, 0);
2595   return Result;
2596 }
2597
2598 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2599                                                      SelectionDAG &DAG) const {
2600   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2601   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2602          "Windows on ARM expects to use movw/movt");
2603
2604   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2605   const ARMII::TOF TargetFlags =
2606     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2607   EVT PtrVT = getPointerTy();
2608   SDValue Result;
2609   SDLoc DL(Op);
2610
2611   ++NumMovwMovt;
2612
2613   // FIXME: Once remat is capable of dealing with instructions with register
2614   // operands, expand this into two nodes.
2615   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2616                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2617                                                   TargetFlags));
2618   if (GV->hasDLLImportStorageClass())
2619     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2620                          MachinePointerInfo::getGOT(), false, false, false, 0);
2621   return Result;
2622 }
2623
2624 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2625                                                     SelectionDAG &DAG) const {
2626   assert(Subtarget->isTargetELF() &&
2627          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2628   MachineFunction &MF = DAG.getMachineFunction();
2629   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2630   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2631   EVT PtrVT = getPointerTy();
2632   SDLoc dl(Op);
2633   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2634   ARMConstantPoolValue *CPV =
2635     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2636                                   ARMPCLabelIndex, PCAdj);
2637   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2638   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2639   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2640                                MachinePointerInfo::getConstantPool(),
2641                                false, false, false, 0);
2642   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2643   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2644 }
2645
2646 SDValue
2647 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2648   SDLoc dl(Op);
2649   SDValue Val = DAG.getConstant(0, MVT::i32);
2650   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2651                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2652                      Op.getOperand(1), Val);
2653 }
2654
2655 SDValue
2656 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2657   SDLoc dl(Op);
2658   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2659                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2660 }
2661
2662 SDValue
2663 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2664                                           const ARMSubtarget *Subtarget) const {
2665   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2666   SDLoc dl(Op);
2667   switch (IntNo) {
2668   default: return SDValue();    // Don't custom lower most intrinsics.
2669   case Intrinsic::arm_rbit: {
2670     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2671            "RBIT intrinsic must have i32 type!");
2672     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2673   }
2674   case Intrinsic::arm_thread_pointer: {
2675     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2676     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2677   }
2678   case Intrinsic::eh_sjlj_lsda: {
2679     MachineFunction &MF = DAG.getMachineFunction();
2680     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2681     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2682     EVT PtrVT = getPointerTy();
2683     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2684     SDValue CPAddr;
2685     unsigned PCAdj = (RelocM != Reloc::PIC_)
2686       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2687     ARMConstantPoolValue *CPV =
2688       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2689                                       ARMCP::CPLSDA, PCAdj);
2690     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2691     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2692     SDValue Result =
2693       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2694                   MachinePointerInfo::getConstantPool(),
2695                   false, false, false, 0);
2696
2697     if (RelocM == Reloc::PIC_) {
2698       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2699       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2700     }
2701     return Result;
2702   }
2703   case Intrinsic::arm_neon_vmulls:
2704   case Intrinsic::arm_neon_vmullu: {
2705     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2706       ? ARMISD::VMULLs : ARMISD::VMULLu;
2707     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2708                        Op.getOperand(1), Op.getOperand(2));
2709   }
2710   }
2711 }
2712
2713 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2714                                  const ARMSubtarget *Subtarget) {
2715   // FIXME: handle "fence singlethread" more efficiently.
2716   SDLoc dl(Op);
2717   if (!Subtarget->hasDataBarrier()) {
2718     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2719     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2720     // here.
2721     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2722            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2723     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2724                        DAG.getConstant(0, MVT::i32));
2725   }
2726
2727   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2728   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2729   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2730   if (Subtarget->isMClass()) {
2731     // Only a full system barrier exists in the M-class architectures.
2732     Domain = ARM_MB::SY;
2733   } else if (Subtarget->isSwift() && Ord == Release) {
2734     // Swift happens to implement ISHST barriers in a way that's compatible with
2735     // Release semantics but weaker than ISH so we'd be fools not to use
2736     // it. Beware: other processors probably don't!
2737     Domain = ARM_MB::ISHST;
2738   }
2739
2740   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2741                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2742                      DAG.getConstant(Domain, MVT::i32));
2743 }
2744
2745 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2746                              const ARMSubtarget *Subtarget) {
2747   // ARM pre v5TE and Thumb1 does not have preload instructions.
2748   if (!(Subtarget->isThumb2() ||
2749         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2750     // Just preserve the chain.
2751     return Op.getOperand(0);
2752
2753   SDLoc dl(Op);
2754   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2755   if (!isRead &&
2756       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2757     // ARMv7 with MP extension has PLDW.
2758     return Op.getOperand(0);
2759
2760   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2761   if (Subtarget->isThumb()) {
2762     // Invert the bits.
2763     isRead = ~isRead & 1;
2764     isData = ~isData & 1;
2765   }
2766
2767   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2768                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2769                      DAG.getConstant(isData, MVT::i32));
2770 }
2771
2772 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2773   MachineFunction &MF = DAG.getMachineFunction();
2774   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2775
2776   // vastart just stores the address of the VarArgsFrameIndex slot into the
2777   // memory location argument.
2778   SDLoc dl(Op);
2779   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2780   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2781   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2782   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2783                       MachinePointerInfo(SV), false, false, 0);
2784 }
2785
2786 SDValue
2787 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2788                                         SDValue &Root, SelectionDAG &DAG,
2789                                         SDLoc dl) const {
2790   MachineFunction &MF = DAG.getMachineFunction();
2791   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2792
2793   const TargetRegisterClass *RC;
2794   if (AFI->isThumb1OnlyFunction())
2795     RC = &ARM::tGPRRegClass;
2796   else
2797     RC = &ARM::GPRRegClass;
2798
2799   // Transform the arguments stored in physical registers into virtual ones.
2800   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2801   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2802
2803   SDValue ArgValue2;
2804   if (NextVA.isMemLoc()) {
2805     MachineFrameInfo *MFI = MF.getFrameInfo();
2806     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2807
2808     // Create load node to retrieve arguments from the stack.
2809     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2810     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2811                             MachinePointerInfo::getFixedStack(FI),
2812                             false, false, false, 0);
2813   } else {
2814     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2815     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2816   }
2817   if (!Subtarget->isLittle())
2818     std::swap (ArgValue, ArgValue2);
2819   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2820 }
2821
2822 void
2823 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2824                                   unsigned InRegsParamRecordIdx,
2825                                   unsigned ArgSize,
2826                                   unsigned &ArgRegsSize,
2827                                   unsigned &ArgRegsSaveSize)
2828   const {
2829   unsigned NumGPRs;
2830   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2831     unsigned RBegin, REnd;
2832     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2833     NumGPRs = REnd - RBegin;
2834   } else {
2835     unsigned int firstUnalloced;
2836     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs);
2837     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2838   }
2839
2840   unsigned Align = Subtarget->getFrameLowering()->getStackAlignment();
2841   ArgRegsSize = NumGPRs * 4;
2842
2843   // If parameter is split between stack and GPRs...
2844   if (NumGPRs && Align > 4 &&
2845       (ArgRegsSize < ArgSize ||
2846         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2847     // Add padding for part of param recovered from GPRs.  For example,
2848     // if Align == 8, its last byte must be at address K*8 - 1.
2849     // We need to do it, since remained (stack) part of parameter has
2850     // stack alignment, and we need to "attach" "GPRs head" without gaps
2851     // to it:
2852     // Stack:
2853     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2854     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2855     //
2856     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2857     unsigned Padding =
2858         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2859     ArgRegsSaveSize = ArgRegsSize + Padding;
2860   } else
2861     // We don't need to extend regs save size for byval parameters if they
2862     // are passed via GPRs only.
2863     ArgRegsSaveSize = ArgRegsSize;
2864 }
2865
2866 // The remaining GPRs hold either the beginning of variable-argument
2867 // data, or the beginning of an aggregate passed by value (usually
2868 // byval).  Either way, we allocate stack slots adjacent to the data
2869 // provided by our caller, and store the unallocated registers there.
2870 // If this is a variadic function, the va_list pointer will begin with
2871 // these values; otherwise, this reassembles a (byval) structure that
2872 // was split between registers and memory.
2873 // Return: The frame index registers were stored into.
2874 int
2875 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2876                                   SDLoc dl, SDValue &Chain,
2877                                   const Value *OrigArg,
2878                                   unsigned InRegsParamRecordIdx,
2879                                   unsigned OffsetFromOrigArg,
2880                                   unsigned ArgOffset,
2881                                   unsigned ArgSize,
2882                                   bool ForceMutable,
2883                                   unsigned ByValStoreOffset,
2884                                   unsigned TotalArgRegsSaveSize) const {
2885
2886   // Currently, two use-cases possible:
2887   // Case #1. Non-var-args function, and we meet first byval parameter.
2888   //          Setup first unallocated register as first byval register;
2889   //          eat all remained registers
2890   //          (these two actions are performed by HandleByVal method).
2891   //          Then, here, we initialize stack frame with
2892   //          "store-reg" instructions.
2893   // Case #2. Var-args function, that doesn't contain byval parameters.
2894   //          The same: eat all remained unallocated registers,
2895   //          initialize stack frame.
2896
2897   MachineFunction &MF = DAG.getMachineFunction();
2898   MachineFrameInfo *MFI = MF.getFrameInfo();
2899   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2900   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2901   unsigned RBegin, REnd;
2902   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2903     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2904     firstRegToSaveIndex = RBegin - ARM::R0;
2905     lastRegToSaveIndex = REnd - ARM::R0;
2906   } else {
2907     firstRegToSaveIndex = CCInfo.getFirstUnallocated(GPRArgRegs);
2908     lastRegToSaveIndex = 4;
2909   }
2910
2911   unsigned ArgRegsSize, ArgRegsSaveSize;
2912   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2913                  ArgRegsSize, ArgRegsSaveSize);
2914
2915   // Store any by-val regs to their spots on the stack so that they may be
2916   // loaded by deferencing the result of formal parameter pointer or va_next.
2917   // Note: once stack area for byval/varargs registers
2918   // was initialized, it can't be initialized again.
2919   if (ArgRegsSaveSize) {
2920     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2921
2922     if (Padding) {
2923       assert(AFI->getStoredByValParamsPadding() == 0 &&
2924              "The only parameter may be padded.");
2925       AFI->setStoredByValParamsPadding(Padding);
2926     }
2927
2928     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2929                                             Padding +
2930                                               ByValStoreOffset -
2931                                               (int64_t)TotalArgRegsSaveSize,
2932                                             false);
2933     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2934     if (Padding) {
2935        MFI->CreateFixedObject(Padding,
2936                               ArgOffset + ByValStoreOffset -
2937                                 (int64_t)ArgRegsSaveSize,
2938                               false);
2939     }
2940
2941     SmallVector<SDValue, 4> MemOps;
2942     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2943          ++firstRegToSaveIndex, ++i) {
2944       const TargetRegisterClass *RC;
2945       if (AFI->isThumb1OnlyFunction())
2946         RC = &ARM::tGPRRegClass;
2947       else
2948         RC = &ARM::GPRRegClass;
2949
2950       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2951       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2952       SDValue Store =
2953         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2954                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2955                      false, false, 0);
2956       MemOps.push_back(Store);
2957       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2958                         DAG.getConstant(4, getPointerTy()));
2959     }
2960
2961     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2962
2963     if (!MemOps.empty())
2964       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2965     return FrameIndex;
2966   } else {
2967     if (ArgSize == 0) {
2968       // We cannot allocate a zero-byte object for the first variadic argument,
2969       // so just make up a size.
2970       ArgSize = 4;
2971     }
2972     // This will point to the next argument passed via stack.
2973     return MFI->CreateFixedObject(
2974       ArgSize, ArgOffset, !ForceMutable);
2975   }
2976 }
2977
2978 // Setup stack frame, the va_list pointer will start from.
2979 void
2980 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2981                                         SDLoc dl, SDValue &Chain,
2982                                         unsigned ArgOffset,
2983                                         unsigned TotalArgRegsSaveSize,
2984                                         bool ForceMutable) const {
2985   MachineFunction &MF = DAG.getMachineFunction();
2986   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2987
2988   // Try to store any remaining integer argument regs
2989   // to their spots on the stack so that they may be loaded by deferencing
2990   // the result of va_next.
2991   // If there is no regs to be stored, just point address after last
2992   // argument passed via stack.
2993   int FrameIndex =
2994     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2995                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2996                    0, TotalArgRegsSaveSize);
2997
2998   AFI->setVarArgsFrameIndex(FrameIndex);
2999 }
3000
3001 SDValue
3002 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3003                                         CallingConv::ID CallConv, bool isVarArg,
3004                                         const SmallVectorImpl<ISD::InputArg>
3005                                           &Ins,
3006                                         SDLoc dl, SelectionDAG &DAG,
3007                                         SmallVectorImpl<SDValue> &InVals)
3008                                           const {
3009   MachineFunction &MF = DAG.getMachineFunction();
3010   MachineFrameInfo *MFI = MF.getFrameInfo();
3011
3012   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3013
3014   // Assign locations to all of the incoming arguments.
3015   SmallVector<CCValAssign, 16> ArgLocs;
3016   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3017                     *DAG.getContext(), Prologue);
3018   CCInfo.AnalyzeFormalArguments(Ins,
3019                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3020                                                   isVarArg));
3021
3022   SmallVector<SDValue, 16> ArgValues;
3023   int lastInsIndex = -1;
3024   SDValue ArgValue;
3025   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3026   unsigned CurArgIdx = 0;
3027
3028   // Initially ArgRegsSaveSize is zero.
3029   // Then we increase this value each time we meet byval parameter.
3030   // We also increase this value in case of varargs function.
3031   AFI->setArgRegsSaveSize(0);
3032
3033   unsigned ByValStoreOffset = 0;
3034   unsigned TotalArgRegsSaveSize = 0;
3035   unsigned ArgRegsSaveSizeMaxAlign = 4;
3036
3037   // Calculate the amount of stack space that we need to allocate to store
3038   // byval and variadic arguments that are passed in registers.
3039   // We need to know this before we allocate the first byval or variadic
3040   // argument, as they will be allocated a stack slot below the CFA (Canonical
3041   // Frame Address, the stack pointer at entry to the function).
3042   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3043     CCValAssign &VA = ArgLocs[i];
3044     if (VA.isMemLoc()) {
3045       int index = VA.getValNo();
3046       if (index != lastInsIndex) {
3047         ISD::ArgFlagsTy Flags = Ins[index].Flags;
3048         if (Flags.isByVal()) {
3049           unsigned ExtraArgRegsSize;
3050           unsigned ExtraArgRegsSaveSize;
3051           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProcessed(),
3052                          Flags.getByValSize(),
3053                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
3054
3055           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3056           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3057               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3058           CCInfo.nextInRegsParam();
3059         }
3060         lastInsIndex = index;
3061       }
3062     }
3063   }
3064   CCInfo.rewindByValRegsInfo();
3065   lastInsIndex = -1;
3066   if (isVarArg && MFI->hasVAStart()) {
3067     unsigned ExtraArgRegsSize;
3068     unsigned ExtraArgRegsSaveSize;
3069     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3070                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
3071     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3072   }
3073   // If the arg regs save area contains N-byte aligned values, the
3074   // bottom of it must be at least N-byte aligned.
3075   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3076   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3077
3078   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3079     CCValAssign &VA = ArgLocs[i];
3080     if (Ins[VA.getValNo()].isOrigArg()) {
3081       std::advance(CurOrigArg,
3082                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3083       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3084     }
3085     // Arguments stored in registers.
3086     if (VA.isRegLoc()) {
3087       EVT RegVT = VA.getLocVT();
3088
3089       if (VA.needsCustom()) {
3090         // f64 and vector types are split up into multiple registers or
3091         // combinations of registers and stack slots.
3092         if (VA.getLocVT() == MVT::v2f64) {
3093           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3094                                                    Chain, DAG, dl);
3095           VA = ArgLocs[++i]; // skip ahead to next loc
3096           SDValue ArgValue2;
3097           if (VA.isMemLoc()) {
3098             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3099             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3100             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3101                                     MachinePointerInfo::getFixedStack(FI),
3102                                     false, false, false, 0);
3103           } else {
3104             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3105                                              Chain, DAG, dl);
3106           }
3107           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3108           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3109                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3110           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3111                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3112         } else
3113           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3114
3115       } else {
3116         const TargetRegisterClass *RC;
3117
3118         if (RegVT == MVT::f32)
3119           RC = &ARM::SPRRegClass;
3120         else if (RegVT == MVT::f64)
3121           RC = &ARM::DPRRegClass;
3122         else if (RegVT == MVT::v2f64)
3123           RC = &ARM::QPRRegClass;
3124         else if (RegVT == MVT::i32)
3125           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3126                                            : &ARM::GPRRegClass;
3127         else
3128           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3129
3130         // Transform the arguments in physical registers into virtual ones.
3131         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3132         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3133       }
3134
3135       // If this is an 8 or 16-bit value, it is really passed promoted
3136       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3137       // truncate to the right size.
3138       switch (VA.getLocInfo()) {
3139       default: llvm_unreachable("Unknown loc info!");
3140       case CCValAssign::Full: break;
3141       case CCValAssign::BCvt:
3142         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3143         break;
3144       case CCValAssign::SExt:
3145         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3146                                DAG.getValueType(VA.getValVT()));
3147         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3148         break;
3149       case CCValAssign::ZExt:
3150         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3151                                DAG.getValueType(VA.getValVT()));
3152         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3153         break;
3154       }
3155
3156       InVals.push_back(ArgValue);
3157
3158     } else { // VA.isRegLoc()
3159
3160       // sanity check
3161       assert(VA.isMemLoc());
3162       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3163
3164       int index = VA.getValNo();
3165
3166       // Some Ins[] entries become multiple ArgLoc[] entries.
3167       // Process them only once.
3168       if (index != lastInsIndex)
3169         {
3170           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3171           // FIXME: For now, all byval parameter objects are marked mutable.
3172           // This can be changed with more analysis.
3173           // In case of tail call optimization mark all arguments mutable.
3174           // Since they could be overwritten by lowering of arguments in case of
3175           // a tail call.
3176           if (Flags.isByVal()) {
3177             assert(Ins[index].isOrigArg() &&
3178                    "Byval arguments cannot be implicit");
3179             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3180
3181             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3182             int FrameIndex = StoreByValRegs(
3183                 CCInfo, DAG, dl, Chain, CurOrigArg,
3184                 CurByValIndex,
3185                 Ins[VA.getValNo()].PartOffset,
3186                 VA.getLocMemOffset(),
3187                 Flags.getByValSize(),
3188                 true /*force mutable frames*/,
3189                 ByValStoreOffset,
3190                 TotalArgRegsSaveSize);
3191             ByValStoreOffset += Flags.getByValSize();
3192             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3193             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3194             CCInfo.nextInRegsParam();
3195           } else {
3196             unsigned FIOffset = VA.getLocMemOffset();
3197             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3198                                             FIOffset, true);
3199
3200             // Create load nodes to retrieve arguments from the stack.
3201             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3202             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3203                                          MachinePointerInfo::getFixedStack(FI),
3204                                          false, false, false, 0));
3205           }
3206           lastInsIndex = index;
3207         }
3208     }
3209   }
3210
3211   // varargs
3212   if (isVarArg && MFI->hasVAStart())
3213     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3214                          CCInfo.getNextStackOffset(),
3215                          TotalArgRegsSaveSize);
3216
3217   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3218
3219   return Chain;
3220 }
3221
3222 /// isFloatingPointZero - Return true if this is +0.0.
3223 static bool isFloatingPointZero(SDValue Op) {
3224   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3225     return CFP->getValueAPF().isPosZero();
3226   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3227     // Maybe this has already been legalized into the constant pool?
3228     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3229       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3230       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3231         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3232           return CFP->getValueAPF().isPosZero();
3233     }
3234   } else if (Op->getOpcode() == ISD::BITCAST &&
3235              Op->getValueType(0) == MVT::f64) {
3236     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3237     // created by LowerConstantFP().
3238     SDValue BitcastOp = Op->getOperand(0);
3239     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3240       SDValue MoveOp = BitcastOp->getOperand(0);
3241       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3242           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3243         return true;
3244       }
3245     }
3246   }
3247   return false;
3248 }
3249
3250 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3251 /// the given operands.
3252 SDValue
3253 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3254                              SDValue &ARMcc, SelectionDAG &DAG,
3255                              SDLoc dl) const {
3256   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3257     unsigned C = RHSC->getZExtValue();
3258     if (!isLegalICmpImmediate(C)) {
3259       // Constant does not fit, try adjusting it by one?
3260       switch (CC) {
3261       default: break;
3262       case ISD::SETLT:
3263       case ISD::SETGE:
3264         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3265           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3266           RHS = DAG.getConstant(C-1, MVT::i32);
3267         }
3268         break;
3269       case ISD::SETULT:
3270       case ISD::SETUGE:
3271         if (C != 0 && isLegalICmpImmediate(C-1)) {
3272           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3273           RHS = DAG.getConstant(C-1, MVT::i32);
3274         }
3275         break;
3276       case ISD::SETLE:
3277       case ISD::SETGT:
3278         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3279           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3280           RHS = DAG.getConstant(C+1, MVT::i32);
3281         }
3282         break;
3283       case ISD::SETULE:
3284       case ISD::SETUGT:
3285         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3286           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3287           RHS = DAG.getConstant(C+1, MVT::i32);
3288         }
3289         break;
3290       }
3291     }
3292   }
3293
3294   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3295   ARMISD::NodeType CompareType;
3296   switch (CondCode) {
3297   default:
3298     CompareType = ARMISD::CMP;
3299     break;
3300   case ARMCC::EQ:
3301   case ARMCC::NE:
3302     // Uses only Z Flag
3303     CompareType = ARMISD::CMPZ;
3304     break;
3305   }
3306   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3307   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3308 }
3309
3310 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3311 SDValue
3312 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3313                              SDLoc dl) const {
3314   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3315   SDValue Cmp;
3316   if (!isFloatingPointZero(RHS))
3317     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3318   else
3319     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3320   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3321 }
3322
3323 /// duplicateCmp - Glue values can have only one use, so this function
3324 /// duplicates a comparison node.
3325 SDValue
3326 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3327   unsigned Opc = Cmp.getOpcode();
3328   SDLoc DL(Cmp);
3329   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3330     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3331
3332   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3333   Cmp = Cmp.getOperand(0);
3334   Opc = Cmp.getOpcode();
3335   if (Opc == ARMISD::CMPFP)
3336     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3337   else {
3338     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3339     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3340   }
3341   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3342 }
3343
3344 std::pair<SDValue, SDValue>
3345 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3346                                  SDValue &ARMcc) const {
3347   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3348
3349   SDValue Value, OverflowCmp;
3350   SDValue LHS = Op.getOperand(0);
3351   SDValue RHS = Op.getOperand(1);
3352
3353
3354   // FIXME: We are currently always generating CMPs because we don't support
3355   // generating CMN through the backend. This is not as good as the natural
3356   // CMP case because it causes a register dependency and cannot be folded
3357   // later.
3358
3359   switch (Op.getOpcode()) {
3360   default:
3361     llvm_unreachable("Unknown overflow instruction!");
3362   case ISD::SADDO:
3363     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3364     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3365     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3366     break;
3367   case ISD::UADDO:
3368     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3369     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3370     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3371     break;
3372   case ISD::SSUBO:
3373     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3374     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3375     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3376     break;
3377   case ISD::USUBO:
3378     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3379     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3380     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3381     break;
3382   } // switch (...)
3383
3384   return std::make_pair(Value, OverflowCmp);
3385 }
3386
3387
3388 SDValue
3389 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3390   // Let legalize expand this if it isn't a legal type yet.
3391   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3392     return SDValue();
3393
3394   SDValue Value, OverflowCmp;
3395   SDValue ARMcc;
3396   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3397   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3398   // We use 0 and 1 as false and true values.
3399   SDValue TVal = DAG.getConstant(1, MVT::i32);
3400   SDValue FVal = DAG.getConstant(0, MVT::i32);
3401   EVT VT = Op.getValueType();
3402
3403   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3404                                  ARMcc, CCR, OverflowCmp);
3405
3406   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3407   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3408 }
3409
3410
3411 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3412   SDValue Cond = Op.getOperand(0);
3413   SDValue SelectTrue = Op.getOperand(1);
3414   SDValue SelectFalse = Op.getOperand(2);
3415   SDLoc dl(Op);
3416   unsigned Opc = Cond.getOpcode();
3417
3418   if (Cond.getResNo() == 1 &&
3419       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3420        Opc == ISD::USUBO)) {
3421     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3422       return SDValue();
3423
3424     SDValue Value, OverflowCmp;
3425     SDValue ARMcc;
3426     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3427     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3428     EVT VT = Op.getValueType();
3429
3430     return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3431                    OverflowCmp, DAG);
3432   }
3433
3434   // Convert:
3435   //
3436   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3437   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3438   //
3439   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3440     const ConstantSDNode *CMOVTrue =
3441       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3442     const ConstantSDNode *CMOVFalse =
3443       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3444
3445     if (CMOVTrue && CMOVFalse) {
3446       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3447       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3448
3449       SDValue True;
3450       SDValue False;
3451       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3452         True = SelectTrue;
3453         False = SelectFalse;
3454       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3455         True = SelectFalse;
3456         False = SelectTrue;
3457       }
3458
3459       if (True.getNode() && False.getNode()) {
3460         EVT VT = Op.getValueType();
3461         SDValue ARMcc = Cond.getOperand(2);
3462         SDValue CCR = Cond.getOperand(3);
3463         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3464         assert(True.getValueType() == VT);
3465         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3466       }
3467     }
3468   }
3469
3470   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3471   // undefined bits before doing a full-word comparison with zero.
3472   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3473                      DAG.getConstant(1, Cond.getValueType()));
3474
3475   return DAG.getSelectCC(dl, Cond,
3476                          DAG.getConstant(0, Cond.getValueType()),
3477                          SelectTrue, SelectFalse, ISD::SETNE);
3478 }
3479
3480 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3481   if (CC == ISD::SETNE)
3482     return ISD::SETEQ;
3483   return ISD::getSetCCInverse(CC, true);
3484 }
3485
3486 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3487                                  bool &swpCmpOps, bool &swpVselOps) {
3488   // Start by selecting the GE condition code for opcodes that return true for
3489   // 'equality'
3490   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3491       CC == ISD::SETULE)
3492     CondCode = ARMCC::GE;
3493
3494   // and GT for opcodes that return false for 'equality'.
3495   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3496            CC == ISD::SETULT)
3497     CondCode = ARMCC::GT;
3498
3499   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3500   // to swap the compare operands.
3501   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3502       CC == ISD::SETULT)
3503     swpCmpOps = true;
3504
3505   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3506   // If we have an unordered opcode, we need to swap the operands to the VSEL
3507   // instruction (effectively negating the condition).
3508   //
3509   // This also has the effect of swapping which one of 'less' or 'greater'
3510   // returns true, so we also swap the compare operands. It also switches
3511   // whether we return true for 'equality', so we compensate by picking the
3512   // opposite condition code to our original choice.
3513   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3514       CC == ISD::SETUGT) {
3515     swpCmpOps = !swpCmpOps;
3516     swpVselOps = !swpVselOps;
3517     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3518   }
3519
3520   // 'ordered' is 'anything but unordered', so use the VS condition code and
3521   // swap the VSEL operands.
3522   if (CC == ISD::SETO) {
3523     CondCode = ARMCC::VS;
3524     swpVselOps = true;
3525   }
3526
3527   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3528   // code and swap the VSEL operands.
3529   if (CC == ISD::SETUNE) {
3530     CondCode = ARMCC::EQ;
3531     swpVselOps = true;
3532   }
3533 }
3534
3535 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3536                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3537                                    SDValue Cmp, SelectionDAG &DAG) const {
3538   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3539     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3540                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3541     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3542                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3543
3544     SDValue TrueLow = TrueVal.getValue(0);
3545     SDValue TrueHigh = TrueVal.getValue(1);
3546     SDValue FalseLow = FalseVal.getValue(0);
3547     SDValue FalseHigh = FalseVal.getValue(1);
3548
3549     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3550                               ARMcc, CCR, Cmp);
3551     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3552                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3553
3554     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3555   } else {
3556     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3557                        Cmp);
3558   }
3559 }
3560
3561 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3562   EVT VT = Op.getValueType();
3563   SDValue LHS = Op.getOperand(0);
3564   SDValue RHS = Op.getOperand(1);
3565   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3566   SDValue TrueVal = Op.getOperand(2);
3567   SDValue FalseVal = Op.getOperand(3);
3568   SDLoc dl(Op);
3569
3570   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3571     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3572                                                     dl);
3573
3574     // If softenSetCCOperands only returned one value, we should compare it to
3575     // zero.
3576     if (!RHS.getNode()) {
3577       RHS = DAG.getConstant(0, LHS.getValueType());
3578       CC = ISD::SETNE;
3579     }
3580   }
3581
3582   if (LHS.getValueType() == MVT::i32) {
3583     // Try to generate VSEL on ARMv8.
3584     // The VSEL instruction can't use all the usual ARM condition
3585     // codes: it only has two bits to select the condition code, so it's
3586     // constrained to use only GE, GT, VS and EQ.
3587     //
3588     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3589     // swap the operands of the previous compare instruction (effectively
3590     // inverting the compare condition, swapping 'less' and 'greater') and
3591     // sometimes need to swap the operands to the VSEL (which inverts the
3592     // condition in the sense of firing whenever the previous condition didn't)
3593     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3594                                     TrueVal.getValueType() == MVT::f64)) {
3595       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3596       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3597           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3598         CC = getInverseCCForVSEL(CC);
3599         std::swap(TrueVal, FalseVal);
3600       }
3601     }
3602
3603     SDValue ARMcc;
3604     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3605     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3606     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3607   }
3608
3609   ARMCC::CondCodes CondCode, CondCode2;
3610   FPCCToARMCC(CC, CondCode, CondCode2);
3611
3612   // Try to generate VSEL on ARMv8.
3613   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3614                                   TrueVal.getValueType() == MVT::f64)) {
3615     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3616     // same operands, as follows:
3617     //   c = fcmp [ogt, olt, ugt, ult] a, b
3618     //   select c, a, b
3619     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3620     // handled differently than the original code sequence.
3621     if (getTargetMachine().Options.UnsafeFPMath) {
3622       if (LHS == TrueVal && RHS == FalseVal) {
3623         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3624           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3625         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3626           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3627       } else if (LHS == FalseVal && RHS == TrueVal) {
3628         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3629           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3630         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3631           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3632       }
3633     }
3634
3635     bool swpCmpOps = false;
3636     bool swpVselOps = false;
3637     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3638
3639     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3640         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3641       if (swpCmpOps)
3642         std::swap(LHS, RHS);
3643       if (swpVselOps)
3644         std::swap(TrueVal, FalseVal);
3645     }
3646   }
3647
3648   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3649   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3650   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3651   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3652   if (CondCode2 != ARMCC::AL) {
3653     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3654     // FIXME: Needs another CMP because flag can have but one use.
3655     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3656     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3657   }
3658   return Result;
3659 }
3660
3661 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3662 /// to morph to an integer compare sequence.
3663 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3664                            const ARMSubtarget *Subtarget) {
3665   SDNode *N = Op.getNode();
3666   if (!N->hasOneUse())
3667     // Otherwise it requires moving the value from fp to integer registers.
3668     return false;
3669   if (!N->getNumValues())
3670     return false;
3671   EVT VT = Op.getValueType();
3672   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3673     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3674     // vmrs are very slow, e.g. cortex-a8.
3675     return false;
3676
3677   if (isFloatingPointZero(Op)) {
3678     SeenZero = true;
3679     return true;
3680   }
3681   return ISD::isNormalLoad(N);
3682 }
3683
3684 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3685   if (isFloatingPointZero(Op))
3686     return DAG.getConstant(0, MVT::i32);
3687
3688   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3689     return DAG.getLoad(MVT::i32, SDLoc(Op),
3690                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3691                        Ld->isVolatile(), Ld->isNonTemporal(),
3692                        Ld->isInvariant(), Ld->getAlignment());
3693
3694   llvm_unreachable("Unknown VFP cmp argument!");
3695 }
3696
3697 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3698                            SDValue &RetVal1, SDValue &RetVal2) {
3699   if (isFloatingPointZero(Op)) {
3700     RetVal1 = DAG.getConstant(0, MVT::i32);
3701     RetVal2 = DAG.getConstant(0, MVT::i32);
3702     return;
3703   }
3704
3705   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3706     SDValue Ptr = Ld->getBasePtr();
3707     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3708                           Ld->getChain(), Ptr,
3709                           Ld->getPointerInfo(),
3710                           Ld->isVolatile(), Ld->isNonTemporal(),
3711                           Ld->isInvariant(), Ld->getAlignment());
3712
3713     EVT PtrType = Ptr.getValueType();
3714     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3715     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3716                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3717     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3718                           Ld->getChain(), NewPtr,
3719                           Ld->getPointerInfo().getWithOffset(4),
3720                           Ld->isVolatile(), Ld->isNonTemporal(),
3721                           Ld->isInvariant(), NewAlign);
3722     return;
3723   }
3724
3725   llvm_unreachable("Unknown VFP cmp argument!");
3726 }
3727
3728 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3729 /// f32 and even f64 comparisons to integer ones.
3730 SDValue
3731 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3732   SDValue Chain = Op.getOperand(0);
3733   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3734   SDValue LHS = Op.getOperand(2);
3735   SDValue RHS = Op.getOperand(3);
3736   SDValue Dest = Op.getOperand(4);
3737   SDLoc dl(Op);
3738
3739   bool LHSSeenZero = false;
3740   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3741   bool RHSSeenZero = false;
3742   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3743   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3744     // If unsafe fp math optimization is enabled and there are no other uses of
3745     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3746     // to an integer comparison.
3747     if (CC == ISD::SETOEQ)
3748       CC = ISD::SETEQ;
3749     else if (CC == ISD::SETUNE)
3750       CC = ISD::SETNE;
3751
3752     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3753     SDValue ARMcc;
3754     if (LHS.getValueType() == MVT::f32) {
3755       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3756                         bitcastf32Toi32(LHS, DAG), Mask);
3757       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3758                         bitcastf32Toi32(RHS, DAG), Mask);
3759       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3760       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3761       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3762                          Chain, Dest, ARMcc, CCR, Cmp);
3763     }
3764
3765     SDValue LHS1, LHS2;
3766     SDValue RHS1, RHS2;
3767     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3768     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3769     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3770     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3771     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3772     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3773     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3774     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3775     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3776   }
3777
3778   return SDValue();
3779 }
3780
3781 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3782   SDValue Chain = Op.getOperand(0);
3783   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3784   SDValue LHS = Op.getOperand(2);
3785   SDValue RHS = Op.getOperand(3);
3786   SDValue Dest = Op.getOperand(4);
3787   SDLoc dl(Op);
3788
3789   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3790     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3791                                                     dl);
3792
3793     // If softenSetCCOperands only returned one value, we should compare it to
3794     // zero.
3795     if (!RHS.getNode()) {
3796       RHS = DAG.getConstant(0, LHS.getValueType());
3797       CC = ISD::SETNE;
3798     }
3799   }
3800
3801   if (LHS.getValueType() == MVT::i32) {
3802     SDValue ARMcc;
3803     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3804     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3805     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3806                        Chain, Dest, ARMcc, CCR, Cmp);
3807   }
3808
3809   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3810
3811   if (getTargetMachine().Options.UnsafeFPMath &&
3812       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3813        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3814     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3815     if (Result.getNode())
3816       return Result;
3817   }
3818
3819   ARMCC::CondCodes CondCode, CondCode2;
3820   FPCCToARMCC(CC, CondCode, CondCode2);
3821
3822   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3823   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3824   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3825   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3826   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3827   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3828   if (CondCode2 != ARMCC::AL) {
3829     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3830     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3831     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3832   }
3833   return Res;
3834 }
3835
3836 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3837   SDValue Chain = Op.getOperand(0);
3838   SDValue Table = Op.getOperand(1);
3839   SDValue Index = Op.getOperand(2);
3840   SDLoc dl(Op);
3841
3842   EVT PTy = getPointerTy();
3843   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3844   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3845   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3846   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3847   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3848   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3849   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3850   if (Subtarget->isThumb2()) {
3851     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3852     // which does another jump to the destination. This also makes it easier
3853     // to translate it to TBB / TBH later.
3854     // FIXME: This might not work if the function is extremely large.
3855     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3856                        Addr, Op.getOperand(2), JTI, UId);
3857   }
3858   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3859     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3860                        MachinePointerInfo::getJumpTable(),
3861                        false, false, false, 0);
3862     Chain = Addr.getValue(1);
3863     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3864     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3865   } else {
3866     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3867                        MachinePointerInfo::getJumpTable(),
3868                        false, false, false, 0);
3869     Chain = Addr.getValue(1);
3870     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3871   }
3872 }
3873
3874 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3875   EVT VT = Op.getValueType();
3876   SDLoc dl(Op);
3877
3878   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3879     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3880       return Op;
3881     return DAG.UnrollVectorOp(Op.getNode());
3882   }
3883
3884   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3885          "Invalid type for custom lowering!");
3886   if (VT != MVT::v4i16)
3887     return DAG.UnrollVectorOp(Op.getNode());
3888
3889   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3890   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3891 }
3892
3893 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3894   EVT VT = Op.getValueType();
3895   if (VT.isVector())
3896     return LowerVectorFP_TO_INT(Op, DAG);
3897
3898   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3899     RTLIB::Libcall LC;
3900     if (Op.getOpcode() == ISD::FP_TO_SINT)
3901       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3902                               Op.getValueType());
3903     else
3904       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3905                               Op.getValueType());
3906     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3907                        /*isSigned*/ false, SDLoc(Op)).first;
3908   }
3909
3910   SDLoc dl(Op);
3911   unsigned Opc;
3912
3913   switch (Op.getOpcode()) {
3914   default: llvm_unreachable("Invalid opcode!");
3915   case ISD::FP_TO_SINT:
3916     Opc = ARMISD::FTOSI;
3917     break;
3918   case ISD::FP_TO_UINT:
3919     Opc = ARMISD::FTOUI;
3920     break;
3921   }
3922   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3923   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3924 }
3925
3926 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3927   EVT VT = Op.getValueType();
3928   SDLoc dl(Op);
3929
3930   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3931     if (VT.getVectorElementType() == MVT::f32)
3932       return Op;
3933     return DAG.UnrollVectorOp(Op.getNode());
3934   }
3935
3936   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3937          "Invalid type for custom lowering!");
3938   if (VT != MVT::v4f32)
3939     return DAG.UnrollVectorOp(Op.getNode());
3940
3941   unsigned CastOpc;
3942   unsigned Opc;
3943   switch (Op.getOpcode()) {
3944   default: llvm_unreachable("Invalid opcode!");
3945   case ISD::SINT_TO_FP:
3946     CastOpc = ISD::SIGN_EXTEND;
3947     Opc = ISD::SINT_TO_FP;
3948     break;
3949   case ISD::UINT_TO_FP:
3950     CastOpc = ISD::ZERO_EXTEND;
3951     Opc = ISD::UINT_TO_FP;
3952     break;
3953   }
3954
3955   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3956   return DAG.getNode(Opc, dl, VT, Op);
3957 }
3958
3959 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3960   EVT VT = Op.getValueType();
3961   if (VT.isVector())
3962     return LowerVectorINT_TO_FP(Op, DAG);
3963
3964   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3965     RTLIB::Libcall LC;
3966     if (Op.getOpcode() == ISD::SINT_TO_FP)
3967       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3968                               Op.getValueType());
3969     else
3970       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3971                               Op.getValueType());
3972     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3973                        /*isSigned*/ false, SDLoc(Op)).first;
3974   }
3975
3976   SDLoc dl(Op);
3977   unsigned Opc;
3978
3979   switch (Op.getOpcode()) {
3980   default: llvm_unreachable("Invalid opcode!");
3981   case ISD::SINT_TO_FP:
3982     Opc = ARMISD::SITOF;
3983     break;
3984   case ISD::UINT_TO_FP:
3985     Opc = ARMISD::UITOF;
3986     break;
3987   }
3988
3989   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3990   return DAG.getNode(Opc, dl, VT, Op);
3991 }
3992
3993 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3994   // Implement fcopysign with a fabs and a conditional fneg.
3995   SDValue Tmp0 = Op.getOperand(0);
3996   SDValue Tmp1 = Op.getOperand(1);
3997   SDLoc dl(Op);
3998   EVT VT = Op.getValueType();
3999   EVT SrcVT = Tmp1.getValueType();
4000   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4001     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4002   bool UseNEON = !InGPR && Subtarget->hasNEON();
4003
4004   if (UseNEON) {
4005     // Use VBSL to copy the sign bit.
4006     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4007     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4008                                DAG.getTargetConstant(EncodedVal, MVT::i32));
4009     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4010     if (VT == MVT::f64)
4011       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4012                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4013                          DAG.getConstant(32, MVT::i32));
4014     else /*if (VT == MVT::f32)*/
4015       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4016     if (SrcVT == MVT::f32) {
4017       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4018       if (VT == MVT::f64)
4019         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4020                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4021                            DAG.getConstant(32, MVT::i32));
4022     } else if (VT == MVT::f32)
4023       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4024                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4025                          DAG.getConstant(32, MVT::i32));
4026     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4027     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4028
4029     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4030                                             MVT::i32);
4031     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4032     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4033                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4034
4035     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4036                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4037                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4038     if (VT == MVT::f32) {
4039       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4040       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4041                         DAG.getConstant(0, MVT::i32));
4042     } else {
4043       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4044     }
4045
4046     return Res;
4047   }
4048
4049   // Bitcast operand 1 to i32.
4050   if (SrcVT == MVT::f64)
4051     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4052                        Tmp1).getValue(1);
4053   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4054
4055   // Or in the signbit with integer operations.
4056   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4057   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4058   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4059   if (VT == MVT::f32) {
4060     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4061                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4062     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4063                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4064   }
4065
4066   // f64: Or the high part with signbit and then combine two parts.
4067   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4068                      Tmp0);
4069   SDValue Lo = Tmp0.getValue(0);
4070   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4071   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4072   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4073 }
4074
4075 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4076   MachineFunction &MF = DAG.getMachineFunction();
4077   MachineFrameInfo *MFI = MF.getFrameInfo();
4078   MFI->setReturnAddressIsTaken(true);
4079
4080   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4081     return SDValue();
4082
4083   EVT VT = Op.getValueType();
4084   SDLoc dl(Op);
4085   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4086   if (Depth) {
4087     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4088     SDValue Offset = DAG.getConstant(4, MVT::i32);
4089     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4090                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4091                        MachinePointerInfo(), false, false, false, 0);
4092   }
4093
4094   // Return LR, which contains the return address. Mark it an implicit live-in.
4095   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4096   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4097 }
4098
4099 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4100   const ARMBaseRegisterInfo &ARI =
4101     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4102   MachineFunction &MF = DAG.getMachineFunction();
4103   MachineFrameInfo *MFI = MF.getFrameInfo();
4104   MFI->setFrameAddressIsTaken(true);
4105
4106   EVT VT = Op.getValueType();
4107   SDLoc dl(Op);  // FIXME probably not meaningful
4108   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4109   unsigned FrameReg = ARI.getFrameRegister(MF);
4110   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4111   while (Depth--)
4112     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4113                             MachinePointerInfo(),
4114                             false, false, false, 0);
4115   return FrameAddr;
4116 }
4117
4118 // FIXME? Maybe this could be a TableGen attribute on some registers and
4119 // this table could be generated automatically from RegInfo.
4120 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4121                                               EVT VT) const {
4122   unsigned Reg = StringSwitch<unsigned>(RegName)
4123                        .Case("sp", ARM::SP)
4124                        .Default(0);
4125   if (Reg)
4126     return Reg;
4127   report_fatal_error("Invalid register name global variable");
4128 }
4129
4130 /// ExpandBITCAST - If the target supports VFP, this function is called to
4131 /// expand a bit convert where either the source or destination type is i64 to
4132 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4133 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4134 /// vectors), since the legalizer won't know what to do with that.
4135 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4136   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4137   SDLoc dl(N);
4138   SDValue Op = N->getOperand(0);
4139
4140   // This function is only supposed to be called for i64 types, either as the
4141   // source or destination of the bit convert.
4142   EVT SrcVT = Op.getValueType();
4143   EVT DstVT = N->getValueType(0);
4144   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4145          "ExpandBITCAST called for non-i64 type");
4146
4147   // Turn i64->f64 into VMOVDRR.
4148   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4149     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4150                              DAG.getConstant(0, MVT::i32));
4151     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4152                              DAG.getConstant(1, MVT::i32));
4153     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4154                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4155   }
4156
4157   // Turn f64->i64 into VMOVRRD.
4158   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4159     SDValue Cvt;
4160     if (TLI.isBigEndian() && SrcVT.isVector() &&
4161         SrcVT.getVectorNumElements() > 1)
4162       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4163                         DAG.getVTList(MVT::i32, MVT::i32),
4164                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4165     else
4166       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4167                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4168     // Merge the pieces into a single i64 value.
4169     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4170   }
4171
4172   return SDValue();
4173 }
4174
4175 /// getZeroVector - Returns a vector of specified type with all zero elements.
4176 /// Zero vectors are used to represent vector negation and in those cases
4177 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4178 /// not support i64 elements, so sometimes the zero vectors will need to be
4179 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4180 /// zero vector.
4181 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4182   assert(VT.isVector() && "Expected a vector type");
4183   // The canonical modified immediate encoding of a zero vector is....0!
4184   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4185   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4186   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4187   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4188 }
4189
4190 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4191 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4192 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4193                                                 SelectionDAG &DAG) const {
4194   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4195   EVT VT = Op.getValueType();
4196   unsigned VTBits = VT.getSizeInBits();
4197   SDLoc dl(Op);
4198   SDValue ShOpLo = Op.getOperand(0);
4199   SDValue ShOpHi = Op.getOperand(1);
4200   SDValue ShAmt  = Op.getOperand(2);
4201   SDValue ARMcc;
4202   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4203
4204   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4205
4206   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4207                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4208   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4209   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4210                                    DAG.getConstant(VTBits, MVT::i32));
4211   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4212   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4213   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4214
4215   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4216   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4217                           ARMcc, DAG, dl);
4218   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4219   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4220                            CCR, Cmp);
4221
4222   SDValue Ops[2] = { Lo, Hi };
4223   return DAG.getMergeValues(Ops, dl);
4224 }
4225
4226 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4227 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4228 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4229                                                SelectionDAG &DAG) const {
4230   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4231   EVT VT = Op.getValueType();
4232   unsigned VTBits = VT.getSizeInBits();
4233   SDLoc dl(Op);
4234   SDValue ShOpLo = Op.getOperand(0);
4235   SDValue ShOpHi = Op.getOperand(1);
4236   SDValue ShAmt  = Op.getOperand(2);
4237   SDValue ARMcc;
4238
4239   assert(Op.getOpcode() == ISD::SHL_PARTS);
4240   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4241                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4242   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4243   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4244                                    DAG.getConstant(VTBits, MVT::i32));
4245   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4246   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4247
4248   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4249   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4250   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4251                           ARMcc, DAG, dl);
4252   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4253   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4254                            CCR, Cmp);
4255
4256   SDValue Ops[2] = { Lo, Hi };
4257   return DAG.getMergeValues(Ops, dl);
4258 }
4259
4260 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4261                                             SelectionDAG &DAG) const {
4262   // The rounding mode is in bits 23:22 of the FPSCR.
4263   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4264   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4265   // so that the shift + and get folded into a bitfield extract.
4266   SDLoc dl(Op);
4267   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4268                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4269                                               MVT::i32));
4270   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4271                                   DAG.getConstant(1U << 22, MVT::i32));
4272   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4273                               DAG.getConstant(22, MVT::i32));
4274   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4275                      DAG.getConstant(3, MVT::i32));
4276 }
4277
4278 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4279                          const ARMSubtarget *ST) {
4280   EVT VT = N->getValueType(0);
4281   SDLoc dl(N);
4282
4283   if (!ST->hasV6T2Ops())
4284     return SDValue();
4285
4286   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4287   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4288 }
4289
4290 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4291 /// for each 16-bit element from operand, repeated.  The basic idea is to
4292 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4293 ///
4294 /// Trace for v4i16:
4295 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4296 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4297 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4298 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4299 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4300 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4301 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4302 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4303 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4304   EVT VT = N->getValueType(0);
4305   SDLoc DL(N);
4306
4307   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4308   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4309   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4310   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4311   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4312   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4313 }
4314
4315 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4316 /// bit-count for each 16-bit element from the operand.  We need slightly
4317 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4318 /// 64/128-bit registers.
4319 ///
4320 /// Trace for v4i16:
4321 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4322 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4323 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4324 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4325 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4326   EVT VT = N->getValueType(0);
4327   SDLoc DL(N);
4328
4329   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4330   if (VT.is64BitVector()) {
4331     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4332     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4333                        DAG.getIntPtrConstant(0));
4334   } else {
4335     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4336                                     BitCounts, DAG.getIntPtrConstant(0));
4337     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4338   }
4339 }
4340
4341 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4342 /// bit-count for each 32-bit element from the operand.  The idea here is
4343 /// to split the vector into 16-bit elements, leverage the 16-bit count
4344 /// routine, and then combine the results.
4345 ///
4346 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4347 /// input    = [v0    v1    ] (vi: 32-bit elements)
4348 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4349 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4350 /// vrev: N0 = [k1 k0 k3 k2 ]
4351 ///            [k0 k1 k2 k3 ]
4352 ///       N1 =+[k1 k0 k3 k2 ]
4353 ///            [k0 k2 k1 k3 ]
4354 ///       N2 =+[k1 k3 k0 k2 ]
4355 ///            [k0    k2    k1    k3    ]
4356 /// Extended =+[k1    k3    k0    k2    ]
4357 ///            [k0    k2    ]
4358 /// Extracted=+[k1    k3    ]
4359 ///
4360 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4361   EVT VT = N->getValueType(0);
4362   SDLoc DL(N);
4363
4364   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4365
4366   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4367   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4368   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4369   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4370   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4371
4372   if (VT.is64BitVector()) {
4373     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4374     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4375                        DAG.getIntPtrConstant(0));
4376   } else {
4377     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4378                                     DAG.getIntPtrConstant(0));
4379     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4380   }
4381 }
4382
4383 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4384                           const ARMSubtarget *ST) {
4385   EVT VT = N->getValueType(0);
4386
4387   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4388   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4389           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4390          "Unexpected type for custom ctpop lowering");
4391
4392   if (VT.getVectorElementType() == MVT::i32)
4393     return lowerCTPOP32BitElements(N, DAG);
4394   else
4395     return lowerCTPOP16BitElements(N, DAG);
4396 }
4397
4398 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4399                           const ARMSubtarget *ST) {
4400   EVT VT = N->getValueType(0);
4401   SDLoc dl(N);
4402
4403   if (!VT.isVector())
4404     return SDValue();
4405
4406   // Lower vector shifts on NEON to use VSHL.
4407   assert(ST->hasNEON() && "unexpected vector shift");
4408
4409   // Left shifts translate directly to the vshiftu intrinsic.
4410   if (N->getOpcode() == ISD::SHL)
4411     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4412                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4413                        N->getOperand(0), N->getOperand(1));
4414
4415   assert((N->getOpcode() == ISD::SRA ||
4416           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4417
4418   // NEON uses the same intrinsics for both left and right shifts.  For
4419   // right shifts, the shift amounts are negative, so negate the vector of
4420   // shift amounts.
4421   EVT ShiftVT = N->getOperand(1).getValueType();
4422   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4423                                      getZeroVector(ShiftVT, DAG, dl),
4424                                      N->getOperand(1));
4425   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4426                              Intrinsic::arm_neon_vshifts :
4427                              Intrinsic::arm_neon_vshiftu);
4428   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4429                      DAG.getConstant(vshiftInt, MVT::i32),
4430                      N->getOperand(0), NegatedCount);
4431 }
4432
4433 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4434                                 const ARMSubtarget *ST) {
4435   EVT VT = N->getValueType(0);
4436   SDLoc dl(N);
4437
4438   // We can get here for a node like i32 = ISD::SHL i32, i64
4439   if (VT != MVT::i64)
4440     return SDValue();
4441
4442   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4443          "Unknown shift to lower!");
4444
4445   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4446   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4447       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4448     return SDValue();
4449
4450   // If we are in thumb mode, we don't have RRX.
4451   if (ST->isThumb1Only()) return SDValue();
4452
4453   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4454   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4455                            DAG.getConstant(0, MVT::i32));
4456   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4457                            DAG.getConstant(1, MVT::i32));
4458
4459   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4460   // captures the result into a carry flag.
4461   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4462   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4463
4464   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4465   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4466
4467   // Merge the pieces into a single i64 value.
4468  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4469 }
4470
4471 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4472   SDValue TmpOp0, TmpOp1;
4473   bool Invert = false;
4474   bool Swap = false;
4475   unsigned Opc = 0;
4476
4477   SDValue Op0 = Op.getOperand(0);
4478   SDValue Op1 = Op.getOperand(1);
4479   SDValue CC = Op.getOperand(2);
4480   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4481   EVT VT = Op.getValueType();
4482   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4483   SDLoc dl(Op);
4484
4485   if (Op1.getValueType().isFloatingPoint()) {
4486     switch (SetCCOpcode) {
4487     default: llvm_unreachable("Illegal FP comparison");
4488     case ISD::SETUNE:
4489     case ISD::SETNE:  Invert = true; // Fallthrough
4490     case ISD::SETOEQ:
4491     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4492     case ISD::SETOLT:
4493     case ISD::SETLT: Swap = true; // Fallthrough
4494     case ISD::SETOGT:
4495     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4496     case ISD::SETOLE:
4497     case ISD::SETLE:  Swap = true; // Fallthrough
4498     case ISD::SETOGE:
4499     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4500     case ISD::SETUGE: Swap = true; // Fallthrough
4501     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4502     case ISD::SETUGT: Swap = true; // Fallthrough
4503     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4504     case ISD::SETUEQ: Invert = true; // Fallthrough
4505     case ISD::SETONE:
4506       // Expand this to (OLT | OGT).
4507       TmpOp0 = Op0;
4508       TmpOp1 = Op1;
4509       Opc = ISD::OR;
4510       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4511       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4512       break;
4513     case ISD::SETUO: Invert = true; // Fallthrough
4514     case ISD::SETO:
4515       // Expand this to (OLT | OGE).
4516       TmpOp0 = Op0;
4517       TmpOp1 = Op1;
4518       Opc = ISD::OR;
4519       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4520       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4521       break;
4522     }
4523   } else {
4524     // Integer comparisons.
4525     switch (SetCCOpcode) {
4526     default: llvm_unreachable("Illegal integer comparison");
4527     case ISD::SETNE:  Invert = true;
4528     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4529     case ISD::SETLT:  Swap = true;
4530     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4531     case ISD::SETLE:  Swap = true;
4532     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4533     case ISD::SETULT: Swap = true;
4534     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4535     case ISD::SETULE: Swap = true;
4536     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4537     }
4538
4539     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4540     if (Opc == ARMISD::VCEQ) {
4541
4542       SDValue AndOp;
4543       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4544         AndOp = Op0;
4545       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4546         AndOp = Op1;
4547
4548       // Ignore bitconvert.
4549       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4550         AndOp = AndOp.getOperand(0);
4551
4552       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4553         Opc = ARMISD::VTST;
4554         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4555         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4556         Invert = !Invert;
4557       }
4558     }
4559   }
4560
4561   if (Swap)
4562     std::swap(Op0, Op1);
4563
4564   // If one of the operands is a constant vector zero, attempt to fold the
4565   // comparison to a specialized compare-against-zero form.
4566   SDValue SingleOp;
4567   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4568     SingleOp = Op0;
4569   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4570     if (Opc == ARMISD::VCGE)
4571       Opc = ARMISD::VCLEZ;
4572     else if (Opc == ARMISD::VCGT)
4573       Opc = ARMISD::VCLTZ;
4574     SingleOp = Op1;
4575   }
4576
4577   SDValue Result;
4578   if (SingleOp.getNode()) {
4579     switch (Opc) {
4580     case ARMISD::VCEQ:
4581       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4582     case ARMISD::VCGE:
4583       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4584     case ARMISD::VCLEZ:
4585       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4586     case ARMISD::VCGT:
4587       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4588     case ARMISD::VCLTZ:
4589       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4590     default:
4591       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4592     }
4593   } else {
4594      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4595   }
4596
4597   Result = DAG.getSExtOrTrunc(Result, dl, VT);
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()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7152         Subtarget->hasNEON()) {
7153       if ((Align % 16 == 0) && SizeVal >= 16)
7154         UnitSize = 16;
7155       else if ((Align % 8 == 0) && SizeVal >= 8)
7156         UnitSize = 8;
7157     }
7158     // Can't use NEON instructions.
7159     if (UnitSize == 0)
7160       UnitSize = 4;
7161   }
7162
7163   // Select the correct opcode and register class for unit size load/store
7164   bool IsNeon = UnitSize >= 8;
7165   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7166   if (IsNeon)
7167     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7168                             : UnitSize == 8 ? &ARM::DPRRegClass
7169                                             : nullptr;
7170
7171   unsigned BytesLeft = SizeVal % UnitSize;
7172   unsigned LoopSize = SizeVal - BytesLeft;
7173
7174   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7175     // Use LDR and STR to copy.
7176     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7177     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7178     unsigned srcIn = src;
7179     unsigned destIn = dest;
7180     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7181       unsigned srcOut = MRI.createVirtualRegister(TRC);
7182       unsigned destOut = MRI.createVirtualRegister(TRC);
7183       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7184       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7185                  IsThumb1, IsThumb2);
7186       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7187                  IsThumb1, IsThumb2);
7188       srcIn = srcOut;
7189       destIn = destOut;
7190     }
7191
7192     // Handle the leftover bytes with LDRB and STRB.
7193     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7194     // [destOut] = STRB_POST(scratch, destIn, 1)
7195     for (unsigned i = 0; i < BytesLeft; i++) {
7196       unsigned srcOut = MRI.createVirtualRegister(TRC);
7197       unsigned destOut = MRI.createVirtualRegister(TRC);
7198       unsigned scratch = MRI.createVirtualRegister(TRC);
7199       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7200                  IsThumb1, IsThumb2);
7201       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7202                  IsThumb1, IsThumb2);
7203       srcIn = srcOut;
7204       destIn = destOut;
7205     }
7206     MI->eraseFromParent();   // The instruction is gone now.
7207     return BB;
7208   }
7209
7210   // Expand the pseudo op to a loop.
7211   // thisMBB:
7212   //   ...
7213   //   movw varEnd, # --> with thumb2
7214   //   movt varEnd, #
7215   //   ldrcp varEnd, idx --> without thumb2
7216   //   fallthrough --> loopMBB
7217   // loopMBB:
7218   //   PHI varPhi, varEnd, varLoop
7219   //   PHI srcPhi, src, srcLoop
7220   //   PHI destPhi, dst, destLoop
7221   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7222   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7223   //   subs varLoop, varPhi, #UnitSize
7224   //   bne loopMBB
7225   //   fallthrough --> exitMBB
7226   // exitMBB:
7227   //   epilogue to handle left-over bytes
7228   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7229   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7230   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7231   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7232   MF->insert(It, loopMBB);
7233   MF->insert(It, exitMBB);
7234
7235   // Transfer the remainder of BB and its successor edges to exitMBB.
7236   exitMBB->splice(exitMBB->begin(), BB,
7237                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7238   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7239
7240   // Load an immediate to varEnd.
7241   unsigned varEnd = MRI.createVirtualRegister(TRC);
7242   if (IsThumb2) {
7243     unsigned Vtmp = varEnd;
7244     if ((LoopSize & 0xFFFF0000) != 0)
7245       Vtmp = MRI.createVirtualRegister(TRC);
7246     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7247                        .addImm(LoopSize & 0xFFFF));
7248
7249     if ((LoopSize & 0xFFFF0000) != 0)
7250       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7251                          .addReg(Vtmp).addImm(LoopSize >> 16));
7252   } else {
7253     MachineConstantPool *ConstantPool = MF->getConstantPool();
7254     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7255     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7256
7257     // MachineConstantPool wants an explicit alignment.
7258     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7259     if (Align == 0)
7260       Align = getDataLayout()->getTypeAllocSize(C->getType());
7261     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7262
7263     if (IsThumb1)
7264       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7265           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7266     else
7267       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7268           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7269   }
7270   BB->addSuccessor(loopMBB);
7271
7272   // Generate the loop body:
7273   //   varPhi = PHI(varLoop, varEnd)
7274   //   srcPhi = PHI(srcLoop, src)
7275   //   destPhi = PHI(destLoop, dst)
7276   MachineBasicBlock *entryBB = BB;
7277   BB = loopMBB;
7278   unsigned varLoop = MRI.createVirtualRegister(TRC);
7279   unsigned varPhi = MRI.createVirtualRegister(TRC);
7280   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7281   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7282   unsigned destLoop = MRI.createVirtualRegister(TRC);
7283   unsigned destPhi = MRI.createVirtualRegister(TRC);
7284
7285   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7286     .addReg(varLoop).addMBB(loopMBB)
7287     .addReg(varEnd).addMBB(entryBB);
7288   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7289     .addReg(srcLoop).addMBB(loopMBB)
7290     .addReg(src).addMBB(entryBB);
7291   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7292     .addReg(destLoop).addMBB(loopMBB)
7293     .addReg(dest).addMBB(entryBB);
7294
7295   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7296   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7297   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7298   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7299              IsThumb1, IsThumb2);
7300   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7301              IsThumb1, IsThumb2);
7302
7303   // Decrement loop variable by UnitSize.
7304   if (IsThumb1) {
7305     MachineInstrBuilder MIB =
7306         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7307     MIB = AddDefaultT1CC(MIB);
7308     MIB.addReg(varPhi).addImm(UnitSize);
7309     AddDefaultPred(MIB);
7310   } else {
7311     MachineInstrBuilder MIB =
7312         BuildMI(*BB, BB->end(), dl,
7313                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7314     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7315     MIB->getOperand(5).setReg(ARM::CPSR);
7316     MIB->getOperand(5).setIsDef(true);
7317   }
7318   BuildMI(*BB, BB->end(), dl,
7319           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7320       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7321
7322   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7323   BB->addSuccessor(loopMBB);
7324   BB->addSuccessor(exitMBB);
7325
7326   // Add epilogue to handle BytesLeft.
7327   BB = exitMBB;
7328   MachineInstr *StartOfExit = exitMBB->begin();
7329
7330   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7331   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7332   unsigned srcIn = srcLoop;
7333   unsigned destIn = destLoop;
7334   for (unsigned i = 0; i < BytesLeft; i++) {
7335     unsigned srcOut = MRI.createVirtualRegister(TRC);
7336     unsigned destOut = MRI.createVirtualRegister(TRC);
7337     unsigned scratch = MRI.createVirtualRegister(TRC);
7338     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7339                IsThumb1, IsThumb2);
7340     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7341                IsThumb1, IsThumb2);
7342     srcIn = srcOut;
7343     destIn = destOut;
7344   }
7345
7346   MI->eraseFromParent();   // The instruction is gone now.
7347   return BB;
7348 }
7349
7350 MachineBasicBlock *
7351 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7352                                        MachineBasicBlock *MBB) const {
7353   const TargetMachine &TM = getTargetMachine();
7354   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7355   DebugLoc DL = MI->getDebugLoc();
7356
7357   assert(Subtarget->isTargetWindows() &&
7358          "__chkstk is only supported on Windows");
7359   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7360
7361   // __chkstk takes the number of words to allocate on the stack in R4, and
7362   // returns the stack adjustment in number of bytes in R4.  This will not
7363   // clober any other registers (other than the obvious lr).
7364   //
7365   // Although, technically, IP should be considered a register which may be
7366   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7367   // thumb-2 environment, so there is no interworking required.  As a result, we
7368   // do not expect a veneer to be emitted by the linker, clobbering IP.
7369   //
7370   // Each module receives its own copy of __chkstk, so no import thunk is
7371   // required, again, ensuring that IP is not clobbered.
7372   //
7373   // Finally, although some linkers may theoretically provide a trampoline for
7374   // out of range calls (which is quite common due to a 32M range limitation of
7375   // branches for Thumb), we can generate the long-call version via
7376   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7377   // IP.
7378
7379   switch (TM.getCodeModel()) {
7380   case CodeModel::Small:
7381   case CodeModel::Medium:
7382   case CodeModel::Default:
7383   case CodeModel::Kernel:
7384     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7385       .addImm((unsigned)ARMCC::AL).addReg(0)
7386       .addExternalSymbol("__chkstk")
7387       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7388       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7389       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7390     break;
7391   case CodeModel::Large:
7392   case CodeModel::JITDefault: {
7393     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7394     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7395
7396     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7397       .addExternalSymbol("__chkstk");
7398     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7399       .addImm((unsigned)ARMCC::AL).addReg(0)
7400       .addReg(Reg, RegState::Kill)
7401       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7402       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7403       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7404     break;
7405   }
7406   }
7407
7408   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7409                                       ARM::SP)
7410                               .addReg(ARM::SP).addReg(ARM::R4)));
7411
7412   MI->eraseFromParent();
7413   return MBB;
7414 }
7415
7416 MachineBasicBlock *
7417 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7418                                                MachineBasicBlock *BB) const {
7419   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7420   DebugLoc dl = MI->getDebugLoc();
7421   bool isThumb2 = Subtarget->isThumb2();
7422   switch (MI->getOpcode()) {
7423   default: {
7424     MI->dump();
7425     llvm_unreachable("Unexpected instr type to insert");
7426   }
7427   // The Thumb2 pre-indexed stores have the same MI operands, they just
7428   // define them differently in the .td files from the isel patterns, so
7429   // they need pseudos.
7430   case ARM::t2STR_preidx:
7431     MI->setDesc(TII->get(ARM::t2STR_PRE));
7432     return BB;
7433   case ARM::t2STRB_preidx:
7434     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7435     return BB;
7436   case ARM::t2STRH_preidx:
7437     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7438     return BB;
7439
7440   case ARM::STRi_preidx:
7441   case ARM::STRBi_preidx: {
7442     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7443       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7444     // Decode the offset.
7445     unsigned Offset = MI->getOperand(4).getImm();
7446     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7447     Offset = ARM_AM::getAM2Offset(Offset);
7448     if (isSub)
7449       Offset = -Offset;
7450
7451     MachineMemOperand *MMO = *MI->memoperands_begin();
7452     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7453       .addOperand(MI->getOperand(0))  // Rn_wb
7454       .addOperand(MI->getOperand(1))  // Rt
7455       .addOperand(MI->getOperand(2))  // Rn
7456       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7457       .addOperand(MI->getOperand(5))  // pred
7458       .addOperand(MI->getOperand(6))
7459       .addMemOperand(MMO);
7460     MI->eraseFromParent();
7461     return BB;
7462   }
7463   case ARM::STRr_preidx:
7464   case ARM::STRBr_preidx:
7465   case ARM::STRH_preidx: {
7466     unsigned NewOpc;
7467     switch (MI->getOpcode()) {
7468     default: llvm_unreachable("unexpected opcode!");
7469     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7470     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7471     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7472     }
7473     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7474     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7475       MIB.addOperand(MI->getOperand(i));
7476     MI->eraseFromParent();
7477     return BB;
7478   }
7479
7480   case ARM::tMOVCCr_pseudo: {
7481     // To "insert" a SELECT_CC instruction, we actually have to insert the
7482     // diamond control-flow pattern.  The incoming instruction knows the
7483     // destination vreg to set, the condition code register to branch on, the
7484     // true/false values to select between, and a branch opcode to use.
7485     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7486     MachineFunction::iterator It = BB;
7487     ++It;
7488
7489     //  thisMBB:
7490     //  ...
7491     //   TrueVal = ...
7492     //   cmpTY ccX, r1, r2
7493     //   bCC copy1MBB
7494     //   fallthrough --> copy0MBB
7495     MachineBasicBlock *thisMBB  = BB;
7496     MachineFunction *F = BB->getParent();
7497     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7498     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7499     F->insert(It, copy0MBB);
7500     F->insert(It, sinkMBB);
7501
7502     // Transfer the remainder of BB and its successor edges to sinkMBB.
7503     sinkMBB->splice(sinkMBB->begin(), BB,
7504                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7505     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7506
7507     BB->addSuccessor(copy0MBB);
7508     BB->addSuccessor(sinkMBB);
7509
7510     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7511       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7512
7513     //  copy0MBB:
7514     //   %FalseValue = ...
7515     //   # fallthrough to sinkMBB
7516     BB = copy0MBB;
7517
7518     // Update machine-CFG edges
7519     BB->addSuccessor(sinkMBB);
7520
7521     //  sinkMBB:
7522     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7523     //  ...
7524     BB = sinkMBB;
7525     BuildMI(*BB, BB->begin(), dl,
7526             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7527       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7528       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7529
7530     MI->eraseFromParent();   // The pseudo instruction is gone now.
7531     return BB;
7532   }
7533
7534   case ARM::BCCi64:
7535   case ARM::BCCZi64: {
7536     // If there is an unconditional branch to the other successor, remove it.
7537     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7538
7539     // Compare both parts that make up the double comparison separately for
7540     // equality.
7541     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7542
7543     unsigned LHS1 = MI->getOperand(1).getReg();
7544     unsigned LHS2 = MI->getOperand(2).getReg();
7545     if (RHSisZero) {
7546       AddDefaultPred(BuildMI(BB, dl,
7547                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7548                      .addReg(LHS1).addImm(0));
7549       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7550         .addReg(LHS2).addImm(0)
7551         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7552     } else {
7553       unsigned RHS1 = MI->getOperand(3).getReg();
7554       unsigned RHS2 = MI->getOperand(4).getReg();
7555       AddDefaultPred(BuildMI(BB, dl,
7556                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7557                      .addReg(LHS1).addReg(RHS1));
7558       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7559         .addReg(LHS2).addReg(RHS2)
7560         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7561     }
7562
7563     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7564     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7565     if (MI->getOperand(0).getImm() == ARMCC::NE)
7566       std::swap(destMBB, exitMBB);
7567
7568     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7569       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7570     if (isThumb2)
7571       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7572     else
7573       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7574
7575     MI->eraseFromParent();   // The pseudo instruction is gone now.
7576     return BB;
7577   }
7578
7579   case ARM::Int_eh_sjlj_setjmp:
7580   case ARM::Int_eh_sjlj_setjmp_nofp:
7581   case ARM::tInt_eh_sjlj_setjmp:
7582   case ARM::t2Int_eh_sjlj_setjmp:
7583   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7584     EmitSjLjDispatchBlock(MI, BB);
7585     return BB;
7586
7587   case ARM::ABS:
7588   case ARM::t2ABS: {
7589     // To insert an ABS instruction, we have to insert the
7590     // diamond control-flow pattern.  The incoming instruction knows the
7591     // source vreg to test against 0, the destination vreg to set,
7592     // the condition code register to branch on, the
7593     // true/false values to select between, and a branch opcode to use.
7594     // It transforms
7595     //     V1 = ABS V0
7596     // into
7597     //     V2 = MOVS V0
7598     //     BCC                      (branch to SinkBB if V0 >= 0)
7599     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7600     //     SinkBB: V1 = PHI(V2, V3)
7601     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7602     MachineFunction::iterator BBI = BB;
7603     ++BBI;
7604     MachineFunction *Fn = BB->getParent();
7605     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7606     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7607     Fn->insert(BBI, RSBBB);
7608     Fn->insert(BBI, SinkBB);
7609
7610     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7611     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7612     bool isThumb2 = Subtarget->isThumb2();
7613     MachineRegisterInfo &MRI = Fn->getRegInfo();
7614     // In Thumb mode S must not be specified if source register is the SP or
7615     // PC and if destination register is the SP, so restrict register class
7616     unsigned NewRsbDstReg =
7617       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7618
7619     // Transfer the remainder of BB and its successor edges to sinkMBB.
7620     SinkBB->splice(SinkBB->begin(), BB,
7621                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7622     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7623
7624     BB->addSuccessor(RSBBB);
7625     BB->addSuccessor(SinkBB);
7626
7627     // fall through to SinkMBB
7628     RSBBB->addSuccessor(SinkBB);
7629
7630     // insert a cmp at the end of BB
7631     AddDefaultPred(BuildMI(BB, dl,
7632                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7633                    .addReg(ABSSrcReg).addImm(0));
7634
7635     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7636     BuildMI(BB, dl,
7637       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7638       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7639
7640     // insert rsbri in RSBBB
7641     // Note: BCC and rsbri will be converted into predicated rsbmi
7642     // by if-conversion pass
7643     BuildMI(*RSBBB, RSBBB->begin(), dl,
7644       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7645       .addReg(ABSSrcReg, RegState::Kill)
7646       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7647
7648     // insert PHI in SinkBB,
7649     // reuse ABSDstReg to not change uses of ABS instruction
7650     BuildMI(*SinkBB, SinkBB->begin(), dl,
7651       TII->get(ARM::PHI), ABSDstReg)
7652       .addReg(NewRsbDstReg).addMBB(RSBBB)
7653       .addReg(ABSSrcReg).addMBB(BB);
7654
7655     // remove ABS instruction
7656     MI->eraseFromParent();
7657
7658     // return last added BB
7659     return SinkBB;
7660   }
7661   case ARM::COPY_STRUCT_BYVAL_I32:
7662     ++NumLoopByVals;
7663     return EmitStructByval(MI, BB);
7664   case ARM::WIN__CHKSTK:
7665     return EmitLowered__chkstk(MI, BB);
7666   }
7667 }
7668
7669 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7670                                                       SDNode *Node) const {
7671   const MCInstrDesc *MCID = &MI->getDesc();
7672   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7673   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7674   // operand is still set to noreg. If needed, set the optional operand's
7675   // register to CPSR, and remove the redundant implicit def.
7676   //
7677   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7678
7679   // Rename pseudo opcodes.
7680   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7681   if (NewOpc) {
7682     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7683     MCID = &TII->get(NewOpc);
7684
7685     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7686            "converted opcode should be the same except for cc_out");
7687
7688     MI->setDesc(*MCID);
7689
7690     // Add the optional cc_out operand
7691     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7692   }
7693   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7694
7695   // Any ARM instruction that sets the 's' bit should specify an optional
7696   // "cc_out" operand in the last operand position.
7697   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7698     assert(!NewOpc && "Optional cc_out operand required");
7699     return;
7700   }
7701   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7702   // since we already have an optional CPSR def.
7703   bool definesCPSR = false;
7704   bool deadCPSR = false;
7705   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7706        i != e; ++i) {
7707     const MachineOperand &MO = MI->getOperand(i);
7708     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7709       definesCPSR = true;
7710       if (MO.isDead())
7711         deadCPSR = true;
7712       MI->RemoveOperand(i);
7713       break;
7714     }
7715   }
7716   if (!definesCPSR) {
7717     assert(!NewOpc && "Optional cc_out operand required");
7718     return;
7719   }
7720   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7721   if (deadCPSR) {
7722     assert(!MI->getOperand(ccOutIdx).getReg() &&
7723            "expect uninitialized optional cc_out operand");
7724     return;
7725   }
7726
7727   // If this instruction was defined with an optional CPSR def and its dag node
7728   // had a live implicit CPSR def, then activate the optional CPSR def.
7729   MachineOperand &MO = MI->getOperand(ccOutIdx);
7730   MO.setReg(ARM::CPSR);
7731   MO.setIsDef(true);
7732 }
7733
7734 //===----------------------------------------------------------------------===//
7735 //                           ARM Optimization Hooks
7736 //===----------------------------------------------------------------------===//
7737
7738 // Helper function that checks if N is a null or all ones constant.
7739 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7740   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7741   if (!C)
7742     return false;
7743   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7744 }
7745
7746 // Return true if N is conditionally 0 or all ones.
7747 // Detects these expressions where cc is an i1 value:
7748 //
7749 //   (select cc 0, y)   [AllOnes=0]
7750 //   (select cc y, 0)   [AllOnes=0]
7751 //   (zext cc)          [AllOnes=0]
7752 //   (sext cc)          [AllOnes=0/1]
7753 //   (select cc -1, y)  [AllOnes=1]
7754 //   (select cc y, -1)  [AllOnes=1]
7755 //
7756 // Invert is set when N is the null/all ones constant when CC is false.
7757 // OtherOp is set to the alternative value of N.
7758 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7759                                        SDValue &CC, bool &Invert,
7760                                        SDValue &OtherOp,
7761                                        SelectionDAG &DAG) {
7762   switch (N->getOpcode()) {
7763   default: return false;
7764   case ISD::SELECT: {
7765     CC = N->getOperand(0);
7766     SDValue N1 = N->getOperand(1);
7767     SDValue N2 = N->getOperand(2);
7768     if (isZeroOrAllOnes(N1, AllOnes)) {
7769       Invert = false;
7770       OtherOp = N2;
7771       return true;
7772     }
7773     if (isZeroOrAllOnes(N2, AllOnes)) {
7774       Invert = true;
7775       OtherOp = N1;
7776       return true;
7777     }
7778     return false;
7779   }
7780   case ISD::ZERO_EXTEND:
7781     // (zext cc) can never be the all ones value.
7782     if (AllOnes)
7783       return false;
7784     // Fall through.
7785   case ISD::SIGN_EXTEND: {
7786     EVT VT = N->getValueType(0);
7787     CC = N->getOperand(0);
7788     if (CC.getValueType() != MVT::i1)
7789       return false;
7790     Invert = !AllOnes;
7791     if (AllOnes)
7792       // When looking for an AllOnes constant, N is an sext, and the 'other'
7793       // value is 0.
7794       OtherOp = DAG.getConstant(0, VT);
7795     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7796       // When looking for a 0 constant, N can be zext or sext.
7797       OtherOp = DAG.getConstant(1, VT);
7798     else
7799       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7800     return true;
7801   }
7802   }
7803 }
7804
7805 // Combine a constant select operand into its use:
7806 //
7807 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7808 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7809 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7810 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7811 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7812 //
7813 // The transform is rejected if the select doesn't have a constant operand that
7814 // is null, or all ones when AllOnes is set.
7815 //
7816 // Also recognize sext/zext from i1:
7817 //
7818 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7819 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7820 //
7821 // These transformations eventually create predicated instructions.
7822 //
7823 // @param N       The node to transform.
7824 // @param Slct    The N operand that is a select.
7825 // @param OtherOp The other N operand (x above).
7826 // @param DCI     Context.
7827 // @param AllOnes Require the select constant to be all ones instead of null.
7828 // @returns The new node, or SDValue() on failure.
7829 static
7830 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7831                             TargetLowering::DAGCombinerInfo &DCI,
7832                             bool AllOnes = false) {
7833   SelectionDAG &DAG = DCI.DAG;
7834   EVT VT = N->getValueType(0);
7835   SDValue NonConstantVal;
7836   SDValue CCOp;
7837   bool SwapSelectOps;
7838   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7839                                   NonConstantVal, DAG))
7840     return SDValue();
7841
7842   // Slct is now know to be the desired identity constant when CC is true.
7843   SDValue TrueVal = OtherOp;
7844   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7845                                  OtherOp, NonConstantVal);
7846   // Unless SwapSelectOps says CC should be false.
7847   if (SwapSelectOps)
7848     std::swap(TrueVal, FalseVal);
7849
7850   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7851                      CCOp, TrueVal, FalseVal);
7852 }
7853
7854 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7855 static
7856 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7857                                        TargetLowering::DAGCombinerInfo &DCI) {
7858   SDValue N0 = N->getOperand(0);
7859   SDValue N1 = N->getOperand(1);
7860   if (N0.getNode()->hasOneUse()) {
7861     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7862     if (Result.getNode())
7863       return Result;
7864   }
7865   if (N1.getNode()->hasOneUse()) {
7866     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7867     if (Result.getNode())
7868       return Result;
7869   }
7870   return SDValue();
7871 }
7872
7873 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7874 // (only after legalization).
7875 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7876                                  TargetLowering::DAGCombinerInfo &DCI,
7877                                  const ARMSubtarget *Subtarget) {
7878
7879   // Only perform optimization if after legalize, and if NEON is available. We
7880   // also expected both operands to be BUILD_VECTORs.
7881   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7882       || N0.getOpcode() != ISD::BUILD_VECTOR
7883       || N1.getOpcode() != ISD::BUILD_VECTOR)
7884     return SDValue();
7885
7886   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7887   EVT VT = N->getValueType(0);
7888   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7889     return SDValue();
7890
7891   // Check that the vector operands are of the right form.
7892   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7893   // operands, where N is the size of the formed vector.
7894   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7895   // index such that we have a pair wise add pattern.
7896
7897   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7898   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7899     return SDValue();
7900   SDValue Vec = N0->getOperand(0)->getOperand(0);
7901   SDNode *V = Vec.getNode();
7902   unsigned nextIndex = 0;
7903
7904   // For each operands to the ADD which are BUILD_VECTORs,
7905   // check to see if each of their operands are an EXTRACT_VECTOR with
7906   // the same vector and appropriate index.
7907   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7908     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7909         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7910
7911       SDValue ExtVec0 = N0->getOperand(i);
7912       SDValue ExtVec1 = N1->getOperand(i);
7913
7914       // First operand is the vector, verify its the same.
7915       if (V != ExtVec0->getOperand(0).getNode() ||
7916           V != ExtVec1->getOperand(0).getNode())
7917         return SDValue();
7918
7919       // Second is the constant, verify its correct.
7920       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7921       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7922
7923       // For the constant, we want to see all the even or all the odd.
7924       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7925           || C1->getZExtValue() != nextIndex+1)
7926         return SDValue();
7927
7928       // Increment index.
7929       nextIndex+=2;
7930     } else
7931       return SDValue();
7932   }
7933
7934   // Create VPADDL node.
7935   SelectionDAG &DAG = DCI.DAG;
7936   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7937
7938   // Build operand list.
7939   SmallVector<SDValue, 8> Ops;
7940   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7941                                 TLI.getPointerTy()));
7942
7943   // Input is the vector.
7944   Ops.push_back(Vec);
7945
7946   // Get widened type and narrowed type.
7947   MVT widenType;
7948   unsigned numElem = VT.getVectorNumElements();
7949   
7950   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7951   switch (inputLaneType.getSimpleVT().SimpleTy) {
7952     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7953     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7954     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7955     default:
7956       llvm_unreachable("Invalid vector element type for padd optimization.");
7957   }
7958
7959   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7960   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7961   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7962 }
7963
7964 static SDValue findMUL_LOHI(SDValue V) {
7965   if (V->getOpcode() == ISD::UMUL_LOHI ||
7966       V->getOpcode() == ISD::SMUL_LOHI)
7967     return V;
7968   return SDValue();
7969 }
7970
7971 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7972                                      TargetLowering::DAGCombinerInfo &DCI,
7973                                      const ARMSubtarget *Subtarget) {
7974
7975   if (Subtarget->isThumb1Only()) return SDValue();
7976
7977   // Only perform the checks after legalize when the pattern is available.
7978   if (DCI.isBeforeLegalize()) return SDValue();
7979
7980   // Look for multiply add opportunities.
7981   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7982   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7983   // a glue link from the first add to the second add.
7984   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7985   // a S/UMLAL instruction.
7986   //          loAdd   UMUL_LOHI
7987   //            \    / :lo    \ :hi
7988   //             \  /          \          [no multiline comment]
7989   //              ADDC         |  hiAdd
7990   //                 \ :glue  /  /
7991   //                  \      /  /
7992   //                    ADDE
7993   //
7994   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7995   SDValue AddcOp0 = AddcNode->getOperand(0);
7996   SDValue AddcOp1 = AddcNode->getOperand(1);
7997
7998   // Check if the two operands are from the same mul_lohi node.
7999   if (AddcOp0.getNode() == AddcOp1.getNode())
8000     return SDValue();
8001
8002   assert(AddcNode->getNumValues() == 2 &&
8003          AddcNode->getValueType(0) == MVT::i32 &&
8004          "Expect ADDC with two result values. First: i32");
8005
8006   // Check that we have a glued ADDC node.
8007   if (AddcNode->getValueType(1) != MVT::Glue)
8008     return SDValue();
8009
8010   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8011   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8012       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8013       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8014       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8015     return SDValue();
8016
8017   // Look for the glued ADDE.
8018   SDNode* AddeNode = AddcNode->getGluedUser();
8019   if (!AddeNode)
8020     return SDValue();
8021
8022   // Make sure it is really an ADDE.
8023   if (AddeNode->getOpcode() != ISD::ADDE)
8024     return SDValue();
8025
8026   assert(AddeNode->getNumOperands() == 3 &&
8027          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8028          "ADDE node has the wrong inputs");
8029
8030   // Check for the triangle shape.
8031   SDValue AddeOp0 = AddeNode->getOperand(0);
8032   SDValue AddeOp1 = AddeNode->getOperand(1);
8033
8034   // Make sure that the ADDE operands are not coming from the same node.
8035   if (AddeOp0.getNode() == AddeOp1.getNode())
8036     return SDValue();
8037
8038   // Find the MUL_LOHI node walking up ADDE's operands.
8039   bool IsLeftOperandMUL = false;
8040   SDValue MULOp = findMUL_LOHI(AddeOp0);
8041   if (MULOp == SDValue())
8042    MULOp = findMUL_LOHI(AddeOp1);
8043   else
8044     IsLeftOperandMUL = true;
8045   if (MULOp == SDValue())
8046     return SDValue();
8047
8048   // Figure out the right opcode.
8049   unsigned Opc = MULOp->getOpcode();
8050   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8051
8052   // Figure out the high and low input values to the MLAL node.
8053   SDValue* HiAdd = nullptr;
8054   SDValue* LoMul = nullptr;
8055   SDValue* LowAdd = nullptr;
8056
8057   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8058   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8059     return SDValue();
8060
8061   if (IsLeftOperandMUL)
8062     HiAdd = &AddeOp1;
8063   else
8064     HiAdd = &AddeOp0;
8065
8066
8067   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8068   // whose low result is fed to the ADDC we are checking.
8069
8070   if (AddcOp0 == MULOp.getValue(0)) {
8071     LoMul = &AddcOp0;
8072     LowAdd = &AddcOp1;
8073   }
8074   if (AddcOp1 == MULOp.getValue(0)) {
8075     LoMul = &AddcOp1;
8076     LowAdd = &AddcOp0;
8077   }
8078
8079   if (!LoMul)
8080     return SDValue();
8081
8082   // Create the merged node.
8083   SelectionDAG &DAG = DCI.DAG;
8084
8085   // Build operand list.
8086   SmallVector<SDValue, 8> Ops;
8087   Ops.push_back(LoMul->getOperand(0));
8088   Ops.push_back(LoMul->getOperand(1));
8089   Ops.push_back(*LowAdd);
8090   Ops.push_back(*HiAdd);
8091
8092   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8093                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8094
8095   // Replace the ADDs' nodes uses by the MLA node's values.
8096   SDValue HiMLALResult(MLALNode.getNode(), 1);
8097   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8098
8099   SDValue LoMLALResult(MLALNode.getNode(), 0);
8100   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8101
8102   // Return original node to notify the driver to stop replacing.
8103   SDValue resNode(AddcNode, 0);
8104   return resNode;
8105 }
8106
8107 /// PerformADDCCombine - Target-specific dag combine transform from
8108 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8109 static SDValue PerformADDCCombine(SDNode *N,
8110                                  TargetLowering::DAGCombinerInfo &DCI,
8111                                  const ARMSubtarget *Subtarget) {
8112
8113   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8114
8115 }
8116
8117 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8118 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8119 /// called with the default operands, and if that fails, with commuted
8120 /// operands.
8121 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8122                                           TargetLowering::DAGCombinerInfo &DCI,
8123                                           const ARMSubtarget *Subtarget){
8124
8125   // Attempt to create vpaddl for this add.
8126   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8127   if (Result.getNode())
8128     return Result;
8129
8130   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8131   if (N0.getNode()->hasOneUse()) {
8132     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8133     if (Result.getNode()) return Result;
8134   }
8135   return SDValue();
8136 }
8137
8138 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8139 ///
8140 static SDValue PerformADDCombine(SDNode *N,
8141                                  TargetLowering::DAGCombinerInfo &DCI,
8142                                  const ARMSubtarget *Subtarget) {
8143   SDValue N0 = N->getOperand(0);
8144   SDValue N1 = N->getOperand(1);
8145
8146   // First try with the default operand order.
8147   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8148   if (Result.getNode())
8149     return Result;
8150
8151   // If that didn't work, try again with the operands commuted.
8152   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8153 }
8154
8155 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8156 ///
8157 static SDValue PerformSUBCombine(SDNode *N,
8158                                  TargetLowering::DAGCombinerInfo &DCI) {
8159   SDValue N0 = N->getOperand(0);
8160   SDValue N1 = N->getOperand(1);
8161
8162   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8163   if (N1.getNode()->hasOneUse()) {
8164     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8165     if (Result.getNode()) return Result;
8166   }
8167
8168   return SDValue();
8169 }
8170
8171 /// PerformVMULCombine
8172 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8173 /// special multiplier accumulator forwarding.
8174 ///   vmul d3, d0, d2
8175 ///   vmla d3, d1, d2
8176 /// is faster than
8177 ///   vadd d3, d0, d1
8178 ///   vmul d3, d3, d2
8179 //  However, for (A + B) * (A + B),
8180 //    vadd d2, d0, d1
8181 //    vmul d3, d0, d2
8182 //    vmla d3, d1, d2
8183 //  is slower than
8184 //    vadd d2, d0, d1
8185 //    vmul d3, d2, d2
8186 static SDValue PerformVMULCombine(SDNode *N,
8187                                   TargetLowering::DAGCombinerInfo &DCI,
8188                                   const ARMSubtarget *Subtarget) {
8189   if (!Subtarget->hasVMLxForwarding())
8190     return SDValue();
8191
8192   SelectionDAG &DAG = DCI.DAG;
8193   SDValue N0 = N->getOperand(0);
8194   SDValue N1 = N->getOperand(1);
8195   unsigned Opcode = N0.getOpcode();
8196   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8197       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8198     Opcode = N1.getOpcode();
8199     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8200         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8201       return SDValue();
8202     std::swap(N0, N1);
8203   }
8204
8205   if (N0 == N1)
8206     return SDValue();
8207
8208   EVT VT = N->getValueType(0);
8209   SDLoc DL(N);
8210   SDValue N00 = N0->getOperand(0);
8211   SDValue N01 = N0->getOperand(1);
8212   return DAG.getNode(Opcode, DL, VT,
8213                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8214                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8215 }
8216
8217 static SDValue PerformMULCombine(SDNode *N,
8218                                  TargetLowering::DAGCombinerInfo &DCI,
8219                                  const ARMSubtarget *Subtarget) {
8220   SelectionDAG &DAG = DCI.DAG;
8221
8222   if (Subtarget->isThumb1Only())
8223     return SDValue();
8224
8225   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8226     return SDValue();
8227
8228   EVT VT = N->getValueType(0);
8229   if (VT.is64BitVector() || VT.is128BitVector())
8230     return PerformVMULCombine(N, DCI, Subtarget);
8231   if (VT != MVT::i32)
8232     return SDValue();
8233
8234   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8235   if (!C)
8236     return SDValue();
8237
8238   int64_t MulAmt = C->getSExtValue();
8239   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8240
8241   ShiftAmt = ShiftAmt & (32 - 1);
8242   SDValue V = N->getOperand(0);
8243   SDLoc DL(N);
8244
8245   SDValue Res;
8246   MulAmt >>= ShiftAmt;
8247
8248   if (MulAmt >= 0) {
8249     if (isPowerOf2_32(MulAmt - 1)) {
8250       // (mul x, 2^N + 1) => (add (shl x, N), x)
8251       Res = DAG.getNode(ISD::ADD, DL, VT,
8252                         V,
8253                         DAG.getNode(ISD::SHL, DL, VT,
8254                                     V,
8255                                     DAG.getConstant(Log2_32(MulAmt - 1),
8256                                                     MVT::i32)));
8257     } else if (isPowerOf2_32(MulAmt + 1)) {
8258       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8259       Res = DAG.getNode(ISD::SUB, DL, VT,
8260                         DAG.getNode(ISD::SHL, DL, VT,
8261                                     V,
8262                                     DAG.getConstant(Log2_32(MulAmt + 1),
8263                                                     MVT::i32)),
8264                         V);
8265     } else
8266       return SDValue();
8267   } else {
8268     uint64_t MulAmtAbs = -MulAmt;
8269     if (isPowerOf2_32(MulAmtAbs + 1)) {
8270       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8271       Res = DAG.getNode(ISD::SUB, DL, VT,
8272                         V,
8273                         DAG.getNode(ISD::SHL, DL, VT,
8274                                     V,
8275                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8276                                                     MVT::i32)));
8277     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8278       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8279       Res = DAG.getNode(ISD::ADD, DL, VT,
8280                         V,
8281                         DAG.getNode(ISD::SHL, DL, VT,
8282                                     V,
8283                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8284                                                     MVT::i32)));
8285       Res = DAG.getNode(ISD::SUB, DL, VT,
8286                         DAG.getConstant(0, MVT::i32),Res);
8287
8288     } else
8289       return SDValue();
8290   }
8291
8292   if (ShiftAmt != 0)
8293     Res = DAG.getNode(ISD::SHL, DL, VT,
8294                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8295
8296   // Do not add new nodes to DAG combiner worklist.
8297   DCI.CombineTo(N, Res, false);
8298   return SDValue();
8299 }
8300
8301 static SDValue PerformANDCombine(SDNode *N,
8302                                  TargetLowering::DAGCombinerInfo &DCI,
8303                                  const ARMSubtarget *Subtarget) {
8304
8305   // Attempt to use immediate-form VBIC
8306   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8307   SDLoc dl(N);
8308   EVT VT = N->getValueType(0);
8309   SelectionDAG &DAG = DCI.DAG;
8310
8311   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8312     return SDValue();
8313
8314   APInt SplatBits, SplatUndef;
8315   unsigned SplatBitSize;
8316   bool HasAnyUndefs;
8317   if (BVN &&
8318       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8319     if (SplatBitSize <= 64) {
8320       EVT VbicVT;
8321       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8322                                       SplatUndef.getZExtValue(), SplatBitSize,
8323                                       DAG, VbicVT, VT.is128BitVector(),
8324                                       OtherModImm);
8325       if (Val.getNode()) {
8326         SDValue Input =
8327           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8328         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8329         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8330       }
8331     }
8332   }
8333
8334   if (!Subtarget->isThumb1Only()) {
8335     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8336     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8337     if (Result.getNode())
8338       return Result;
8339   }
8340
8341   return SDValue();
8342 }
8343
8344 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8345 static SDValue PerformORCombine(SDNode *N,
8346                                 TargetLowering::DAGCombinerInfo &DCI,
8347                                 const ARMSubtarget *Subtarget) {
8348   // Attempt to use immediate-form VORR
8349   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8350   SDLoc dl(N);
8351   EVT VT = N->getValueType(0);
8352   SelectionDAG &DAG = DCI.DAG;
8353
8354   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8355     return SDValue();
8356
8357   APInt SplatBits, SplatUndef;
8358   unsigned SplatBitSize;
8359   bool HasAnyUndefs;
8360   if (BVN && Subtarget->hasNEON() &&
8361       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8362     if (SplatBitSize <= 64) {
8363       EVT VorrVT;
8364       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8365                                       SplatUndef.getZExtValue(), SplatBitSize,
8366                                       DAG, VorrVT, VT.is128BitVector(),
8367                                       OtherModImm);
8368       if (Val.getNode()) {
8369         SDValue Input =
8370           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8371         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8372         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8373       }
8374     }
8375   }
8376
8377   if (!Subtarget->isThumb1Only()) {
8378     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8379     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8380     if (Result.getNode())
8381       return Result;
8382   }
8383
8384   // The code below optimizes (or (and X, Y), Z).
8385   // The AND operand needs to have a single user to make these optimizations
8386   // profitable.
8387   SDValue N0 = N->getOperand(0);
8388   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8389     return SDValue();
8390   SDValue N1 = N->getOperand(1);
8391
8392   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8393   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8394       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8395     APInt SplatUndef;
8396     unsigned SplatBitSize;
8397     bool HasAnyUndefs;
8398
8399     APInt SplatBits0, SplatBits1;
8400     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8401     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8402     // Ensure that the second operand of both ands are constants
8403     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8404                                       HasAnyUndefs) && !HasAnyUndefs) {
8405         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8406                                           HasAnyUndefs) && !HasAnyUndefs) {
8407             // Ensure that the bit width of the constants are the same and that
8408             // the splat arguments are logical inverses as per the pattern we
8409             // are trying to simplify.
8410             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8411                 SplatBits0 == ~SplatBits1) {
8412                 // Canonicalize the vector type to make instruction selection
8413                 // simpler.
8414                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8415                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8416                                              N0->getOperand(1),
8417                                              N0->getOperand(0),
8418                                              N1->getOperand(0));
8419                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8420             }
8421         }
8422     }
8423   }
8424
8425   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8426   // reasonable.
8427
8428   // BFI is only available on V6T2+
8429   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8430     return SDValue();
8431
8432   SDLoc DL(N);
8433   // 1) or (and A, mask), val => ARMbfi A, val, mask
8434   //      iff (val & mask) == val
8435   //
8436   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8437   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8438   //          && mask == ~mask2
8439   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8440   //          && ~mask == mask2
8441   //  (i.e., copy a bitfield value into another bitfield of the same width)
8442
8443   if (VT != MVT::i32)
8444     return SDValue();
8445
8446   SDValue N00 = N0.getOperand(0);
8447
8448   // The value and the mask need to be constants so we can verify this is
8449   // actually a bitfield set. If the mask is 0xffff, we can do better
8450   // via a movt instruction, so don't use BFI in that case.
8451   SDValue MaskOp = N0.getOperand(1);
8452   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8453   if (!MaskC)
8454     return SDValue();
8455   unsigned Mask = MaskC->getZExtValue();
8456   if (Mask == 0xffff)
8457     return SDValue();
8458   SDValue Res;
8459   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8460   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8461   if (N1C) {
8462     unsigned Val = N1C->getZExtValue();
8463     if ((Val & ~Mask) != Val)
8464       return SDValue();
8465
8466     if (ARM::isBitFieldInvertedMask(Mask)) {
8467       Val >>= countTrailingZeros(~Mask);
8468
8469       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8470                         DAG.getConstant(Val, MVT::i32),
8471                         DAG.getConstant(Mask, MVT::i32));
8472
8473       // Do not add new nodes to DAG combiner worklist.
8474       DCI.CombineTo(N, Res, false);
8475       return SDValue();
8476     }
8477   } else if (N1.getOpcode() == ISD::AND) {
8478     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8479     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8480     if (!N11C)
8481       return SDValue();
8482     unsigned Mask2 = N11C->getZExtValue();
8483
8484     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8485     // as is to match.
8486     if (ARM::isBitFieldInvertedMask(Mask) &&
8487         (Mask == ~Mask2)) {
8488       // The pack halfword instruction works better for masks that fit it,
8489       // so use that when it's available.
8490       if (Subtarget->hasT2ExtractPack() &&
8491           (Mask == 0xffff || Mask == 0xffff0000))
8492         return SDValue();
8493       // 2a
8494       unsigned amt = countTrailingZeros(Mask2);
8495       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8496                         DAG.getConstant(amt, MVT::i32));
8497       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8498                         DAG.getConstant(Mask, MVT::i32));
8499       // Do not add new nodes to DAG combiner worklist.
8500       DCI.CombineTo(N, Res, false);
8501       return SDValue();
8502     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8503                (~Mask == Mask2)) {
8504       // The pack halfword instruction works better for masks that fit it,
8505       // so use that when it's available.
8506       if (Subtarget->hasT2ExtractPack() &&
8507           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8508         return SDValue();
8509       // 2b
8510       unsigned lsb = countTrailingZeros(Mask);
8511       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8512                         DAG.getConstant(lsb, MVT::i32));
8513       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8514                         DAG.getConstant(Mask2, MVT::i32));
8515       // Do not add new nodes to DAG combiner worklist.
8516       DCI.CombineTo(N, Res, false);
8517       return SDValue();
8518     }
8519   }
8520
8521   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8522       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8523       ARM::isBitFieldInvertedMask(~Mask)) {
8524     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8525     // where lsb(mask) == #shamt and masked bits of B are known zero.
8526     SDValue ShAmt = N00.getOperand(1);
8527     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8528     unsigned LSB = countTrailingZeros(Mask);
8529     if (ShAmtC != LSB)
8530       return SDValue();
8531
8532     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8533                       DAG.getConstant(~Mask, MVT::i32));
8534
8535     // Do not add new nodes to DAG combiner worklist.
8536     DCI.CombineTo(N, Res, false);
8537   }
8538
8539   return SDValue();
8540 }
8541
8542 static SDValue PerformXORCombine(SDNode *N,
8543                                  TargetLowering::DAGCombinerInfo &DCI,
8544                                  const ARMSubtarget *Subtarget) {
8545   EVT VT = N->getValueType(0);
8546   SelectionDAG &DAG = DCI.DAG;
8547
8548   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8549     return SDValue();
8550
8551   if (!Subtarget->isThumb1Only()) {
8552     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8553     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8554     if (Result.getNode())
8555       return Result;
8556   }
8557
8558   return SDValue();
8559 }
8560
8561 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8562 /// the bits being cleared by the AND are not demanded by the BFI.
8563 static SDValue PerformBFICombine(SDNode *N,
8564                                  TargetLowering::DAGCombinerInfo &DCI) {
8565   SDValue N1 = N->getOperand(1);
8566   if (N1.getOpcode() == ISD::AND) {
8567     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8568     if (!N11C)
8569       return SDValue();
8570     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8571     unsigned LSB = countTrailingZeros(~InvMask);
8572     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8573     assert(Width <
8574                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8575            "undefined behavior");
8576     unsigned Mask = (1u << Width) - 1;
8577     unsigned Mask2 = N11C->getZExtValue();
8578     if ((Mask & (~Mask2)) == 0)
8579       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8580                              N->getOperand(0), N1.getOperand(0),
8581                              N->getOperand(2));
8582   }
8583   return SDValue();
8584 }
8585
8586 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8587 /// ARMISD::VMOVRRD.
8588 static SDValue PerformVMOVRRDCombine(SDNode *N,
8589                                      TargetLowering::DAGCombinerInfo &DCI,
8590                                      const ARMSubtarget *Subtarget) {
8591   // vmovrrd(vmovdrr x, y) -> x,y
8592   SDValue InDouble = N->getOperand(0);
8593   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8594     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8595
8596   // vmovrrd(load f64) -> (load i32), (load i32)
8597   SDNode *InNode = InDouble.getNode();
8598   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8599       InNode->getValueType(0) == MVT::f64 &&
8600       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8601       !cast<LoadSDNode>(InNode)->isVolatile()) {
8602     // TODO: Should this be done for non-FrameIndex operands?
8603     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8604
8605     SelectionDAG &DAG = DCI.DAG;
8606     SDLoc DL(LD);
8607     SDValue BasePtr = LD->getBasePtr();
8608     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8609                                  LD->getPointerInfo(), LD->isVolatile(),
8610                                  LD->isNonTemporal(), LD->isInvariant(),
8611                                  LD->getAlignment());
8612
8613     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8614                                     DAG.getConstant(4, MVT::i32));
8615     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8616                                  LD->getPointerInfo(), LD->isVolatile(),
8617                                  LD->isNonTemporal(), LD->isInvariant(),
8618                                  std::min(4U, LD->getAlignment() / 2));
8619
8620     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8621     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8622       std::swap (NewLD1, NewLD2);
8623     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8624     return Result;
8625   }
8626
8627   return SDValue();
8628 }
8629
8630 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8631 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8632 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8633   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8634   SDValue Op0 = N->getOperand(0);
8635   SDValue Op1 = N->getOperand(1);
8636   if (Op0.getOpcode() == ISD::BITCAST)
8637     Op0 = Op0.getOperand(0);
8638   if (Op1.getOpcode() == ISD::BITCAST)
8639     Op1 = Op1.getOperand(0);
8640   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8641       Op0.getNode() == Op1.getNode() &&
8642       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8643     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8644                        N->getValueType(0), Op0.getOperand(0));
8645   return SDValue();
8646 }
8647
8648 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8649 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8650 /// i64 vector to have f64 elements, since the value can then be loaded
8651 /// directly into a VFP register.
8652 static bool hasNormalLoadOperand(SDNode *N) {
8653   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8654   for (unsigned i = 0; i < NumElts; ++i) {
8655     SDNode *Elt = N->getOperand(i).getNode();
8656     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8657       return true;
8658   }
8659   return false;
8660 }
8661
8662 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8663 /// ISD::BUILD_VECTOR.
8664 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8665                                           TargetLowering::DAGCombinerInfo &DCI,
8666                                           const ARMSubtarget *Subtarget) {
8667   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8668   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8669   // into a pair of GPRs, which is fine when the value is used as a scalar,
8670   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8671   SelectionDAG &DAG = DCI.DAG;
8672   if (N->getNumOperands() == 2) {
8673     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8674     if (RV.getNode())
8675       return RV;
8676   }
8677
8678   // Load i64 elements as f64 values so that type legalization does not split
8679   // them up into i32 values.
8680   EVT VT = N->getValueType(0);
8681   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8682     return SDValue();
8683   SDLoc dl(N);
8684   SmallVector<SDValue, 8> Ops;
8685   unsigned NumElts = VT.getVectorNumElements();
8686   for (unsigned i = 0; i < NumElts; ++i) {
8687     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8688     Ops.push_back(V);
8689     // Make the DAGCombiner fold the bitcast.
8690     DCI.AddToWorklist(V.getNode());
8691   }
8692   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8693   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8694   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8695 }
8696
8697 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8698 static SDValue
8699 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8700   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8701   // At that time, we may have inserted bitcasts from integer to float.
8702   // If these bitcasts have survived DAGCombine, change the lowering of this
8703   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8704   // force to use floating point types.
8705
8706   // Make sure we can change the type of the vector.
8707   // This is possible iff:
8708   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8709   //    1.1. Vector is used only once.
8710   //    1.2. Use is a bit convert to an integer type.
8711   // 2. The size of its operands are 32-bits (64-bits are not legal).
8712   EVT VT = N->getValueType(0);
8713   EVT EltVT = VT.getVectorElementType();
8714
8715   // Check 1.1. and 2.
8716   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8717     return SDValue();
8718
8719   // By construction, the input type must be float.
8720   assert(EltVT == MVT::f32 && "Unexpected type!");
8721
8722   // Check 1.2.
8723   SDNode *Use = *N->use_begin();
8724   if (Use->getOpcode() != ISD::BITCAST ||
8725       Use->getValueType(0).isFloatingPoint())
8726     return SDValue();
8727
8728   // Check profitability.
8729   // Model is, if more than half of the relevant operands are bitcast from
8730   // i32, turn the build_vector into a sequence of insert_vector_elt.
8731   // Relevant operands are everything that is not statically
8732   // (i.e., at compile time) bitcasted.
8733   unsigned NumOfBitCastedElts = 0;
8734   unsigned NumElts = VT.getVectorNumElements();
8735   unsigned NumOfRelevantElts = NumElts;
8736   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8737     SDValue Elt = N->getOperand(Idx);
8738     if (Elt->getOpcode() == ISD::BITCAST) {
8739       // Assume only bit cast to i32 will go away.
8740       if (Elt->getOperand(0).getValueType() == MVT::i32)
8741         ++NumOfBitCastedElts;
8742     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8743       // Constants are statically casted, thus do not count them as
8744       // relevant operands.
8745       --NumOfRelevantElts;
8746   }
8747
8748   // Check if more than half of the elements require a non-free bitcast.
8749   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8750     return SDValue();
8751
8752   SelectionDAG &DAG = DCI.DAG;
8753   // Create the new vector type.
8754   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8755   // Check if the type is legal.
8756   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8757   if (!TLI.isTypeLegal(VecVT))
8758     return SDValue();
8759
8760   // Combine:
8761   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8762   // => BITCAST INSERT_VECTOR_ELT
8763   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8764   //                      (BITCAST EN), N.
8765   SDValue Vec = DAG.getUNDEF(VecVT);
8766   SDLoc dl(N);
8767   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8768     SDValue V = N->getOperand(Idx);
8769     if (V.getOpcode() == ISD::UNDEF)
8770       continue;
8771     if (V.getOpcode() == ISD::BITCAST &&
8772         V->getOperand(0).getValueType() == MVT::i32)
8773       // Fold obvious case.
8774       V = V.getOperand(0);
8775     else {
8776       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8777       // Make the DAGCombiner fold the bitcasts.
8778       DCI.AddToWorklist(V.getNode());
8779     }
8780     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8781     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8782   }
8783   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8784   // Make the DAGCombiner fold the bitcasts.
8785   DCI.AddToWorklist(Vec.getNode());
8786   return Vec;
8787 }
8788
8789 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8790 /// ISD::INSERT_VECTOR_ELT.
8791 static SDValue PerformInsertEltCombine(SDNode *N,
8792                                        TargetLowering::DAGCombinerInfo &DCI) {
8793   // Bitcast an i64 load inserted into a vector to f64.
8794   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8795   EVT VT = N->getValueType(0);
8796   SDNode *Elt = N->getOperand(1).getNode();
8797   if (VT.getVectorElementType() != MVT::i64 ||
8798       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8799     return SDValue();
8800
8801   SelectionDAG &DAG = DCI.DAG;
8802   SDLoc dl(N);
8803   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8804                                  VT.getVectorNumElements());
8805   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8806   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8807   // Make the DAGCombiner fold the bitcasts.
8808   DCI.AddToWorklist(Vec.getNode());
8809   DCI.AddToWorklist(V.getNode());
8810   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8811                                Vec, V, N->getOperand(2));
8812   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8813 }
8814
8815 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8816 /// ISD::VECTOR_SHUFFLE.
8817 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8818   // The LLVM shufflevector instruction does not require the shuffle mask
8819   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8820   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8821   // operands do not match the mask length, they are extended by concatenating
8822   // them with undef vectors.  That is probably the right thing for other
8823   // targets, but for NEON it is better to concatenate two double-register
8824   // size vector operands into a single quad-register size vector.  Do that
8825   // transformation here:
8826   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8827   //   shuffle(concat(v1, v2), undef)
8828   SDValue Op0 = N->getOperand(0);
8829   SDValue Op1 = N->getOperand(1);
8830   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8831       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8832       Op0.getNumOperands() != 2 ||
8833       Op1.getNumOperands() != 2)
8834     return SDValue();
8835   SDValue Concat0Op1 = Op0.getOperand(1);
8836   SDValue Concat1Op1 = Op1.getOperand(1);
8837   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8838       Concat1Op1.getOpcode() != ISD::UNDEF)
8839     return SDValue();
8840   // Skip the transformation if any of the types are illegal.
8841   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8842   EVT VT = N->getValueType(0);
8843   if (!TLI.isTypeLegal(VT) ||
8844       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8845       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8846     return SDValue();
8847
8848   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8849                                   Op0.getOperand(0), Op1.getOperand(0));
8850   // Translate the shuffle mask.
8851   SmallVector<int, 16> NewMask;
8852   unsigned NumElts = VT.getVectorNumElements();
8853   unsigned HalfElts = NumElts/2;
8854   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8855   for (unsigned n = 0; n < NumElts; ++n) {
8856     int MaskElt = SVN->getMaskElt(n);
8857     int NewElt = -1;
8858     if (MaskElt < (int)HalfElts)
8859       NewElt = MaskElt;
8860     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8861       NewElt = HalfElts + MaskElt - NumElts;
8862     NewMask.push_back(NewElt);
8863   }
8864   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8865                               DAG.getUNDEF(VT), NewMask.data());
8866 }
8867
8868 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8869 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8870 /// base address updates.
8871 /// For generic load/stores, the memory type is assumed to be a vector.
8872 /// The caller is assumed to have checked legality.
8873 static SDValue CombineBaseUpdate(SDNode *N,
8874                                  TargetLowering::DAGCombinerInfo &DCI) {
8875   SelectionDAG &DAG = DCI.DAG;
8876   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8877                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8878   const bool isStore = N->getOpcode() == ISD::STORE;
8879   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8880   SDValue Addr = N->getOperand(AddrOpIdx);
8881   MemSDNode *MemN = cast<MemSDNode>(N);
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 isLoadOp = 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; isLoadOp = false; break;
8921       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8922         NumVecs = 2; isLoadOp = false; break;
8923       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8924         NumVecs = 3; isLoadOp = false; break;
8925       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8926         NumVecs = 4; isLoadOp = false; break;
8927       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8928         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8929       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8930         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8931       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8932         NumVecs = 4; isLoadOp = 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       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
8942         NumVecs = 1; isLaneOp = false; break;
8943       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
8944         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8945       }
8946     }
8947
8948     // Find the size of memory referenced by the load/store.
8949     EVT VecTy;
8950     if (isLoadOp) {
8951       VecTy = N->getValueType(0);
8952     } else if (isIntrinsic) {
8953       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8954     } else {
8955       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8956       VecTy = N->getOperand(1).getValueType();
8957     }
8958
8959     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8960     if (isLaneOp)
8961       NumBytes /= VecTy.getVectorNumElements();
8962
8963     // If the increment is a constant, it must match the memory ref size.
8964     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8965     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8966       uint64_t IncVal = CInc->getZExtValue();
8967       if (IncVal != NumBytes)
8968         continue;
8969     } else if (NumBytes >= 3 * 16) {
8970       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8971       // separate instructions that make it harder to use a non-constant update.
8972       continue;
8973     }
8974
8975     // OK, we found an ADD we can fold into the base update.
8976     // Now, create a _UPD node, taking care of not breaking alignment.
8977
8978     EVT AlignedVecTy = VecTy;
8979     unsigned Alignment = MemN->getAlignment();
8980
8981     // If this is a less-than-standard-aligned load/store, change the type to
8982     // match the standard alignment.
8983     // The alignment is overlooked when selecting _UPD variants; and it's
8984     // easier to introduce bitcasts here than fix that.
8985     // There are 3 ways to get to this base-update combine:
8986     // - intrinsics: they are assumed to be properly aligned (to the standard
8987     //   alignment of the memory type), so we don't need to do anything.
8988     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
8989     //   intrinsics, so, likewise, there's nothing to do.
8990     // - generic load/store instructions: the alignment is specified as an
8991     //   explicit operand, rather than implicitly as the standard alignment
8992     //   of the memory type (like the intrisics).  We need to change the
8993     //   memory type to match the explicit alignment.  That way, we don't
8994     //   generate non-standard-aligned ARMISD::VLDx nodes.
8995     if (isa<LSBaseSDNode>(N)) {
8996       if (Alignment == 0)
8997         Alignment = 1;
8998       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
8999         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9000         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9001         assert(!isLaneOp && "Unexpected generic load/store lane.");
9002         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9003         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9004       }
9005       // Don't set an explicit alignment on regular load/stores that we want
9006       // to transform to VLD/VST 1_UPD nodes.
9007       // This matches the behavior of regular load/stores, which only get an
9008       // explicit alignment if the MMO alignment is larger than the standard
9009       // alignment of the memory type.
9010       // Intrinsics, however, always get an explicit alignment, set to the
9011       // alignment of the MMO.
9012       Alignment = 1;
9013     }
9014
9015     // Create the new updating load/store node.
9016     // First, create an SDVTList for the new updating node's results.
9017     EVT Tys[6];
9018     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9019     unsigned n;
9020     for (n = 0; n < NumResultVecs; ++n)
9021       Tys[n] = AlignedVecTy;
9022     Tys[n++] = MVT::i32;
9023     Tys[n] = MVT::Other;
9024     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9025
9026     // Then, gather the new node's operands.
9027     SmallVector<SDValue, 8> Ops;
9028     Ops.push_back(N->getOperand(0)); // incoming chain
9029     Ops.push_back(N->getOperand(AddrOpIdx));
9030     Ops.push_back(Inc);
9031
9032     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9033       // Try to match the intrinsic's signature
9034       Ops.push_back(StN->getValue());
9035     } else {
9036       // Loads (and of course intrinsics) match the intrinsics' signature,
9037       // so just add all but the alignment operand.
9038       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9039         Ops.push_back(N->getOperand(i));
9040     }
9041
9042     // For all node types, the alignment operand is always the last one.
9043     Ops.push_back(DAG.getConstant(Alignment, MVT::i32));
9044
9045     // If this is a non-standard-aligned STORE, the penultimate operand is the
9046     // stored value.  Bitcast it to the aligned type.
9047     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9048       SDValue &StVal = Ops[Ops.size()-2];
9049       StVal = DAG.getNode(ISD::BITCAST, SDLoc(N), AlignedVecTy, StVal);
9050     }
9051
9052     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9053                                            Ops, AlignedVecTy,
9054                                            MemN->getMemOperand());
9055
9056     // Update the uses.
9057     SmallVector<SDValue, 5> NewResults;
9058     for (unsigned i = 0; i < NumResultVecs; ++i)
9059       NewResults.push_back(SDValue(UpdN.getNode(), i));
9060
9061     // If this is an non-standard-aligned LOAD, the first result is the loaded
9062     // value.  Bitcast it to the expected result type.
9063     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9064       SDValue &LdVal = NewResults[0];
9065       LdVal = DAG.getNode(ISD::BITCAST, SDLoc(N), VecTy, LdVal);
9066     }
9067
9068     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9069     DCI.CombineTo(N, NewResults);
9070     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9071
9072     break;
9073   }
9074   return SDValue();
9075 }
9076
9077 static SDValue PerformVLDCombine(SDNode *N,
9078                                  TargetLowering::DAGCombinerInfo &DCI) {
9079   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9080     return SDValue();
9081
9082   return CombineBaseUpdate(N, DCI);
9083 }
9084
9085 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9086 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9087 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9088 /// return true.
9089 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9090   SelectionDAG &DAG = DCI.DAG;
9091   EVT VT = N->getValueType(0);
9092   // vldN-dup instructions only support 64-bit vectors for N > 1.
9093   if (!VT.is64BitVector())
9094     return false;
9095
9096   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9097   SDNode *VLD = N->getOperand(0).getNode();
9098   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9099     return false;
9100   unsigned NumVecs = 0;
9101   unsigned NewOpc = 0;
9102   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9103   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9104     NumVecs = 2;
9105     NewOpc = ARMISD::VLD2DUP;
9106   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9107     NumVecs = 3;
9108     NewOpc = ARMISD::VLD3DUP;
9109   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9110     NumVecs = 4;
9111     NewOpc = ARMISD::VLD4DUP;
9112   } else {
9113     return false;
9114   }
9115
9116   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9117   // numbers match the load.
9118   unsigned VLDLaneNo =
9119     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9120   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9121        UI != UE; ++UI) {
9122     // Ignore uses of the chain result.
9123     if (UI.getUse().getResNo() == NumVecs)
9124       continue;
9125     SDNode *User = *UI;
9126     if (User->getOpcode() != ARMISD::VDUPLANE ||
9127         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9128       return false;
9129   }
9130
9131   // Create the vldN-dup node.
9132   EVT Tys[5];
9133   unsigned n;
9134   for (n = 0; n < NumVecs; ++n)
9135     Tys[n] = VT;
9136   Tys[n] = MVT::Other;
9137   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9138   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9139   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9140   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9141                                            Ops, VLDMemInt->getMemoryVT(),
9142                                            VLDMemInt->getMemOperand());
9143
9144   // Update the uses.
9145   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9146        UI != UE; ++UI) {
9147     unsigned ResNo = UI.getUse().getResNo();
9148     // Ignore uses of the chain result.
9149     if (ResNo == NumVecs)
9150       continue;
9151     SDNode *User = *UI;
9152     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9153   }
9154
9155   // Now the vldN-lane intrinsic is dead except for its chain result.
9156   // Update uses of the chain.
9157   std::vector<SDValue> VLDDupResults;
9158   for (unsigned n = 0; n < NumVecs; ++n)
9159     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9160   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9161   DCI.CombineTo(VLD, VLDDupResults);
9162
9163   return true;
9164 }
9165
9166 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9167 /// ARMISD::VDUPLANE.
9168 static SDValue PerformVDUPLANECombine(SDNode *N,
9169                                       TargetLowering::DAGCombinerInfo &DCI) {
9170   SDValue Op = N->getOperand(0);
9171
9172   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9173   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9174   if (CombineVLDDUP(N, DCI))
9175     return SDValue(N, 0);
9176
9177   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9178   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9179   while (Op.getOpcode() == ISD::BITCAST)
9180     Op = Op.getOperand(0);
9181   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9182     return SDValue();
9183
9184   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9185   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9186   // The canonical VMOV for a zero vector uses a 32-bit element size.
9187   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9188   unsigned EltBits;
9189   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9190     EltSize = 8;
9191   EVT VT = N->getValueType(0);
9192   if (EltSize > VT.getVectorElementType().getSizeInBits())
9193     return SDValue();
9194
9195   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9196 }
9197
9198 static SDValue PerformLOADCombine(SDNode *N,
9199                                   TargetLowering::DAGCombinerInfo &DCI) {
9200   EVT VT = N->getValueType(0);
9201
9202   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9203   if (ISD::isNormalLoad(N) && VT.isVector() &&
9204       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9205     return CombineBaseUpdate(N, DCI);
9206
9207   return SDValue();
9208 }
9209
9210 /// PerformSTORECombine - Target-specific dag combine xforms for
9211 /// ISD::STORE.
9212 static SDValue PerformSTORECombine(SDNode *N,
9213                                    TargetLowering::DAGCombinerInfo &DCI) {
9214   StoreSDNode *St = cast<StoreSDNode>(N);
9215   if (St->isVolatile())
9216     return SDValue();
9217
9218   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9219   // pack all of the elements in one place.  Next, store to memory in fewer
9220   // chunks.
9221   SDValue StVal = St->getValue();
9222   EVT VT = StVal.getValueType();
9223   if (St->isTruncatingStore() && VT.isVector()) {
9224     SelectionDAG &DAG = DCI.DAG;
9225     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9226     EVT StVT = St->getMemoryVT();
9227     unsigned NumElems = VT.getVectorNumElements();
9228     assert(StVT != VT && "Cannot truncate to the same type");
9229     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9230     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9231
9232     // From, To sizes and ElemCount must be pow of two
9233     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9234
9235     // We are going to use the original vector elt for storing.
9236     // Accumulated smaller vector elements must be a multiple of the store size.
9237     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9238
9239     unsigned SizeRatio  = FromEltSz / ToEltSz;
9240     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9241
9242     // Create a type on which we perform the shuffle.
9243     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9244                                      NumElems*SizeRatio);
9245     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9246
9247     SDLoc DL(St);
9248     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9249     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9250     for (unsigned i = 0; i < NumElems; ++i)
9251       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9252
9253     // Can't shuffle using an illegal type.
9254     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9255
9256     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9257                                 DAG.getUNDEF(WideVec.getValueType()),
9258                                 ShuffleVec.data());
9259     // At this point all of the data is stored at the bottom of the
9260     // register. We now need to save it to mem.
9261
9262     // Find the largest store unit
9263     MVT StoreType = MVT::i8;
9264     for (MVT Tp : MVT::integer_valuetypes()) {
9265       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9266         StoreType = Tp;
9267     }
9268     // Didn't find a legal store type.
9269     if (!TLI.isTypeLegal(StoreType))
9270       return SDValue();
9271
9272     // Bitcast the original vector into a vector of store-size units
9273     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9274             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9275     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9276     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9277     SmallVector<SDValue, 8> Chains;
9278     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9279                                         TLI.getPointerTy());
9280     SDValue BasePtr = St->getBasePtr();
9281
9282     // Perform one or more big stores into memory.
9283     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9284     for (unsigned I = 0; I < E; I++) {
9285       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9286                                    StoreType, ShuffWide,
9287                                    DAG.getIntPtrConstant(I));
9288       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9289                                 St->getPointerInfo(), St->isVolatile(),
9290                                 St->isNonTemporal(), St->getAlignment());
9291       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9292                             Increment);
9293       Chains.push_back(Ch);
9294     }
9295     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9296   }
9297
9298   if (!ISD::isNormalStore(St))
9299     return SDValue();
9300
9301   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9302   // ARM stores of arguments in the same cache line.
9303   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9304       StVal.getNode()->hasOneUse()) {
9305     SelectionDAG  &DAG = DCI.DAG;
9306     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9307     SDLoc DL(St);
9308     SDValue BasePtr = St->getBasePtr();
9309     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9310                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9311                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9312                                   St->isNonTemporal(), St->getAlignment());
9313
9314     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9315                                     DAG.getConstant(4, MVT::i32));
9316     return DAG.getStore(NewST1.getValue(0), DL,
9317                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9318                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9319                         St->isNonTemporal(),
9320                         std::min(4U, St->getAlignment() / 2));
9321   }
9322
9323   if (StVal.getValueType() == MVT::i64 &&
9324       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9325
9326     // Bitcast an i64 store extracted from a vector to f64.
9327     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9328     SelectionDAG &DAG = DCI.DAG;
9329     SDLoc dl(StVal);
9330     SDValue IntVec = StVal.getOperand(0);
9331     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9332                                    IntVec.getValueType().getVectorNumElements());
9333     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9334     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9335                                  Vec, StVal.getOperand(1));
9336     dl = SDLoc(N);
9337     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9338     // Make the DAGCombiner fold the bitcasts.
9339     DCI.AddToWorklist(Vec.getNode());
9340     DCI.AddToWorklist(ExtElt.getNode());
9341     DCI.AddToWorklist(V.getNode());
9342     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9343                         St->getPointerInfo(), St->isVolatile(),
9344                         St->isNonTemporal(), St->getAlignment(),
9345                         St->getAAInfo());
9346   }
9347
9348   // If this is a legal vector store, try to combine it into a VST1_UPD.
9349   if (ISD::isNormalStore(N) && VT.isVector() &&
9350       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9351     return CombineBaseUpdate(N, DCI);
9352
9353   return SDValue();
9354 }
9355
9356 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9357 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9358 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9359 {
9360   integerPart cN;
9361   integerPart c0 = 0;
9362   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9363        I != E; I++) {
9364     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9365     if (!C)
9366       return false;
9367
9368     bool isExact;
9369     APFloat APF = C->getValueAPF();
9370     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9371         != APFloat::opOK || !isExact)
9372       return false;
9373
9374     c0 = (I == 0) ? cN : c0;
9375     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9376       return false;
9377   }
9378   C = c0;
9379   return true;
9380 }
9381
9382 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9383 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9384 /// when the VMUL has a constant operand that is a power of 2.
9385 ///
9386 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9387 ///  vmul.f32        d16, d17, d16
9388 ///  vcvt.s32.f32    d16, d16
9389 /// becomes:
9390 ///  vcvt.s32.f32    d16, d16, #3
9391 static SDValue PerformVCVTCombine(SDNode *N,
9392                                   TargetLowering::DAGCombinerInfo &DCI,
9393                                   const ARMSubtarget *Subtarget) {
9394   SelectionDAG &DAG = DCI.DAG;
9395   SDValue Op = N->getOperand(0);
9396
9397   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9398       Op.getOpcode() != ISD::FMUL)
9399     return SDValue();
9400
9401   uint64_t C;
9402   SDValue N0 = Op->getOperand(0);
9403   SDValue ConstVec = Op->getOperand(1);
9404   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9405
9406   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9407       !isConstVecPow2(ConstVec, isSigned, C))
9408     return SDValue();
9409
9410   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9411   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9412   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9413   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9414       NumLanes > 4) {
9415     // These instructions only exist converting from f32 to i32. We can handle
9416     // smaller integers by generating an extra truncate, but larger ones would
9417     // be lossy. We also can't handle more then 4 lanes, since these intructions
9418     // only support v2i32/v4i32 types.
9419     return SDValue();
9420   }
9421
9422   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9423     Intrinsic::arm_neon_vcvtfp2fxu;
9424   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9425                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9426                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9427                                  DAG.getConstant(Log2_64(C), MVT::i32));
9428
9429   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9430     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9431
9432   return FixConv;
9433 }
9434
9435 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9436 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9437 /// when the VDIV has a constant operand that is a power of 2.
9438 ///
9439 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9440 ///  vcvt.f32.s32    d16, d16
9441 ///  vdiv.f32        d16, d17, d16
9442 /// becomes:
9443 ///  vcvt.f32.s32    d16, d16, #3
9444 static SDValue PerformVDIVCombine(SDNode *N,
9445                                   TargetLowering::DAGCombinerInfo &DCI,
9446                                   const ARMSubtarget *Subtarget) {
9447   SelectionDAG &DAG = DCI.DAG;
9448   SDValue Op = N->getOperand(0);
9449   unsigned OpOpcode = Op.getNode()->getOpcode();
9450
9451   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9452       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9453     return SDValue();
9454
9455   uint64_t C;
9456   SDValue ConstVec = N->getOperand(1);
9457   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9458
9459   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9460       !isConstVecPow2(ConstVec, isSigned, C))
9461     return SDValue();
9462
9463   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9464   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9465   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9466     // These instructions only exist converting from i32 to f32. We can handle
9467     // smaller integers by generating an extra extend, but larger ones would
9468     // be lossy.
9469     return SDValue();
9470   }
9471
9472   SDValue ConvInput = Op.getOperand(0);
9473   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9474   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9475     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9476                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9477                             ConvInput);
9478
9479   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9480     Intrinsic::arm_neon_vcvtfxu2fp;
9481   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9482                      Op.getValueType(),
9483                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9484                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9485 }
9486
9487 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9488 /// operand of a vector shift operation, where all the elements of the
9489 /// build_vector must have the same constant integer value.
9490 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9491   // Ignore bit_converts.
9492   while (Op.getOpcode() == ISD::BITCAST)
9493     Op = Op.getOperand(0);
9494   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9495   APInt SplatBits, SplatUndef;
9496   unsigned SplatBitSize;
9497   bool HasAnyUndefs;
9498   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9499                                       HasAnyUndefs, ElementBits) ||
9500       SplatBitSize > ElementBits)
9501     return false;
9502   Cnt = SplatBits.getSExtValue();
9503   return true;
9504 }
9505
9506 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9507 /// operand of a vector shift left operation.  That value must be in the range:
9508 ///   0 <= Value < ElementBits for a left shift; or
9509 ///   0 <= Value <= ElementBits for a long left shift.
9510 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9511   assert(VT.isVector() && "vector shift count is not a vector type");
9512   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9513   if (! getVShiftImm(Op, ElementBits, Cnt))
9514     return false;
9515   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9516 }
9517
9518 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9519 /// operand of a vector shift right operation.  For a shift opcode, the value
9520 /// is positive, but for an intrinsic the value count must be negative. The
9521 /// absolute value must be in the range:
9522 ///   1 <= |Value| <= ElementBits for a right shift; or
9523 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9524 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9525                          int64_t &Cnt) {
9526   assert(VT.isVector() && "vector shift count is not a vector type");
9527   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9528   if (! getVShiftImm(Op, ElementBits, Cnt))
9529     return false;
9530   if (isIntrinsic)
9531     Cnt = -Cnt;
9532   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9533 }
9534
9535 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9536 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9537   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9538   switch (IntNo) {
9539   default:
9540     // Don't do anything for most intrinsics.
9541     break;
9542
9543   // Vector shifts: check for immediate versions and lower them.
9544   // Note: This is done during DAG combining instead of DAG legalizing because
9545   // the build_vectors for 64-bit vector element shift counts are generally
9546   // not legal, and it is hard to see their values after they get legalized to
9547   // loads from a constant pool.
9548   case Intrinsic::arm_neon_vshifts:
9549   case Intrinsic::arm_neon_vshiftu:
9550   case Intrinsic::arm_neon_vrshifts:
9551   case Intrinsic::arm_neon_vrshiftu:
9552   case Intrinsic::arm_neon_vrshiftn:
9553   case Intrinsic::arm_neon_vqshifts:
9554   case Intrinsic::arm_neon_vqshiftu:
9555   case Intrinsic::arm_neon_vqshiftsu:
9556   case Intrinsic::arm_neon_vqshiftns:
9557   case Intrinsic::arm_neon_vqshiftnu:
9558   case Intrinsic::arm_neon_vqshiftnsu:
9559   case Intrinsic::arm_neon_vqrshiftns:
9560   case Intrinsic::arm_neon_vqrshiftnu:
9561   case Intrinsic::arm_neon_vqrshiftnsu: {
9562     EVT VT = N->getOperand(1).getValueType();
9563     int64_t Cnt;
9564     unsigned VShiftOpc = 0;
9565
9566     switch (IntNo) {
9567     case Intrinsic::arm_neon_vshifts:
9568     case Intrinsic::arm_neon_vshiftu:
9569       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9570         VShiftOpc = ARMISD::VSHL;
9571         break;
9572       }
9573       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9574         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9575                      ARMISD::VSHRs : ARMISD::VSHRu);
9576         break;
9577       }
9578       return SDValue();
9579
9580     case Intrinsic::arm_neon_vrshifts:
9581     case Intrinsic::arm_neon_vrshiftu:
9582       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9583         break;
9584       return SDValue();
9585
9586     case Intrinsic::arm_neon_vqshifts:
9587     case Intrinsic::arm_neon_vqshiftu:
9588       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9589         break;
9590       return SDValue();
9591
9592     case Intrinsic::arm_neon_vqshiftsu:
9593       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9594         break;
9595       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9596
9597     case Intrinsic::arm_neon_vrshiftn:
9598     case Intrinsic::arm_neon_vqshiftns:
9599     case Intrinsic::arm_neon_vqshiftnu:
9600     case Intrinsic::arm_neon_vqshiftnsu:
9601     case Intrinsic::arm_neon_vqrshiftns:
9602     case Intrinsic::arm_neon_vqrshiftnu:
9603     case Intrinsic::arm_neon_vqrshiftnsu:
9604       // Narrowing shifts require an immediate right shift.
9605       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9606         break;
9607       llvm_unreachable("invalid shift count for narrowing vector shift "
9608                        "intrinsic");
9609
9610     default:
9611       llvm_unreachable("unhandled vector shift");
9612     }
9613
9614     switch (IntNo) {
9615     case Intrinsic::arm_neon_vshifts:
9616     case Intrinsic::arm_neon_vshiftu:
9617       // Opcode already set above.
9618       break;
9619     case Intrinsic::arm_neon_vrshifts:
9620       VShiftOpc = ARMISD::VRSHRs; break;
9621     case Intrinsic::arm_neon_vrshiftu:
9622       VShiftOpc = ARMISD::VRSHRu; break;
9623     case Intrinsic::arm_neon_vrshiftn:
9624       VShiftOpc = ARMISD::VRSHRN; break;
9625     case Intrinsic::arm_neon_vqshifts:
9626       VShiftOpc = ARMISD::VQSHLs; break;
9627     case Intrinsic::arm_neon_vqshiftu:
9628       VShiftOpc = ARMISD::VQSHLu; break;
9629     case Intrinsic::arm_neon_vqshiftsu:
9630       VShiftOpc = ARMISD::VQSHLsu; break;
9631     case Intrinsic::arm_neon_vqshiftns:
9632       VShiftOpc = ARMISD::VQSHRNs; break;
9633     case Intrinsic::arm_neon_vqshiftnu:
9634       VShiftOpc = ARMISD::VQSHRNu; break;
9635     case Intrinsic::arm_neon_vqshiftnsu:
9636       VShiftOpc = ARMISD::VQSHRNsu; break;
9637     case Intrinsic::arm_neon_vqrshiftns:
9638       VShiftOpc = ARMISD::VQRSHRNs; break;
9639     case Intrinsic::arm_neon_vqrshiftnu:
9640       VShiftOpc = ARMISD::VQRSHRNu; break;
9641     case Intrinsic::arm_neon_vqrshiftnsu:
9642       VShiftOpc = ARMISD::VQRSHRNsu; break;
9643     }
9644
9645     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9646                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9647   }
9648
9649   case Intrinsic::arm_neon_vshiftins: {
9650     EVT VT = N->getOperand(1).getValueType();
9651     int64_t Cnt;
9652     unsigned VShiftOpc = 0;
9653
9654     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9655       VShiftOpc = ARMISD::VSLI;
9656     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9657       VShiftOpc = ARMISD::VSRI;
9658     else {
9659       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9660     }
9661
9662     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9663                        N->getOperand(1), N->getOperand(2),
9664                        DAG.getConstant(Cnt, MVT::i32));
9665   }
9666
9667   case Intrinsic::arm_neon_vqrshifts:
9668   case Intrinsic::arm_neon_vqrshiftu:
9669     // No immediate versions of these to check for.
9670     break;
9671   }
9672
9673   return SDValue();
9674 }
9675
9676 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9677 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9678 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9679 /// vector element shift counts are generally not legal, and it is hard to see
9680 /// their values after they get legalized to loads from a constant pool.
9681 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9682                                    const ARMSubtarget *ST) {
9683   EVT VT = N->getValueType(0);
9684   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9685     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9686     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9687     SDValue N1 = N->getOperand(1);
9688     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9689       SDValue N0 = N->getOperand(0);
9690       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9691           DAG.MaskedValueIsZero(N0.getOperand(0),
9692                                 APInt::getHighBitsSet(32, 16)))
9693         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9694     }
9695   }
9696
9697   // Nothing to be done for scalar shifts.
9698   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9699   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9700     return SDValue();
9701
9702   assert(ST->hasNEON() && "unexpected vector shift");
9703   int64_t Cnt;
9704
9705   switch (N->getOpcode()) {
9706   default: llvm_unreachable("unexpected shift opcode");
9707
9708   case ISD::SHL:
9709     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9710       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9711                          DAG.getConstant(Cnt, MVT::i32));
9712     break;
9713
9714   case ISD::SRA:
9715   case ISD::SRL:
9716     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9717       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9718                             ARMISD::VSHRs : ARMISD::VSHRu);
9719       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9720                          DAG.getConstant(Cnt, MVT::i32));
9721     }
9722   }
9723   return SDValue();
9724 }
9725
9726 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9727 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9728 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9729                                     const ARMSubtarget *ST) {
9730   SDValue N0 = N->getOperand(0);
9731
9732   // Check for sign- and zero-extensions of vector extract operations of 8-
9733   // and 16-bit vector elements.  NEON supports these directly.  They are
9734   // handled during DAG combining because type legalization will promote them
9735   // to 32-bit types and it is messy to recognize the operations after that.
9736   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9737     SDValue Vec = N0.getOperand(0);
9738     SDValue Lane = N0.getOperand(1);
9739     EVT VT = N->getValueType(0);
9740     EVT EltVT = N0.getValueType();
9741     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9742
9743     if (VT == MVT::i32 &&
9744         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9745         TLI.isTypeLegal(Vec.getValueType()) &&
9746         isa<ConstantSDNode>(Lane)) {
9747
9748       unsigned Opc = 0;
9749       switch (N->getOpcode()) {
9750       default: llvm_unreachable("unexpected opcode");
9751       case ISD::SIGN_EXTEND:
9752         Opc = ARMISD::VGETLANEs;
9753         break;
9754       case ISD::ZERO_EXTEND:
9755       case ISD::ANY_EXTEND:
9756         Opc = ARMISD::VGETLANEu;
9757         break;
9758       }
9759       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9760     }
9761   }
9762
9763   return SDValue();
9764 }
9765
9766 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9767 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9768 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9769                                        const ARMSubtarget *ST) {
9770   // If the target supports NEON, try to use vmax/vmin instructions for f32
9771   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9772   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9773   // a NaN; only do the transformation when it matches that behavior.
9774
9775   // For now only do this when using NEON for FP operations; if using VFP, it
9776   // is not obvious that the benefit outweighs the cost of switching to the
9777   // NEON pipeline.
9778   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9779       N->getValueType(0) != MVT::f32)
9780     return SDValue();
9781
9782   SDValue CondLHS = N->getOperand(0);
9783   SDValue CondRHS = N->getOperand(1);
9784   SDValue LHS = N->getOperand(2);
9785   SDValue RHS = N->getOperand(3);
9786   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9787
9788   unsigned Opcode = 0;
9789   bool IsReversed;
9790   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9791     IsReversed = false; // x CC y ? x : y
9792   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9793     IsReversed = true ; // x CC y ? y : x
9794   } else {
9795     return SDValue();
9796   }
9797
9798   bool IsUnordered;
9799   switch (CC) {
9800   default: break;
9801   case ISD::SETOLT:
9802   case ISD::SETOLE:
9803   case ISD::SETLT:
9804   case ISD::SETLE:
9805   case ISD::SETULT:
9806   case ISD::SETULE:
9807     // If LHS is NaN, an ordered comparison will be false and the result will
9808     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9809     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9810     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9811     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9812       break;
9813     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9814     // will return -0, so vmin can only be used for unsafe math or if one of
9815     // the operands is known to be nonzero.
9816     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9817         !DAG.getTarget().Options.UnsafeFPMath &&
9818         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9819       break;
9820     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9821     break;
9822
9823   case ISD::SETOGT:
9824   case ISD::SETOGE:
9825   case ISD::SETGT:
9826   case ISD::SETGE:
9827   case ISD::SETUGT:
9828   case ISD::SETUGE:
9829     // If LHS is NaN, an ordered comparison will be false and the result will
9830     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9831     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9832     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9833     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9834       break;
9835     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9836     // will return +0, so vmax can only be used for unsafe math or if one of
9837     // the operands is known to be nonzero.
9838     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9839         !DAG.getTarget().Options.UnsafeFPMath &&
9840         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9841       break;
9842     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9843     break;
9844   }
9845
9846   if (!Opcode)
9847     return SDValue();
9848   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9849 }
9850
9851 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9852 SDValue
9853 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9854   SDValue Cmp = N->getOperand(4);
9855   if (Cmp.getOpcode() != ARMISD::CMPZ)
9856     // Only looking at EQ and NE cases.
9857     return SDValue();
9858
9859   EVT VT = N->getValueType(0);
9860   SDLoc dl(N);
9861   SDValue LHS = Cmp.getOperand(0);
9862   SDValue RHS = Cmp.getOperand(1);
9863   SDValue FalseVal = N->getOperand(0);
9864   SDValue TrueVal = N->getOperand(1);
9865   SDValue ARMcc = N->getOperand(2);
9866   ARMCC::CondCodes CC =
9867     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9868
9869   // Simplify
9870   //   mov     r1, r0
9871   //   cmp     r1, x
9872   //   mov     r0, y
9873   //   moveq   r0, x
9874   // to
9875   //   cmp     r0, x
9876   //   movne   r0, y
9877   //
9878   //   mov     r1, r0
9879   //   cmp     r1, x
9880   //   mov     r0, x
9881   //   movne   r0, y
9882   // to
9883   //   cmp     r0, x
9884   //   movne   r0, y
9885   /// FIXME: Turn this into a target neutral optimization?
9886   SDValue Res;
9887   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9888     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9889                       N->getOperand(3), Cmp);
9890   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9891     SDValue ARMcc;
9892     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9893     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9894                       N->getOperand(3), NewCmp);
9895   }
9896
9897   if (Res.getNode()) {
9898     APInt KnownZero, KnownOne;
9899     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9900     // Capture demanded bits information that would be otherwise lost.
9901     if (KnownZero == 0xfffffffe)
9902       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9903                         DAG.getValueType(MVT::i1));
9904     else if (KnownZero == 0xffffff00)
9905       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9906                         DAG.getValueType(MVT::i8));
9907     else if (KnownZero == 0xffff0000)
9908       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9909                         DAG.getValueType(MVT::i16));
9910   }
9911
9912   return Res;
9913 }
9914
9915 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9916                                              DAGCombinerInfo &DCI) const {
9917   switch (N->getOpcode()) {
9918   default: break;
9919   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9920   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9921   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9922   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9923   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9924   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9925   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9926   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9927   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9928   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9929   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9930   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9931   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9932   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9933   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9934   case ISD::FP_TO_SINT:
9935   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9936   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9937   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9938   case ISD::SHL:
9939   case ISD::SRA:
9940   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9941   case ISD::SIGN_EXTEND:
9942   case ISD::ZERO_EXTEND:
9943   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9944   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9945   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9946   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
9947   case ARMISD::VLD2DUP:
9948   case ARMISD::VLD3DUP:
9949   case ARMISD::VLD4DUP:
9950     return PerformVLDCombine(N, DCI);
9951   case ARMISD::BUILD_VECTOR:
9952     return PerformARMBUILD_VECTORCombine(N, DCI);
9953   case ISD::INTRINSIC_VOID:
9954   case ISD::INTRINSIC_W_CHAIN:
9955     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9956     case Intrinsic::arm_neon_vld1:
9957     case Intrinsic::arm_neon_vld2:
9958     case Intrinsic::arm_neon_vld3:
9959     case Intrinsic::arm_neon_vld4:
9960     case Intrinsic::arm_neon_vld2lane:
9961     case Intrinsic::arm_neon_vld3lane:
9962     case Intrinsic::arm_neon_vld4lane:
9963     case Intrinsic::arm_neon_vst1:
9964     case Intrinsic::arm_neon_vst2:
9965     case Intrinsic::arm_neon_vst3:
9966     case Intrinsic::arm_neon_vst4:
9967     case Intrinsic::arm_neon_vst2lane:
9968     case Intrinsic::arm_neon_vst3lane:
9969     case Intrinsic::arm_neon_vst4lane:
9970       return PerformVLDCombine(N, DCI);
9971     default: break;
9972     }
9973     break;
9974   }
9975   return SDValue();
9976 }
9977
9978 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9979                                                           EVT VT) const {
9980   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9981 }
9982
9983 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9984                                                        unsigned,
9985                                                        unsigned,
9986                                                        bool *Fast) const {
9987   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9988   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9989
9990   switch (VT.getSimpleVT().SimpleTy) {
9991   default:
9992     return false;
9993   case MVT::i8:
9994   case MVT::i16:
9995   case MVT::i32: {
9996     // Unaligned access can use (for example) LRDB, LRDH, LDR
9997     if (AllowsUnaligned) {
9998       if (Fast)
9999         *Fast = Subtarget->hasV7Ops();
10000       return true;
10001     }
10002     return false;
10003   }
10004   case MVT::f64:
10005   case MVT::v2f64: {
10006     // For any little-endian targets with neon, we can support unaligned ld/st
10007     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10008     // A big-endian target may also explicitly support unaligned accesses
10009     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10010       if (Fast)
10011         *Fast = true;
10012       return true;
10013     }
10014     return false;
10015   }
10016   }
10017 }
10018
10019 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10020                        unsigned AlignCheck) {
10021   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10022           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10023 }
10024
10025 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10026                                            unsigned DstAlign, unsigned SrcAlign,
10027                                            bool IsMemset, bool ZeroMemset,
10028                                            bool MemcpyStrSrc,
10029                                            MachineFunction &MF) const {
10030   const Function *F = MF.getFunction();
10031
10032   // See if we can use NEON instructions for this...
10033   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10034       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10035     bool Fast;
10036     if (Size >= 16 &&
10037         (memOpAlign(SrcAlign, DstAlign, 16) ||
10038          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10039       return MVT::v2f64;
10040     } else if (Size >= 8 &&
10041                (memOpAlign(SrcAlign, DstAlign, 8) ||
10042                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10043                  Fast))) {
10044       return MVT::f64;
10045     }
10046   }
10047
10048   // Lowering to i32/i16 if the size permits.
10049   if (Size >= 4)
10050     return MVT::i32;
10051   else if (Size >= 2)
10052     return MVT::i16;
10053
10054   // Let the target-independent logic figure it out.
10055   return MVT::Other;
10056 }
10057
10058 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10059   if (Val.getOpcode() != ISD::LOAD)
10060     return false;
10061
10062   EVT VT1 = Val.getValueType();
10063   if (!VT1.isSimple() || !VT1.isInteger() ||
10064       !VT2.isSimple() || !VT2.isInteger())
10065     return false;
10066
10067   switch (VT1.getSimpleVT().SimpleTy) {
10068   default: break;
10069   case MVT::i1:
10070   case MVT::i8:
10071   case MVT::i16:
10072     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10073     return true;
10074   }
10075
10076   return false;
10077 }
10078
10079 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10080   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10081     return false;
10082
10083   if (!isTypeLegal(EVT::getEVT(Ty1)))
10084     return false;
10085
10086   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10087
10088   // Assuming the caller doesn't have a zeroext or signext return parameter,
10089   // truncation all the way down to i1 is valid.
10090   return true;
10091 }
10092
10093
10094 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10095   if (V < 0)
10096     return false;
10097
10098   unsigned Scale = 1;
10099   switch (VT.getSimpleVT().SimpleTy) {
10100   default: return false;
10101   case MVT::i1:
10102   case MVT::i8:
10103     // Scale == 1;
10104     break;
10105   case MVT::i16:
10106     // Scale == 2;
10107     Scale = 2;
10108     break;
10109   case MVT::i32:
10110     // Scale == 4;
10111     Scale = 4;
10112     break;
10113   }
10114
10115   if ((V & (Scale - 1)) != 0)
10116     return false;
10117   V /= Scale;
10118   return V == (V & ((1LL << 5) - 1));
10119 }
10120
10121 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10122                                       const ARMSubtarget *Subtarget) {
10123   bool isNeg = false;
10124   if (V < 0) {
10125     isNeg = true;
10126     V = - V;
10127   }
10128
10129   switch (VT.getSimpleVT().SimpleTy) {
10130   default: return false;
10131   case MVT::i1:
10132   case MVT::i8:
10133   case MVT::i16:
10134   case MVT::i32:
10135     // + imm12 or - imm8
10136     if (isNeg)
10137       return V == (V & ((1LL << 8) - 1));
10138     return V == (V & ((1LL << 12) - 1));
10139   case MVT::f32:
10140   case MVT::f64:
10141     // Same as ARM mode. FIXME: NEON?
10142     if (!Subtarget->hasVFP2())
10143       return false;
10144     if ((V & 3) != 0)
10145       return false;
10146     V >>= 2;
10147     return V == (V & ((1LL << 8) - 1));
10148   }
10149 }
10150
10151 /// isLegalAddressImmediate - Return true if the integer value can be used
10152 /// as the offset of the target addressing mode for load / store of the
10153 /// given type.
10154 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10155                                     const ARMSubtarget *Subtarget) {
10156   if (V == 0)
10157     return true;
10158
10159   if (!VT.isSimple())
10160     return false;
10161
10162   if (Subtarget->isThumb1Only())
10163     return isLegalT1AddressImmediate(V, VT);
10164   else if (Subtarget->isThumb2())
10165     return isLegalT2AddressImmediate(V, VT, Subtarget);
10166
10167   // ARM mode.
10168   if (V < 0)
10169     V = - V;
10170   switch (VT.getSimpleVT().SimpleTy) {
10171   default: return false;
10172   case MVT::i1:
10173   case MVT::i8:
10174   case MVT::i32:
10175     // +- imm12
10176     return V == (V & ((1LL << 12) - 1));
10177   case MVT::i16:
10178     // +- imm8
10179     return V == (V & ((1LL << 8) - 1));
10180   case MVT::f32:
10181   case MVT::f64:
10182     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10183       return false;
10184     if ((V & 3) != 0)
10185       return false;
10186     V >>= 2;
10187     return V == (V & ((1LL << 8) - 1));
10188   }
10189 }
10190
10191 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10192                                                       EVT VT) const {
10193   int Scale = AM.Scale;
10194   if (Scale < 0)
10195     return false;
10196
10197   switch (VT.getSimpleVT().SimpleTy) {
10198   default: return false;
10199   case MVT::i1:
10200   case MVT::i8:
10201   case MVT::i16:
10202   case MVT::i32:
10203     if (Scale == 1)
10204       return true;
10205     // r + r << imm
10206     Scale = Scale & ~1;
10207     return Scale == 2 || Scale == 4 || Scale == 8;
10208   case MVT::i64:
10209     // r + r
10210     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10211       return true;
10212     return false;
10213   case MVT::isVoid:
10214     // Note, we allow "void" uses (basically, uses that aren't loads or
10215     // stores), because arm allows folding a scale into many arithmetic
10216     // operations.  This should be made more precise and revisited later.
10217
10218     // Allow r << imm, but the imm has to be a multiple of two.
10219     if (Scale & 1) return false;
10220     return isPowerOf2_32(Scale);
10221   }
10222 }
10223
10224 /// isLegalAddressingMode - Return true if the addressing mode represented
10225 /// by AM is legal for this target, for a load/store of the specified type.
10226 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10227                                               Type *Ty) const {
10228   EVT VT = getValueType(Ty, true);
10229   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10230     return false;
10231
10232   // Can never fold addr of global into load/store.
10233   if (AM.BaseGV)
10234     return false;
10235
10236   switch (AM.Scale) {
10237   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10238     break;
10239   case 1:
10240     if (Subtarget->isThumb1Only())
10241       return false;
10242     // FALL THROUGH.
10243   default:
10244     // ARM doesn't support any R+R*scale+imm addr modes.
10245     if (AM.BaseOffs)
10246       return false;
10247
10248     if (!VT.isSimple())
10249       return false;
10250
10251     if (Subtarget->isThumb2())
10252       return isLegalT2ScaledAddressingMode(AM, VT);
10253
10254     int Scale = AM.Scale;
10255     switch (VT.getSimpleVT().SimpleTy) {
10256     default: return false;
10257     case MVT::i1:
10258     case MVT::i8:
10259     case MVT::i32:
10260       if (Scale < 0) Scale = -Scale;
10261       if (Scale == 1)
10262         return true;
10263       // r + r << imm
10264       return isPowerOf2_32(Scale & ~1);
10265     case MVT::i16:
10266     case MVT::i64:
10267       // r + r
10268       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10269         return true;
10270       return false;
10271
10272     case MVT::isVoid:
10273       // Note, we allow "void" uses (basically, uses that aren't loads or
10274       // stores), because arm allows folding a scale into many arithmetic
10275       // operations.  This should be made more precise and revisited later.
10276
10277       // Allow r << imm, but the imm has to be a multiple of two.
10278       if (Scale & 1) return false;
10279       return isPowerOf2_32(Scale);
10280     }
10281   }
10282   return true;
10283 }
10284
10285 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10286 /// icmp immediate, that is the target has icmp instructions which can compare
10287 /// a register against the immediate without having to materialize the
10288 /// immediate into a register.
10289 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10290   // Thumb2 and ARM modes can use cmn for negative immediates.
10291   if (!Subtarget->isThumb())
10292     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10293   if (Subtarget->isThumb2())
10294     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10295   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10296   return Imm >= 0 && Imm <= 255;
10297 }
10298
10299 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10300 /// *or sub* immediate, that is the target has add or sub instructions which can
10301 /// add a register with the immediate without having to materialize the
10302 /// immediate into a register.
10303 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10304   // Same encoding for add/sub, just flip the sign.
10305   int64_t AbsImm = llvm::abs64(Imm);
10306   if (!Subtarget->isThumb())
10307     return ARM_AM::getSOImmVal(AbsImm) != -1;
10308   if (Subtarget->isThumb2())
10309     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10310   // Thumb1 only has 8-bit unsigned immediate.
10311   return AbsImm >= 0 && AbsImm <= 255;
10312 }
10313
10314 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10315                                       bool isSEXTLoad, SDValue &Base,
10316                                       SDValue &Offset, bool &isInc,
10317                                       SelectionDAG &DAG) {
10318   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10319     return false;
10320
10321   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10322     // AddressingMode 3
10323     Base = Ptr->getOperand(0);
10324     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10325       int RHSC = (int)RHS->getZExtValue();
10326       if (RHSC < 0 && RHSC > -256) {
10327         assert(Ptr->getOpcode() == ISD::ADD);
10328         isInc = false;
10329         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10330         return true;
10331       }
10332     }
10333     isInc = (Ptr->getOpcode() == ISD::ADD);
10334     Offset = Ptr->getOperand(1);
10335     return true;
10336   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10337     // AddressingMode 2
10338     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10339       int RHSC = (int)RHS->getZExtValue();
10340       if (RHSC < 0 && RHSC > -0x1000) {
10341         assert(Ptr->getOpcode() == ISD::ADD);
10342         isInc = false;
10343         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10344         Base = Ptr->getOperand(0);
10345         return true;
10346       }
10347     }
10348
10349     if (Ptr->getOpcode() == ISD::ADD) {
10350       isInc = true;
10351       ARM_AM::ShiftOpc ShOpcVal=
10352         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10353       if (ShOpcVal != ARM_AM::no_shift) {
10354         Base = Ptr->getOperand(1);
10355         Offset = Ptr->getOperand(0);
10356       } else {
10357         Base = Ptr->getOperand(0);
10358         Offset = Ptr->getOperand(1);
10359       }
10360       return true;
10361     }
10362
10363     isInc = (Ptr->getOpcode() == ISD::ADD);
10364     Base = Ptr->getOperand(0);
10365     Offset = Ptr->getOperand(1);
10366     return true;
10367   }
10368
10369   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10370   return false;
10371 }
10372
10373 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10374                                      bool isSEXTLoad, SDValue &Base,
10375                                      SDValue &Offset, bool &isInc,
10376                                      SelectionDAG &DAG) {
10377   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10378     return false;
10379
10380   Base = Ptr->getOperand(0);
10381   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10382     int RHSC = (int)RHS->getZExtValue();
10383     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10384       assert(Ptr->getOpcode() == ISD::ADD);
10385       isInc = false;
10386       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10387       return true;
10388     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10389       isInc = Ptr->getOpcode() == ISD::ADD;
10390       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10391       return true;
10392     }
10393   }
10394
10395   return false;
10396 }
10397
10398 /// getPreIndexedAddressParts - returns true by value, base pointer and
10399 /// offset pointer and addressing mode by reference if the node's address
10400 /// can be legally represented as pre-indexed load / store address.
10401 bool
10402 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10403                                              SDValue &Offset,
10404                                              ISD::MemIndexedMode &AM,
10405                                              SelectionDAG &DAG) const {
10406   if (Subtarget->isThumb1Only())
10407     return false;
10408
10409   EVT VT;
10410   SDValue Ptr;
10411   bool isSEXTLoad = false;
10412   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10413     Ptr = LD->getBasePtr();
10414     VT  = LD->getMemoryVT();
10415     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10416   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10417     Ptr = ST->getBasePtr();
10418     VT  = ST->getMemoryVT();
10419   } else
10420     return false;
10421
10422   bool isInc;
10423   bool isLegal = false;
10424   if (Subtarget->isThumb2())
10425     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10426                                        Offset, isInc, DAG);
10427   else
10428     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10429                                         Offset, isInc, DAG);
10430   if (!isLegal)
10431     return false;
10432
10433   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10434   return true;
10435 }
10436
10437 /// getPostIndexedAddressParts - returns true by value, base pointer and
10438 /// offset pointer and addressing mode by reference if this node can be
10439 /// combined with a load / store to form a post-indexed load / store.
10440 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10441                                                    SDValue &Base,
10442                                                    SDValue &Offset,
10443                                                    ISD::MemIndexedMode &AM,
10444                                                    SelectionDAG &DAG) const {
10445   if (Subtarget->isThumb1Only())
10446     return false;
10447
10448   EVT VT;
10449   SDValue Ptr;
10450   bool isSEXTLoad = false;
10451   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10452     VT  = LD->getMemoryVT();
10453     Ptr = LD->getBasePtr();
10454     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10455   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10456     VT  = ST->getMemoryVT();
10457     Ptr = ST->getBasePtr();
10458   } else
10459     return false;
10460
10461   bool isInc;
10462   bool isLegal = false;
10463   if (Subtarget->isThumb2())
10464     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10465                                        isInc, DAG);
10466   else
10467     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10468                                         isInc, DAG);
10469   if (!isLegal)
10470     return false;
10471
10472   if (Ptr != Base) {
10473     // Swap base ptr and offset to catch more post-index load / store when
10474     // it's legal. In Thumb2 mode, offset must be an immediate.
10475     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10476         !Subtarget->isThumb2())
10477       std::swap(Base, Offset);
10478
10479     // Post-indexed load / store update the base pointer.
10480     if (Ptr != Base)
10481       return false;
10482   }
10483
10484   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10485   return true;
10486 }
10487
10488 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10489                                                       APInt &KnownZero,
10490                                                       APInt &KnownOne,
10491                                                       const SelectionDAG &DAG,
10492                                                       unsigned Depth) const {
10493   unsigned BitWidth = KnownOne.getBitWidth();
10494   KnownZero = KnownOne = APInt(BitWidth, 0);
10495   switch (Op.getOpcode()) {
10496   default: break;
10497   case ARMISD::ADDC:
10498   case ARMISD::ADDE:
10499   case ARMISD::SUBC:
10500   case ARMISD::SUBE:
10501     // These nodes' second result is a boolean
10502     if (Op.getResNo() == 0)
10503       break;
10504     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10505     break;
10506   case ARMISD::CMOV: {
10507     // Bits are known zero/one if known on the LHS and RHS.
10508     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10509     if (KnownZero == 0 && KnownOne == 0) return;
10510
10511     APInt KnownZeroRHS, KnownOneRHS;
10512     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10513     KnownZero &= KnownZeroRHS;
10514     KnownOne  &= KnownOneRHS;
10515     return;
10516   }
10517   case ISD::INTRINSIC_W_CHAIN: {
10518     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10519     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10520     switch (IntID) {
10521     default: return;
10522     case Intrinsic::arm_ldaex:
10523     case Intrinsic::arm_ldrex: {
10524       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10525       unsigned MemBits = VT.getScalarType().getSizeInBits();
10526       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10527       return;
10528     }
10529     }
10530   }
10531   }
10532 }
10533
10534 //===----------------------------------------------------------------------===//
10535 //                           ARM Inline Assembly Support
10536 //===----------------------------------------------------------------------===//
10537
10538 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10539   // Looking for "rev" which is V6+.
10540   if (!Subtarget->hasV6Ops())
10541     return false;
10542
10543   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10544   std::string AsmStr = IA->getAsmString();
10545   SmallVector<StringRef, 4> AsmPieces;
10546   SplitString(AsmStr, AsmPieces, ";\n");
10547
10548   switch (AsmPieces.size()) {
10549   default: return false;
10550   case 1:
10551     AsmStr = AsmPieces[0];
10552     AsmPieces.clear();
10553     SplitString(AsmStr, AsmPieces, " \t,");
10554
10555     // rev $0, $1
10556     if (AsmPieces.size() == 3 &&
10557         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10558         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10559       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10560       if (Ty && Ty->getBitWidth() == 32)
10561         return IntrinsicLowering::LowerToByteSwap(CI);
10562     }
10563     break;
10564   }
10565
10566   return false;
10567 }
10568
10569 /// getConstraintType - Given a constraint letter, return the type of
10570 /// constraint it is for this target.
10571 ARMTargetLowering::ConstraintType
10572 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10573   if (Constraint.size() == 1) {
10574     switch (Constraint[0]) {
10575     default:  break;
10576     case 'l': return C_RegisterClass;
10577     case 'w': return C_RegisterClass;
10578     case 'h': return C_RegisterClass;
10579     case 'x': return C_RegisterClass;
10580     case 't': return C_RegisterClass;
10581     case 'j': return C_Other; // Constant for movw.
10582       // An address with a single base register. Due to the way we
10583       // currently handle addresses it is the same as an 'r' memory constraint.
10584     case 'Q': return C_Memory;
10585     }
10586   } else if (Constraint.size() == 2) {
10587     switch (Constraint[0]) {
10588     default: break;
10589     // All 'U+' constraints are addresses.
10590     case 'U': return C_Memory;
10591     }
10592   }
10593   return TargetLowering::getConstraintType(Constraint);
10594 }
10595
10596 /// Examine constraint type and operand type and determine a weight value.
10597 /// This object must already have been set up with the operand type
10598 /// and the current alternative constraint selected.
10599 TargetLowering::ConstraintWeight
10600 ARMTargetLowering::getSingleConstraintMatchWeight(
10601     AsmOperandInfo &info, const char *constraint) const {
10602   ConstraintWeight weight = CW_Invalid;
10603   Value *CallOperandVal = info.CallOperandVal;
10604     // If we don't have a value, we can't do a match,
10605     // but allow it at the lowest weight.
10606   if (!CallOperandVal)
10607     return CW_Default;
10608   Type *type = CallOperandVal->getType();
10609   // Look at the constraint type.
10610   switch (*constraint) {
10611   default:
10612     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10613     break;
10614   case 'l':
10615     if (type->isIntegerTy()) {
10616       if (Subtarget->isThumb())
10617         weight = CW_SpecificReg;
10618       else
10619         weight = CW_Register;
10620     }
10621     break;
10622   case 'w':
10623     if (type->isFloatingPointTy())
10624       weight = CW_Register;
10625     break;
10626   }
10627   return weight;
10628 }
10629
10630 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10631 RCPair
10632 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10633                                                 MVT VT) const {
10634   if (Constraint.size() == 1) {
10635     // GCC ARM Constraint Letters
10636     switch (Constraint[0]) {
10637     case 'l': // Low regs or general regs.
10638       if (Subtarget->isThumb())
10639         return RCPair(0U, &ARM::tGPRRegClass);
10640       return RCPair(0U, &ARM::GPRRegClass);
10641     case 'h': // High regs or no regs.
10642       if (Subtarget->isThumb())
10643         return RCPair(0U, &ARM::hGPRRegClass);
10644       break;
10645     case 'r':
10646       if (Subtarget->isThumb1Only())
10647         return RCPair(0U, &ARM::tGPRRegClass);
10648       return RCPair(0U, &ARM::GPRRegClass);
10649     case 'w':
10650       if (VT == MVT::Other)
10651         break;
10652       if (VT == MVT::f32)
10653         return RCPair(0U, &ARM::SPRRegClass);
10654       if (VT.getSizeInBits() == 64)
10655         return RCPair(0U, &ARM::DPRRegClass);
10656       if (VT.getSizeInBits() == 128)
10657         return RCPair(0U, &ARM::QPRRegClass);
10658       break;
10659     case 'x':
10660       if (VT == MVT::Other)
10661         break;
10662       if (VT == MVT::f32)
10663         return RCPair(0U, &ARM::SPR_8RegClass);
10664       if (VT.getSizeInBits() == 64)
10665         return RCPair(0U, &ARM::DPR_8RegClass);
10666       if (VT.getSizeInBits() == 128)
10667         return RCPair(0U, &ARM::QPR_8RegClass);
10668       break;
10669     case 't':
10670       if (VT == MVT::f32)
10671         return RCPair(0U, &ARM::SPRRegClass);
10672       break;
10673     }
10674   }
10675   if (StringRef("{cc}").equals_lower(Constraint))
10676     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10677
10678   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10679 }
10680
10681 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10682 /// vector.  If it is invalid, don't add anything to Ops.
10683 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10684                                                      std::string &Constraint,
10685                                                      std::vector<SDValue>&Ops,
10686                                                      SelectionDAG &DAG) const {
10687   SDValue Result;
10688
10689   // Currently only support length 1 constraints.
10690   if (Constraint.length() != 1) return;
10691
10692   char ConstraintLetter = Constraint[0];
10693   switch (ConstraintLetter) {
10694   default: break;
10695   case 'j':
10696   case 'I': case 'J': case 'K': case 'L':
10697   case 'M': case 'N': case 'O':
10698     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10699     if (!C)
10700       return;
10701
10702     int64_t CVal64 = C->getSExtValue();
10703     int CVal = (int) CVal64;
10704     // None of these constraints allow values larger than 32 bits.  Check
10705     // that the value fits in an int.
10706     if (CVal != CVal64)
10707       return;
10708
10709     switch (ConstraintLetter) {
10710       case 'j':
10711         // Constant suitable for movw, must be between 0 and
10712         // 65535.
10713         if (Subtarget->hasV6T2Ops())
10714           if (CVal >= 0 && CVal <= 65535)
10715             break;
10716         return;
10717       case 'I':
10718         if (Subtarget->isThumb1Only()) {
10719           // This must be a constant between 0 and 255, for ADD
10720           // immediates.
10721           if (CVal >= 0 && CVal <= 255)
10722             break;
10723         } else if (Subtarget->isThumb2()) {
10724           // A constant that can be used as an immediate value in a
10725           // data-processing instruction.
10726           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10727             break;
10728         } else {
10729           // A constant that can be used as an immediate value in a
10730           // data-processing instruction.
10731           if (ARM_AM::getSOImmVal(CVal) != -1)
10732             break;
10733         }
10734         return;
10735
10736       case 'J':
10737         if (Subtarget->isThumb()) {  // FIXME thumb2
10738           // This must be a constant between -255 and -1, for negated ADD
10739           // immediates. This can be used in GCC with an "n" modifier that
10740           // prints the negated value, for use with SUB instructions. It is
10741           // not useful otherwise but is implemented for compatibility.
10742           if (CVal >= -255 && CVal <= -1)
10743             break;
10744         } else {
10745           // This must be a constant between -4095 and 4095. It is not clear
10746           // what this constraint is intended for. Implemented for
10747           // compatibility with GCC.
10748           if (CVal >= -4095 && CVal <= 4095)
10749             break;
10750         }
10751         return;
10752
10753       case 'K':
10754         if (Subtarget->isThumb1Only()) {
10755           // A 32-bit value where only one byte has a nonzero value. Exclude
10756           // zero to match GCC. This constraint is used by GCC internally for
10757           // constants that can be loaded with a move/shift combination.
10758           // It is not useful otherwise but is implemented for compatibility.
10759           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10760             break;
10761         } else if (Subtarget->isThumb2()) {
10762           // A constant whose bitwise inverse can be used as an immediate
10763           // value in a data-processing instruction. This can be used in GCC
10764           // with a "B" modifier that prints the inverted value, for use with
10765           // BIC and MVN instructions. It is not useful otherwise but is
10766           // implemented for compatibility.
10767           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10768             break;
10769         } else {
10770           // A constant whose bitwise inverse can be used as an immediate
10771           // value in a data-processing instruction. This can be used in GCC
10772           // with a "B" modifier that prints the inverted value, for use with
10773           // BIC and MVN instructions. It is not useful otherwise but is
10774           // implemented for compatibility.
10775           if (ARM_AM::getSOImmVal(~CVal) != -1)
10776             break;
10777         }
10778         return;
10779
10780       case 'L':
10781         if (Subtarget->isThumb1Only()) {
10782           // This must be a constant between -7 and 7,
10783           // for 3-operand ADD/SUB immediate instructions.
10784           if (CVal >= -7 && CVal < 7)
10785             break;
10786         } else if (Subtarget->isThumb2()) {
10787           // A constant whose negation can be used as an immediate value in a
10788           // data-processing instruction. This can be used in GCC with an "n"
10789           // modifier that prints the negated value, for use with SUB
10790           // instructions. It is not useful otherwise but is implemented for
10791           // compatibility.
10792           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10793             break;
10794         } else {
10795           // A constant whose negation can be used as an immediate value in a
10796           // data-processing instruction. This can be used in GCC with an "n"
10797           // modifier that prints the negated value, for use with SUB
10798           // instructions. It is not useful otherwise but is implemented for
10799           // compatibility.
10800           if (ARM_AM::getSOImmVal(-CVal) != -1)
10801             break;
10802         }
10803         return;
10804
10805       case 'M':
10806         if (Subtarget->isThumb()) { // FIXME thumb2
10807           // This must be a multiple of 4 between 0 and 1020, for
10808           // ADD sp + immediate.
10809           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10810             break;
10811         } else {
10812           // A power of two or a constant between 0 and 32.  This is used in
10813           // GCC for the shift amount on shifted register operands, but it is
10814           // useful in general for any shift amounts.
10815           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10816             break;
10817         }
10818         return;
10819
10820       case 'N':
10821         if (Subtarget->isThumb()) {  // FIXME thumb2
10822           // This must be a constant between 0 and 31, for shift amounts.
10823           if (CVal >= 0 && CVal <= 31)
10824             break;
10825         }
10826         return;
10827
10828       case 'O':
10829         if (Subtarget->isThumb()) {  // FIXME thumb2
10830           // This must be a multiple of 4 between -508 and 508, for
10831           // ADD/SUB sp = sp + immediate.
10832           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10833             break;
10834         }
10835         return;
10836     }
10837     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10838     break;
10839   }
10840
10841   if (Result.getNode()) {
10842     Ops.push_back(Result);
10843     return;
10844   }
10845   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10846 }
10847
10848 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10849   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10850   unsigned Opcode = Op->getOpcode();
10851   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10852          "Invalid opcode for Div/Rem lowering");
10853   bool isSigned = (Opcode == ISD::SDIVREM);
10854   EVT VT = Op->getValueType(0);
10855   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10856
10857   RTLIB::Libcall LC;
10858   switch (VT.getSimpleVT().SimpleTy) {
10859   default: llvm_unreachable("Unexpected request for libcall!");
10860   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10861   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10862   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10863   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10864   }
10865
10866   SDValue InChain = DAG.getEntryNode();
10867
10868   TargetLowering::ArgListTy Args;
10869   TargetLowering::ArgListEntry Entry;
10870   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10871     EVT ArgVT = Op->getOperand(i).getValueType();
10872     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10873     Entry.Node = Op->getOperand(i);
10874     Entry.Ty = ArgTy;
10875     Entry.isSExt = isSigned;
10876     Entry.isZExt = !isSigned;
10877     Args.push_back(Entry);
10878   }
10879
10880   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10881                                          getPointerTy());
10882
10883   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10884
10885   SDLoc dl(Op);
10886   TargetLowering::CallLoweringInfo CLI(DAG);
10887   CLI.setDebugLoc(dl).setChain(InChain)
10888     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10889     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10890
10891   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10892   return CallInfo.first;
10893 }
10894
10895 SDValue
10896 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10897   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10898   SDLoc DL(Op);
10899
10900   // Get the inputs.
10901   SDValue Chain = Op.getOperand(0);
10902   SDValue Size  = Op.getOperand(1);
10903
10904   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10905                               DAG.getConstant(2, MVT::i32));
10906
10907   SDValue Flag;
10908   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10909   Flag = Chain.getValue(1);
10910
10911   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10912   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10913
10914   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10915   Chain = NewSP.getValue(1);
10916
10917   SDValue Ops[2] = { NewSP, Chain };
10918   return DAG.getMergeValues(Ops, DL);
10919 }
10920
10921 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10922   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10923          "Unexpected type for custom-lowering FP_EXTEND");
10924
10925   RTLIB::Libcall LC;
10926   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10927
10928   SDValue SrcVal = Op.getOperand(0);
10929   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10930                      /*isSigned*/ false, SDLoc(Op)).first;
10931 }
10932
10933 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10934   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10935          Subtarget->isFPOnlySP() &&
10936          "Unexpected type for custom-lowering FP_ROUND");
10937
10938   RTLIB::Libcall LC;
10939   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10940
10941   SDValue SrcVal = Op.getOperand(0);
10942   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10943                      /*isSigned*/ false, SDLoc(Op)).first;
10944 }
10945
10946 bool
10947 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10948   // The ARM target isn't yet aware of offsets.
10949   return false;
10950 }
10951
10952 bool ARM::isBitFieldInvertedMask(unsigned v) {
10953   if (v == 0xffffffff)
10954     return false;
10955
10956   // there can be 1's on either or both "outsides", all the "inside"
10957   // bits must be 0's
10958   return isShiftedMask_32(~v);
10959 }
10960
10961 /// isFPImmLegal - Returns true if the target can instruction select the
10962 /// specified FP immediate natively. If false, the legalizer will
10963 /// materialize the FP immediate as a load from a constant pool.
10964 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10965   if (!Subtarget->hasVFP3())
10966     return false;
10967   if (VT == MVT::f32)
10968     return ARM_AM::getFP32Imm(Imm) != -1;
10969   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10970     return ARM_AM::getFP64Imm(Imm) != -1;
10971   return false;
10972 }
10973
10974 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10975 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10976 /// specified in the intrinsic calls.
10977 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10978                                            const CallInst &I,
10979                                            unsigned Intrinsic) const {
10980   switch (Intrinsic) {
10981   case Intrinsic::arm_neon_vld1:
10982   case Intrinsic::arm_neon_vld2:
10983   case Intrinsic::arm_neon_vld3:
10984   case Intrinsic::arm_neon_vld4:
10985   case Intrinsic::arm_neon_vld2lane:
10986   case Intrinsic::arm_neon_vld3lane:
10987   case Intrinsic::arm_neon_vld4lane: {
10988     Info.opc = ISD::INTRINSIC_W_CHAIN;
10989     // Conservatively set memVT to the entire set of vectors loaded.
10990     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10991     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10992     Info.ptrVal = I.getArgOperand(0);
10993     Info.offset = 0;
10994     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10995     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10996     Info.vol = false; // volatile loads with NEON intrinsics not supported
10997     Info.readMem = true;
10998     Info.writeMem = false;
10999     return true;
11000   }
11001   case Intrinsic::arm_neon_vst1:
11002   case Intrinsic::arm_neon_vst2:
11003   case Intrinsic::arm_neon_vst3:
11004   case Intrinsic::arm_neon_vst4:
11005   case Intrinsic::arm_neon_vst2lane:
11006   case Intrinsic::arm_neon_vst3lane:
11007   case Intrinsic::arm_neon_vst4lane: {
11008     Info.opc = ISD::INTRINSIC_VOID;
11009     // Conservatively set memVT to the entire set of vectors stored.
11010     unsigned NumElts = 0;
11011     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11012       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11013       if (!ArgTy->isVectorTy())
11014         break;
11015       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11016     }
11017     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11018     Info.ptrVal = I.getArgOperand(0);
11019     Info.offset = 0;
11020     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11021     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11022     Info.vol = false; // volatile stores with NEON intrinsics not supported
11023     Info.readMem = false;
11024     Info.writeMem = true;
11025     return true;
11026   }
11027   case Intrinsic::arm_ldaex:
11028   case Intrinsic::arm_ldrex: {
11029     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11030     Info.opc = ISD::INTRINSIC_W_CHAIN;
11031     Info.memVT = MVT::getVT(PtrTy->getElementType());
11032     Info.ptrVal = I.getArgOperand(0);
11033     Info.offset = 0;
11034     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11035     Info.vol = true;
11036     Info.readMem = true;
11037     Info.writeMem = false;
11038     return true;
11039   }
11040   case Intrinsic::arm_stlex:
11041   case Intrinsic::arm_strex: {
11042     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11043     Info.opc = ISD::INTRINSIC_W_CHAIN;
11044     Info.memVT = MVT::getVT(PtrTy->getElementType());
11045     Info.ptrVal = I.getArgOperand(1);
11046     Info.offset = 0;
11047     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11048     Info.vol = true;
11049     Info.readMem = false;
11050     Info.writeMem = true;
11051     return true;
11052   }
11053   case Intrinsic::arm_stlexd:
11054   case Intrinsic::arm_strexd: {
11055     Info.opc = ISD::INTRINSIC_W_CHAIN;
11056     Info.memVT = MVT::i64;
11057     Info.ptrVal = I.getArgOperand(2);
11058     Info.offset = 0;
11059     Info.align = 8;
11060     Info.vol = true;
11061     Info.readMem = false;
11062     Info.writeMem = true;
11063     return true;
11064   }
11065   case Intrinsic::arm_ldaexd:
11066   case Intrinsic::arm_ldrexd: {
11067     Info.opc = ISD::INTRINSIC_W_CHAIN;
11068     Info.memVT = MVT::i64;
11069     Info.ptrVal = I.getArgOperand(0);
11070     Info.offset = 0;
11071     Info.align = 8;
11072     Info.vol = true;
11073     Info.readMem = true;
11074     Info.writeMem = false;
11075     return true;
11076   }
11077   default:
11078     break;
11079   }
11080
11081   return false;
11082 }
11083
11084 /// \brief Returns true if it is beneficial to convert a load of a constant
11085 /// to just the constant itself.
11086 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11087                                                           Type *Ty) const {
11088   assert(Ty->isIntegerTy());
11089
11090   unsigned Bits = Ty->getPrimitiveSizeInBits();
11091   if (Bits == 0 || Bits > 32)
11092     return false;
11093   return true;
11094 }
11095
11096 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11097
11098 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11099                                         ARM_MB::MemBOpt Domain) const {
11100   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11101
11102   // First, if the target has no DMB, see what fallback we can use.
11103   if (!Subtarget->hasDataBarrier()) {
11104     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11105     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11106     // here.
11107     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11108       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11109       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11110                         Builder.getInt32(0), Builder.getInt32(7),
11111                         Builder.getInt32(10), Builder.getInt32(5)};
11112       return Builder.CreateCall(MCR, args);
11113     } else {
11114       // Instead of using barriers, atomic accesses on these subtargets use
11115       // libcalls.
11116       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11117     }
11118   } else {
11119     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11120     // Only a full system barrier exists in the M-class architectures.
11121     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11122     Constant *CDomain = Builder.getInt32(Domain);
11123     return Builder.CreateCall(DMB, CDomain);
11124   }
11125 }
11126
11127 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11128 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11129                                          AtomicOrdering Ord, bool IsStore,
11130                                          bool IsLoad) const {
11131   if (!getInsertFencesForAtomic())
11132     return nullptr;
11133
11134   switch (Ord) {
11135   case NotAtomic:
11136   case Unordered:
11137     llvm_unreachable("Invalid fence: unordered/non-atomic");
11138   case Monotonic:
11139   case Acquire:
11140     return nullptr; // Nothing to do
11141   case SequentiallyConsistent:
11142     if (!IsStore)
11143       return nullptr; // Nothing to do
11144     /*FALLTHROUGH*/
11145   case Release:
11146   case AcquireRelease:
11147     if (Subtarget->isSwift())
11148       return makeDMB(Builder, ARM_MB::ISHST);
11149     // FIXME: add a comment with a link to documentation justifying this.
11150     else
11151       return makeDMB(Builder, ARM_MB::ISH);
11152   }
11153   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11154 }
11155
11156 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11157                                           AtomicOrdering Ord, bool IsStore,
11158                                           bool IsLoad) const {
11159   if (!getInsertFencesForAtomic())
11160     return nullptr;
11161
11162   switch (Ord) {
11163   case NotAtomic:
11164   case Unordered:
11165     llvm_unreachable("Invalid fence: unordered/not-atomic");
11166   case Monotonic:
11167   case Release:
11168     return nullptr; // Nothing to do
11169   case Acquire:
11170   case AcquireRelease:
11171   case SequentiallyConsistent:
11172     return makeDMB(Builder, ARM_MB::ISH);
11173   }
11174   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11175 }
11176
11177 // Loads and stores less than 64-bits are already atomic; ones above that
11178 // are doomed anyway, so defer to the default libcall and blame the OS when
11179 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11180 // anything for those.
11181 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11182   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11183   return (Size == 64) && !Subtarget->isMClass();
11184 }
11185
11186 // Loads and stores less than 64-bits are already atomic; ones above that
11187 // are doomed anyway, so defer to the default libcall and blame the OS when
11188 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11189 // anything for those.
11190 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11191 // guarantee, see DDI0406C ARM architecture reference manual,
11192 // sections A8.8.72-74 LDRD)
11193 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11194   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11195   return (Size == 64) && !Subtarget->isMClass();
11196 }
11197
11198 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11199 // and up to 64 bits on the non-M profiles
11200 bool ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11201   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11202   return Size <= (Subtarget->isMClass() ? 32U : 64U);
11203 }
11204
11205 // This has so far only been implemented for MachO.
11206 bool ARMTargetLowering::useLoadStackGuardNode() const {
11207   return Subtarget->isTargetMachO();
11208 }
11209
11210 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11211                                                   unsigned &Cost) const {
11212   // If we do not have NEON, vector types are not natively supported.
11213   if (!Subtarget->hasNEON())
11214     return false;
11215
11216   // Floating point values and vector values map to the same register file.
11217   // Therefore, althought we could do a store extract of a vector type, this is
11218   // better to leave at float as we have more freedom in the addressing mode for
11219   // those.
11220   if (VectorTy->isFPOrFPVectorTy())
11221     return false;
11222
11223   // If the index is unknown at compile time, this is very expensive to lower
11224   // and it is not possible to combine the store with the extract.
11225   if (!isa<ConstantInt>(Idx))
11226     return false;
11227
11228   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11229   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11230   // We can do a store + vector extract on any vector that fits perfectly in a D
11231   // or Q register.
11232   if (BitWidth == 64 || BitWidth == 128) {
11233     Cost = 0;
11234     return true;
11235   }
11236   return false;
11237 }
11238
11239 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11240                                          AtomicOrdering Ord) const {
11241   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11242   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11243   bool IsAcquire = isAtLeastAcquire(Ord);
11244
11245   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11246   // intrinsic must return {i32, i32} and we have to recombine them into a
11247   // single i64 here.
11248   if (ValTy->getPrimitiveSizeInBits() == 64) {
11249     Intrinsic::ID Int =
11250         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11251     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11252
11253     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11254     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11255
11256     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11257     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11258     if (!Subtarget->isLittle())
11259       std::swap (Lo, Hi);
11260     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11261     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11262     return Builder.CreateOr(
11263         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11264   }
11265
11266   Type *Tys[] = { Addr->getType() };
11267   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11268   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11269
11270   return Builder.CreateTruncOrBitCast(
11271       Builder.CreateCall(Ldrex, Addr),
11272       cast<PointerType>(Addr->getType())->getElementType());
11273 }
11274
11275 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11276                                                Value *Addr,
11277                                                AtomicOrdering Ord) const {
11278   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11279   bool IsRelease = isAtLeastRelease(Ord);
11280
11281   // Since the intrinsics must have legal type, the i64 intrinsics take two
11282   // parameters: "i32, i32". We must marshal Val into the appropriate form
11283   // before the call.
11284   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11285     Intrinsic::ID Int =
11286         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11287     Function *Strex = Intrinsic::getDeclaration(M, Int);
11288     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11289
11290     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11291     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11292     if (!Subtarget->isLittle())
11293       std::swap (Lo, Hi);
11294     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11295     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11296   }
11297
11298   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11299   Type *Tys[] = { Addr->getType() };
11300   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11301
11302   return Builder.CreateCall2(
11303       Strex, Builder.CreateZExtOrBitCast(
11304                  Val, Strex->getFunctionType()->getParamType(0)),
11305       Addr);
11306 }
11307
11308 enum HABaseType {
11309   HA_UNKNOWN = 0,
11310   HA_FLOAT,
11311   HA_DOUBLE,
11312   HA_VECT64,
11313   HA_VECT128
11314 };
11315
11316 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11317                                    uint64_t &Members) {
11318   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11319     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11320       uint64_t SubMembers = 0;
11321       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11322         return false;
11323       Members += SubMembers;
11324     }
11325   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11326     uint64_t SubMembers = 0;
11327     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11328       return false;
11329     Members += SubMembers * AT->getNumElements();
11330   } else if (Ty->isFloatTy()) {
11331     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11332       return false;
11333     Members = 1;
11334     Base = HA_FLOAT;
11335   } else if (Ty->isDoubleTy()) {
11336     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11337       return false;
11338     Members = 1;
11339     Base = HA_DOUBLE;
11340   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11341     Members = 1;
11342     switch (Base) {
11343     case HA_FLOAT:
11344     case HA_DOUBLE:
11345       return false;
11346     case HA_VECT64:
11347       return VT->getBitWidth() == 64;
11348     case HA_VECT128:
11349       return VT->getBitWidth() == 128;
11350     case HA_UNKNOWN:
11351       switch (VT->getBitWidth()) {
11352       case 64:
11353         Base = HA_VECT64;
11354         return true;
11355       case 128:
11356         Base = HA_VECT128;
11357         return true;
11358       default:
11359         return false;
11360       }
11361     }
11362   }
11363
11364   return (Members > 0 && Members <= 4);
11365 }
11366
11367 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11368 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11369 /// passing according to AAPCS rules.
11370 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11371     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11372   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11373       CallingConv::ARM_AAPCS_VFP)
11374     return false;
11375
11376   HABaseType Base = HA_UNKNOWN;
11377   uint64_t Members = 0;
11378   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11379   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11380
11381   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11382   return IsHA || IsIntArray;
11383 }