Make constant arrays that are passed to functions as const.
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/IR/Type.h"
46 #include "llvm/MC/MCSectionMachO.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <utility>
53 using namespace llvm;
54
55 #define DEBUG_TYPE "arm-isel"
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
59 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
60
61 cl::opt<bool>
62 EnableARMLongCalls("arm-long-calls", cl::Hidden,
63   cl::desc("Generate calls via indirect call instructions"),
64   cl::init(false));
65
66 static cl::opt<bool>
67 ARMInterworking("arm-interworking", cl::Hidden,
68   cl::desc("Enable / disable ARM interworking (for debugging only)"),
69   cl::init(true));
70
71 namespace {
72   class ARMCCState : public CCState {
73   public:
74     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
75                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
76                ParmContext PC)
77         : CCState(CC, isVarArg, MF, locs, C) {
78       assert(((PC == Call) || (PC == Prologue)) &&
79              "ARMCCState users must specify whether their context is call"
80              "or prologue generation.");
81       CallOrPrologue = PC;
82     }
83   };
84 }
85
86 // The APCS parameter registers.
87 static const MCPhysReg GPRArgRegs[] = {
88   ARM::R0, ARM::R1, ARM::R2, ARM::R3
89 };
90
91 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
92                                        MVT PromotedBitwiseVT) {
93   if (VT != PromotedLdStVT) {
94     setOperationAction(ISD::LOAD, VT, Promote);
95     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
96
97     setOperationAction(ISD::STORE, VT, Promote);
98     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
99   }
100
101   MVT ElemTy = VT.getVectorElementType();
102   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
103     setOperationAction(ISD::SETCC, VT, Custom);
104   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
105   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
106   if (ElemTy == MVT::i32) {
107     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
108     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
109     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
110     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
111   } else {
112     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
113     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
114     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
115     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
116   }
117   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
118   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
119   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
120   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
121   setOperationAction(ISD::SELECT,            VT, Expand);
122   setOperationAction(ISD::SELECT_CC,         VT, Expand);
123   setOperationAction(ISD::VSELECT,           VT, Expand);
124   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
125   if (VT.isInteger()) {
126     setOperationAction(ISD::SHL, VT, Custom);
127     setOperationAction(ISD::SRA, VT, Custom);
128     setOperationAction(ISD::SRL, VT, Custom);
129   }
130
131   // Promote all bit-wise operations.
132   if (VT.isInteger() && VT != PromotedBitwiseVT) {
133     setOperationAction(ISD::AND, VT, Promote);
134     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
135     setOperationAction(ISD::OR,  VT, Promote);
136     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
137     setOperationAction(ISD::XOR, VT, Promote);
138     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
139   }
140
141   // Neon does not support vector divide/remainder operations.
142   setOperationAction(ISD::SDIV, VT, Expand);
143   setOperationAction(ISD::UDIV, VT, Expand);
144   setOperationAction(ISD::FDIV, VT, Expand);
145   setOperationAction(ISD::SREM, VT, Expand);
146   setOperationAction(ISD::UREM, VT, Expand);
147   setOperationAction(ISD::FREM, VT, Expand);
148 }
149
150 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
151   addRegisterClass(VT, &ARM::DPRRegClass);
152   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
153 }
154
155 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
156   addRegisterClass(VT, &ARM::DPairRegClass);
157   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
158 }
159
160 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
161                                      const ARMSubtarget &STI)
162     : TargetLowering(TM), Subtarget(&STI) {
163   RegInfo = Subtarget->getRegisterInfo();
164   Itins = Subtarget->getInstrItineraryData();
165
166   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
167
168   if (Subtarget->isTargetMachO()) {
169     // Uses VFP for Thumb libfuncs if available.
170     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
171         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
172       // Single-precision floating-point arithmetic.
173       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
174       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
175       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
176       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
177
178       // Double-precision floating-point arithmetic.
179       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
180       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
181       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
182       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
183
184       // Single-precision comparisons.
185       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
186       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
187       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
188       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
189       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
190       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
191       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
192       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
193
194       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
195       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
196       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
197       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
198       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
199       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
200       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
201       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
202
203       // Double-precision comparisons.
204       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
205       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
206       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
207       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
208       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
209       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
210       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
211       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
212
213       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
214       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
215       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
216       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
217       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
218       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
219       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
220       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
221
222       // Floating-point to integer conversions.
223       // i64 conversions are done via library routines even when generating VFP
224       // instructions, so use the same ones.
225       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
226       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
227       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
228       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
229
230       // Conversions between floating types.
231       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
232       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
233
234       // Integer to floating-point conversions.
235       // i64 conversions are done via library routines even when generating VFP
236       // instructions, so use the same ones.
237       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
238       // e.g., __floatunsidf vs. __floatunssidfvfp.
239       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
240       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
241       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
242       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
243     }
244   }
245
246   // These libcalls are not available in 32-bit.
247   setLibcallName(RTLIB::SHL_I128, nullptr);
248   setLibcallName(RTLIB::SRL_I128, nullptr);
249   setLibcallName(RTLIB::SRA_I128, nullptr);
250
251   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
252       !Subtarget->isTargetWindows()) {
253     static const struct {
254       const RTLIB::Libcall Op;
255       const char * const Name;
256       const CallingConv::ID CC;
257       const ISD::CondCode Cond;
258     } LibraryCalls[] = {
259       // Double-precision floating-point arithmetic helper functions
260       // RTABI chapter 4.1.2, Table 2
261       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
262       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
263       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265
266       // Double-precision floating-point comparison helper functions
267       // RTABI chapter 4.1.2, Table 3
268       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
269       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
270       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
271       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
272       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
273       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
274       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
276
277       // Single-precision floating-point arithmetic helper functions
278       // RTABI chapter 4.1.2, Table 4
279       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
280       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
281       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283
284       // Single-precision floating-point comparison helper functions
285       // RTABI chapter 4.1.2, Table 5
286       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
287       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
288       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
289       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
290       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
291       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
292       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
294
295       // Floating-point to integer conversions.
296       // RTABI chapter 4.1.2, Table 6
297       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
298       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305
306       // Conversions between floating types.
307       // RTABI chapter 4.1.2, Table 7
308       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311
312       // Integer to floating-point conversions.
313       // RTABI chapter 4.1.2, Table 8
314       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322
323       // Long long helper functions
324       // RTABI chapter 4.2, Table 9
325       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329
330       // Integer division functions
331       // RTABI chapter 4.3.1
332       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340
341       // Memory operations
342       // RTABI chapter 4.3.4
343       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346     };
347
348     for (const auto &LC : LibraryCalls) {
349       setLibcallName(LC.Op, LC.Name);
350       setLibcallCallingConv(LC.Op, LC.CC);
351       if (LC.Cond != ISD::SETCC_INVALID)
352         setCmpLibcallCC(LC.Op, LC.Cond);
353     }
354   }
355
356   if (Subtarget->isTargetWindows()) {
357     static const struct {
358       const RTLIB::Libcall Op;
359       const char * const Name;
360       const CallingConv::ID CC;
361     } LibraryCalls[] = {
362       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
363       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
364       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
366       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
367       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
370     };
371
372     for (const auto &LC : LibraryCalls) {
373       setLibcallName(LC.Op, LC.Name);
374       setLibcallCallingConv(LC.Op, LC.CC);
375     }
376   }
377
378   // Use divmod compiler-rt calls for iOS 5.0 and later.
379   if (Subtarget->getTargetTriple().isiOS() &&
380       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
381     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
382     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
383   }
384
385   // The half <-> float conversion functions are always soft-float, but are
386   // needed for some targets which use a hard-float calling convention by
387   // default.
388   if (Subtarget->isAAPCS_ABI()) {
389     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
392   } else {
393     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
394     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
395     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
396   }
397
398   if (Subtarget->isThumb1Only())
399     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
400   else
401     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
402   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
403       !Subtarget->isThumb1Only()) {
404     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
405     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
406   }
407
408   for (MVT VT : MVT::vector_valuetypes()) {
409     for (MVT InnerVT : MVT::vector_valuetypes()) {
410       setTruncStoreAction(VT, InnerVT, Expand);
411       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
412       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
413       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
414     }
415
416     setOperationAction(ISD::MULHS, VT, Expand);
417     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
418     setOperationAction(ISD::MULHU, VT, Expand);
419     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
420
421     setOperationAction(ISD::BSWAP, VT, Expand);
422   }
423
424   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
425   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
426
427   if (Subtarget->hasNEON()) {
428     addDRTypeForNEON(MVT::v2f32);
429     addDRTypeForNEON(MVT::v8i8);
430     addDRTypeForNEON(MVT::v4i16);
431     addDRTypeForNEON(MVT::v2i32);
432     addDRTypeForNEON(MVT::v1i64);
433
434     addQRTypeForNEON(MVT::v4f32);
435     addQRTypeForNEON(MVT::v2f64);
436     addQRTypeForNEON(MVT::v16i8);
437     addQRTypeForNEON(MVT::v8i16);
438     addQRTypeForNEON(MVT::v4i32);
439     addQRTypeForNEON(MVT::v2i64);
440
441     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
442     // neither Neon nor VFP support any arithmetic operations on it.
443     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
444     // supported for v4f32.
445     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
446     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
447     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
448     // FIXME: Code duplication: FDIV and FREM are expanded always, see
449     // ARMTargetLowering::addTypeForNEON method for details.
450     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
451     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
452     // FIXME: Create unittest.
453     // In another words, find a way when "copysign" appears in DAG with vector
454     // operands.
455     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
456     // FIXME: Code duplication: SETCC has custom operation action, see
457     // ARMTargetLowering::addTypeForNEON method for details.
458     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
459     // FIXME: Create unittest for FNEG and for FABS.
460     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
461     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
462     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
463     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
464     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
465     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
466     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
467     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
468     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
469     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
470     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
471     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
472     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
473     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
474     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
475     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
476     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
477     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
478     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
479
480     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
481     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
482     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
483     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
484     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
485     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
486     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
487     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
488     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
489     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
490     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
491     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
492     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
493     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
494     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
495
496     // Mark v2f32 intrinsics.
497     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
498     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
499     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
500     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
501     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
502     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
503     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
504     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
505     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
506     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
507     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
508     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
509     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
510     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
511     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
512
513     // Neon does not support some operations on v1i64 and v2i64 types.
514     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
515     // Custom handling for some quad-vector types to detect VMULL.
516     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
517     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
518     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
519     // Custom handling for some vector types to avoid expensive expansions
520     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
521     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
522     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
523     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
524     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
525     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
526     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
527     // a destination type that is wider than the source, and nor does
528     // it have a FP_TO_[SU]INT instruction with a narrower destination than
529     // source.
530     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
531     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
532     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
533     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
534
535     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
536     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
537
538     // NEON does not have single instruction CTPOP for vectors with element
539     // types wider than 8-bits.  However, custom lowering can leverage the
540     // v8i8/v16i8 vcnt instruction.
541     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
542     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
543     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
544     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
545
546     // NEON only has FMA instructions as of VFP4.
547     if (!Subtarget->hasVFP4()) {
548       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
549       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
550     }
551
552     setTargetDAGCombine(ISD::INTRINSIC_VOID);
553     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
554     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
555     setTargetDAGCombine(ISD::SHL);
556     setTargetDAGCombine(ISD::SRL);
557     setTargetDAGCombine(ISD::SRA);
558     setTargetDAGCombine(ISD::SIGN_EXTEND);
559     setTargetDAGCombine(ISD::ZERO_EXTEND);
560     setTargetDAGCombine(ISD::ANY_EXTEND);
561     setTargetDAGCombine(ISD::SELECT_CC);
562     setTargetDAGCombine(ISD::BUILD_VECTOR);
563     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
564     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
565     setTargetDAGCombine(ISD::STORE);
566     setTargetDAGCombine(ISD::FP_TO_SINT);
567     setTargetDAGCombine(ISD::FP_TO_UINT);
568     setTargetDAGCombine(ISD::FDIV);
569     setTargetDAGCombine(ISD::LOAD);
570
571     // It is legal to extload from v4i8 to v4i16 or v4i32.
572     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
573                    MVT::v2i32}) {
574       for (MVT VT : MVT::integer_vector_valuetypes()) {
575         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
576         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
577         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
578       }
579     }
580   }
581
582   // ARM and Thumb2 support UMLAL/SMLAL.
583   if (!Subtarget->isThumb1Only())
584     setTargetDAGCombine(ISD::ADDC);
585
586   if (Subtarget->isFPOnlySP()) {
587     // When targetting a floating-point unit with only single-precision
588     // operations, f64 is legal for the few double-precision instructions which
589     // are present However, no double-precision operations other than moves,
590     // loads and stores are provided by the hardware.
591     setOperationAction(ISD::FADD,       MVT::f64, Expand);
592     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
593     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
594     setOperationAction(ISD::FMA,        MVT::f64, Expand);
595     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
596     setOperationAction(ISD::FREM,       MVT::f64, Expand);
597     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
598     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
599     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
600     setOperationAction(ISD::FABS,       MVT::f64, Expand);
601     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
602     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
603     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
604     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
605     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
606     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
607     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
608     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
609     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
610     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
611     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
612     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
613     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
614     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
615     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
616     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
617     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
618   }
619
620   computeRegisterProperties(Subtarget->getRegisterInfo());
621
622   // ARM does not have floating-point extending loads.
623   for (MVT VT : MVT::fp_valuetypes()) {
624     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
625     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
626   }
627
628   // ... or truncating stores
629   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
630   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
631   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
632
633   // ARM does not have i1 sign extending load.
634   for (MVT VT : MVT::integer_valuetypes())
635     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
636
637   // ARM supports all 4 flavors of integer indexed load / store.
638   if (!Subtarget->isThumb1Only()) {
639     for (unsigned im = (unsigned)ISD::PRE_INC;
640          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
641       setIndexedLoadAction(im,  MVT::i1,  Legal);
642       setIndexedLoadAction(im,  MVT::i8,  Legal);
643       setIndexedLoadAction(im,  MVT::i16, Legal);
644       setIndexedLoadAction(im,  MVT::i32, Legal);
645       setIndexedStoreAction(im, MVT::i1,  Legal);
646       setIndexedStoreAction(im, MVT::i8,  Legal);
647       setIndexedStoreAction(im, MVT::i16, Legal);
648       setIndexedStoreAction(im, MVT::i32, Legal);
649     }
650   }
651
652   setOperationAction(ISD::SADDO, MVT::i32, Custom);
653   setOperationAction(ISD::UADDO, MVT::i32, Custom);
654   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
655   setOperationAction(ISD::USUBO, MVT::i32, Custom);
656
657   // i64 operation support.
658   setOperationAction(ISD::MUL,     MVT::i64, Expand);
659   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
660   if (Subtarget->isThumb1Only()) {
661     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
662     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
663   }
664   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
665       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
666     setOperationAction(ISD::MULHS, MVT::i32, Expand);
667
668   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
669   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
670   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
671   setOperationAction(ISD::SRL,       MVT::i64, Custom);
672   setOperationAction(ISD::SRA,       MVT::i64, Custom);
673
674   if (!Subtarget->isThumb1Only()) {
675     // FIXME: We should do this for Thumb1 as well.
676     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
677     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
678     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
679     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
680   }
681
682   // ARM does not have ROTL.
683   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
684   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
685   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
686   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
687     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
688
689   // These just redirect to CTTZ and CTLZ on ARM.
690   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
691   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
692
693   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
694
695   // Only ARMv6 has BSWAP.
696   if (!Subtarget->hasV6Ops())
697     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
698
699   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
700       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
701     // These are expanded into libcalls if the cpu doesn't have HW divider.
702     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
703     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
704   }
705
706   // FIXME: Also set divmod for SREM on EABI
707   setOperationAction(ISD::SREM,  MVT::i32, Expand);
708   setOperationAction(ISD::UREM,  MVT::i32, Expand);
709   // Register based DivRem for AEABI (RTABI 4.2)
710   if (Subtarget->isTargetAEABI()) {
711     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
712     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
713     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
714     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
715     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
716     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
717     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
718     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
719
720     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
721     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
722     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
723     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
724     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
725     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
726     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
727     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
728
729     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
730     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
731   } else {
732     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
733     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
734   }
735
736   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
737   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
738   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
739   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
740   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
741
742   setOperationAction(ISD::TRAP, MVT::Other, Legal);
743
744   // Use the default implementation.
745   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
746   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
747   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
748   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
749   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
750   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
751
752   if (!Subtarget->isTargetMachO()) {
753     // Non-MachO platforms may return values in these registers via the
754     // personality function.
755     setExceptionPointerRegister(ARM::R0);
756     setExceptionSelectorRegister(ARM::R1);
757   }
758
759   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
760     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
761   else
762     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
763
764   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
765   // the default expansion. If we are targeting a single threaded system,
766   // then set them all for expand so we can lower them later into their
767   // non-atomic form.
768   if (TM.Options.ThreadModel == ThreadModel::Single)
769     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
770   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
771     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
772     // to ldrex/strex loops already.
773     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
774
775     // On v8, we have particularly efficient implementations of atomic fences
776     // if they can be combined with nearby atomic loads and stores.
777     if (!Subtarget->hasV8Ops()) {
778       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
779       setInsertFencesForAtomic(true);
780     }
781   } else {
782     // If there's anything we can use as a barrier, go through custom lowering
783     // for ATOMIC_FENCE.
784     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
785                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
786
787     // Set them all for expansion, which will force libcalls.
788     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
789     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
790     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
791     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
792     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
793     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
794     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
795     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
796     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
800     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
801     // Unordered/Monotonic case.
802     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
803     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
804   }
805
806   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
807
808   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
809   if (!Subtarget->hasV6Ops()) {
810     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
811     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
812   }
813   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
814
815   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
816       !Subtarget->isThumb1Only()) {
817     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
818     // iff target supports vfp2.
819     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
820     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
821   }
822
823   // We want to custom lower some of our intrinsics.
824   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
825   if (Subtarget->isTargetDarwin()) {
826     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
827     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
828     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
829   }
830
831   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
832   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
833   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
834   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
835   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
836   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
837   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
838   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
839   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
840
841   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
842   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
843   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
844   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
845   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
846
847   // We don't support sin/cos/fmod/copysign/pow
848   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
849   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
850   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
851   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
852   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
853   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
854   setOperationAction(ISD::FREM,      MVT::f64, Expand);
855   setOperationAction(ISD::FREM,      MVT::f32, Expand);
856   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
857       !Subtarget->isThumb1Only()) {
858     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
859     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
860   }
861   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
862   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
863
864   if (!Subtarget->hasVFP4()) {
865     setOperationAction(ISD::FMA, MVT::f64, Expand);
866     setOperationAction(ISD::FMA, MVT::f32, Expand);
867   }
868
869   // Various VFP goodness
870   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
871     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
872     if (Subtarget->hasVFP2()) {
873       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
874       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
875       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
876       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
877     }
878
879     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
880     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
881       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
882       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
883     }
884
885     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
886     if (!Subtarget->hasFP16()) {
887       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
888       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
889     }
890   }
891
892   // Combine sin / cos into one node or libcall if possible.
893   if (Subtarget->hasSinCos()) {
894     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
895     setLibcallName(RTLIB::SINCOS_F64, "sincos");
896     if (Subtarget->getTargetTriple().isiOS()) {
897       // For iOS, we don't want to the normal expansion of a libcall to
898       // sincos. We want to issue a libcall to __sincos_stret.
899       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
900       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
901     }
902   }
903
904   // FP-ARMv8 implements a lot of rounding-like FP operations.
905   if (Subtarget->hasFPARMv8()) {
906     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
907     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
908     setOperationAction(ISD::FROUND, MVT::f32, Legal);
909     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
910     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
911     setOperationAction(ISD::FRINT, MVT::f32, Legal);
912     if (!Subtarget->isFPOnlySP()) {
913       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
914       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
915       setOperationAction(ISD::FROUND, MVT::f64, Legal);
916       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
917       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
918       setOperationAction(ISD::FRINT, MVT::f64, Legal);
919     }
920   }
921   // We have target-specific dag combine patterns for the following nodes:
922   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
923   setTargetDAGCombine(ISD::ADD);
924   setTargetDAGCombine(ISD::SUB);
925   setTargetDAGCombine(ISD::MUL);
926   setTargetDAGCombine(ISD::AND);
927   setTargetDAGCombine(ISD::OR);
928   setTargetDAGCombine(ISD::XOR);
929
930   if (Subtarget->hasV6Ops())
931     setTargetDAGCombine(ISD::SRL);
932
933   setStackPointerRegisterToSaveRestore(ARM::SP);
934
935   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
936       !Subtarget->hasVFP2())
937     setSchedulingPreference(Sched::RegPressure);
938   else
939     setSchedulingPreference(Sched::Hybrid);
940
941   //// temporary - rewrite interface to use type
942   MaxStoresPerMemset = 8;
943   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
944   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
945   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
946   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
947   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
948
949   // On ARM arguments smaller than 4 bytes are extended, so all arguments
950   // are at least 4 bytes aligned.
951   setMinStackArgumentAlignment(4);
952
953   // Prefer likely predicted branches to selects on out-of-order cores.
954   PredictableSelectIsExpensive = Subtarget->isLikeA9();
955
956   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
957 }
958
959 // FIXME: It might make sense to define the representative register class as the
960 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
961 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
962 // SPR's representative would be DPR_VFP2. This should work well if register
963 // pressure tracking were modified such that a register use would increment the
964 // pressure of the register class's representative and all of it's super
965 // classes' representatives transitively. We have not implemented this because
966 // of the difficulty prior to coalescing of modeling operand register classes
967 // due to the common occurrence of cross class copies and subregister insertions
968 // and extractions.
969 std::pair<const TargetRegisterClass *, uint8_t>
970 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
971                                            MVT VT) const {
972   const TargetRegisterClass *RRC = nullptr;
973   uint8_t Cost = 1;
974   switch (VT.SimpleTy) {
975   default:
976     return TargetLowering::findRepresentativeClass(TRI, VT);
977   // Use DPR as representative register class for all floating point
978   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
979   // the cost is 1 for both f32 and f64.
980   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
981   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
982     RRC = &ARM::DPRRegClass;
983     // When NEON is used for SP, only half of the register file is available
984     // because operations that define both SP and DP results will be constrained
985     // to the VFP2 class (D0-D15). We currently model this constraint prior to
986     // coalescing by double-counting the SP regs. See the FIXME above.
987     if (Subtarget->useNEONForSinglePrecisionFP())
988       Cost = 2;
989     break;
990   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
991   case MVT::v4f32: case MVT::v2f64:
992     RRC = &ARM::DPRRegClass;
993     Cost = 2;
994     break;
995   case MVT::v4i64:
996     RRC = &ARM::DPRRegClass;
997     Cost = 4;
998     break;
999   case MVT::v8i64:
1000     RRC = &ARM::DPRRegClass;
1001     Cost = 8;
1002     break;
1003   }
1004   return std::make_pair(RRC, Cost);
1005 }
1006
1007 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1008   switch (Opcode) {
1009   default: return nullptr;
1010   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1011   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1012   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1013   case ARMISD::CALL:          return "ARMISD::CALL";
1014   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1015   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1016   case ARMISD::tCALL:         return "ARMISD::tCALL";
1017   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1018   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1019   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1020   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1021   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1022   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1023   case ARMISD::CMP:           return "ARMISD::CMP";
1024   case ARMISD::CMN:           return "ARMISD::CMN";
1025   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1026   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1027   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1028   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1029   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1030
1031   case ARMISD::CMOV:          return "ARMISD::CMOV";
1032
1033   case ARMISD::RBIT:          return "ARMISD::RBIT";
1034
1035   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1036   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1037   case ARMISD::SITOF:         return "ARMISD::SITOF";
1038   case ARMISD::UITOF:         return "ARMISD::UITOF";
1039
1040   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1041   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1042   case ARMISD::RRX:           return "ARMISD::RRX";
1043
1044   case ARMISD::ADDC:          return "ARMISD::ADDC";
1045   case ARMISD::ADDE:          return "ARMISD::ADDE";
1046   case ARMISD::SUBC:          return "ARMISD::SUBC";
1047   case ARMISD::SUBE:          return "ARMISD::SUBE";
1048
1049   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1050   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1051
1052   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1053   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1054
1055   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1056
1057   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1058
1059   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1060
1061   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1062
1063   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1064
1065   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1066
1067   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1068   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1069   case ARMISD::VCGE:          return "ARMISD::VCGE";
1070   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1071   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1072   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1073   case ARMISD::VCGT:          return "ARMISD::VCGT";
1074   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1075   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1076   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1077   case ARMISD::VTST:          return "ARMISD::VTST";
1078
1079   case ARMISD::VSHL:          return "ARMISD::VSHL";
1080   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1081   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1082   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1083   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1084   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1085   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1086   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1087   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1088   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1089   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1090   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1091   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1092   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1093   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1094   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1095   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1096   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1097   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1098   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1099   case ARMISD::VDUP:          return "ARMISD::VDUP";
1100   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1101   case ARMISD::VEXT:          return "ARMISD::VEXT";
1102   case ARMISD::VREV64:        return "ARMISD::VREV64";
1103   case ARMISD::VREV32:        return "ARMISD::VREV32";
1104   case ARMISD::VREV16:        return "ARMISD::VREV16";
1105   case ARMISD::VZIP:          return "ARMISD::VZIP";
1106   case ARMISD::VUZP:          return "ARMISD::VUZP";
1107   case ARMISD::VTRN:          return "ARMISD::VTRN";
1108   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1109   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1110   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1111   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1112   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1113   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1114   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1115   case ARMISD::FMAX:          return "ARMISD::FMAX";
1116   case ARMISD::FMIN:          return "ARMISD::FMIN";
1117   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1118   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1119   case ARMISD::BFI:           return "ARMISD::BFI";
1120   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1121   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1122   case ARMISD::VBSL:          return "ARMISD::VBSL";
1123   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1124   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1125   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1126   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1127   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1128   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1129   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1130   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1131   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1132   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1133   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1134   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1135   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1136   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1137   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1138   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1139   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1140   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1141   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1142   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1143   }
1144 }
1145
1146 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1147   if (!VT.isVector()) return getPointerTy();
1148   return VT.changeVectorElementTypeToInteger();
1149 }
1150
1151 /// getRegClassFor - Return the register class that should be used for the
1152 /// specified value type.
1153 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1154   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1155   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1156   // load / store 4 to 8 consecutive D registers.
1157   if (Subtarget->hasNEON()) {
1158     if (VT == MVT::v4i64)
1159       return &ARM::QQPRRegClass;
1160     if (VT == MVT::v8i64)
1161       return &ARM::QQQQPRRegClass;
1162   }
1163   return TargetLowering::getRegClassFor(VT);
1164 }
1165
1166 // Create a fast isel object.
1167 FastISel *
1168 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1169                                   const TargetLibraryInfo *libInfo) const {
1170   return ARM::createFastISel(funcInfo, libInfo);
1171 }
1172
1173 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1174   unsigned NumVals = N->getNumValues();
1175   if (!NumVals)
1176     return Sched::RegPressure;
1177
1178   for (unsigned i = 0; i != NumVals; ++i) {
1179     EVT VT = N->getValueType(i);
1180     if (VT == MVT::Glue || VT == MVT::Other)
1181       continue;
1182     if (VT.isFloatingPoint() || VT.isVector())
1183       return Sched::ILP;
1184   }
1185
1186   if (!N->isMachineOpcode())
1187     return Sched::RegPressure;
1188
1189   // Load are scheduled for latency even if there instruction itinerary
1190   // is not available.
1191   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1192   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1193
1194   if (MCID.getNumDefs() == 0)
1195     return Sched::RegPressure;
1196   if (!Itins->isEmpty() &&
1197       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1198     return Sched::ILP;
1199
1200   return Sched::RegPressure;
1201 }
1202
1203 //===----------------------------------------------------------------------===//
1204 // Lowering Code
1205 //===----------------------------------------------------------------------===//
1206
1207 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1208 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1209   switch (CC) {
1210   default: llvm_unreachable("Unknown condition code!");
1211   case ISD::SETNE:  return ARMCC::NE;
1212   case ISD::SETEQ:  return ARMCC::EQ;
1213   case ISD::SETGT:  return ARMCC::GT;
1214   case ISD::SETGE:  return ARMCC::GE;
1215   case ISD::SETLT:  return ARMCC::LT;
1216   case ISD::SETLE:  return ARMCC::LE;
1217   case ISD::SETUGT: return ARMCC::HI;
1218   case ISD::SETUGE: return ARMCC::HS;
1219   case ISD::SETULT: return ARMCC::LO;
1220   case ISD::SETULE: return ARMCC::LS;
1221   }
1222 }
1223
1224 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1225 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1226                         ARMCC::CondCodes &CondCode2) {
1227   CondCode2 = ARMCC::AL;
1228   switch (CC) {
1229   default: llvm_unreachable("Unknown FP condition!");
1230   case ISD::SETEQ:
1231   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1232   case ISD::SETGT:
1233   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1234   case ISD::SETGE:
1235   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1236   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1237   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1238   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1239   case ISD::SETO:   CondCode = ARMCC::VC; break;
1240   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1241   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1242   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1243   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1244   case ISD::SETLT:
1245   case ISD::SETULT: CondCode = ARMCC::LT; break;
1246   case ISD::SETLE:
1247   case ISD::SETULE: CondCode = ARMCC::LE; break;
1248   case ISD::SETNE:
1249   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1250   }
1251 }
1252
1253 //===----------------------------------------------------------------------===//
1254 //                      Calling Convention Implementation
1255 //===----------------------------------------------------------------------===//
1256
1257 #include "ARMGenCallingConv.inc"
1258
1259 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1260 /// account presence of floating point hardware and calling convention
1261 /// limitations, such as support for variadic functions.
1262 CallingConv::ID
1263 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1264                                            bool isVarArg) const {
1265   switch (CC) {
1266   default:
1267     llvm_unreachable("Unsupported calling convention");
1268   case CallingConv::ARM_AAPCS:
1269   case CallingConv::ARM_APCS:
1270   case CallingConv::GHC:
1271     return CC;
1272   case CallingConv::ARM_AAPCS_VFP:
1273     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1274   case CallingConv::C:
1275     if (!Subtarget->isAAPCS_ABI())
1276       return CallingConv::ARM_APCS;
1277     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1278              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1279              !isVarArg)
1280       return CallingConv::ARM_AAPCS_VFP;
1281     else
1282       return CallingConv::ARM_AAPCS;
1283   case CallingConv::Fast:
1284     if (!Subtarget->isAAPCS_ABI()) {
1285       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1286         return CallingConv::Fast;
1287       return CallingConv::ARM_APCS;
1288     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1289       return CallingConv::ARM_AAPCS_VFP;
1290     else
1291       return CallingConv::ARM_AAPCS;
1292   }
1293 }
1294
1295 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1296 /// CallingConvention.
1297 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1298                                                  bool Return,
1299                                                  bool isVarArg) const {
1300   switch (getEffectiveCallingConv(CC, isVarArg)) {
1301   default:
1302     llvm_unreachable("Unsupported calling convention");
1303   case CallingConv::ARM_APCS:
1304     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1305   case CallingConv::ARM_AAPCS:
1306     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1307   case CallingConv::ARM_AAPCS_VFP:
1308     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1309   case CallingConv::Fast:
1310     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1311   case CallingConv::GHC:
1312     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1313   }
1314 }
1315
1316 /// LowerCallResult - Lower the result values of a call into the
1317 /// appropriate copies out of appropriate physical registers.
1318 SDValue
1319 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1320                                    CallingConv::ID CallConv, bool isVarArg,
1321                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1322                                    SDLoc dl, SelectionDAG &DAG,
1323                                    SmallVectorImpl<SDValue> &InVals,
1324                                    bool isThisReturn, SDValue ThisVal) const {
1325
1326   // Assign locations to each value returned by this call.
1327   SmallVector<CCValAssign, 16> RVLocs;
1328   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1329                     *DAG.getContext(), Call);
1330   CCInfo.AnalyzeCallResult(Ins,
1331                            CCAssignFnForNode(CallConv, /* Return*/ true,
1332                                              isVarArg));
1333
1334   // Copy all of the result registers out of their specified physreg.
1335   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1336     CCValAssign VA = RVLocs[i];
1337
1338     // Pass 'this' value directly from the argument to return value, to avoid
1339     // reg unit interference
1340     if (i == 0 && isThisReturn) {
1341       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1342              "unexpected return calling convention register assignment");
1343       InVals.push_back(ThisVal);
1344       continue;
1345     }
1346
1347     SDValue Val;
1348     if (VA.needsCustom()) {
1349       // Handle f64 or half of a v2f64.
1350       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1351                                       InFlag);
1352       Chain = Lo.getValue(1);
1353       InFlag = Lo.getValue(2);
1354       VA = RVLocs[++i]; // skip ahead to next loc
1355       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1356                                       InFlag);
1357       Chain = Hi.getValue(1);
1358       InFlag = Hi.getValue(2);
1359       if (!Subtarget->isLittle())
1360         std::swap (Lo, Hi);
1361       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1362
1363       if (VA.getLocVT() == MVT::v2f64) {
1364         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1365         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1366                           DAG.getConstant(0, MVT::i32));
1367
1368         VA = RVLocs[++i]; // skip ahead to next loc
1369         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1370         Chain = Lo.getValue(1);
1371         InFlag = Lo.getValue(2);
1372         VA = RVLocs[++i]; // skip ahead to next loc
1373         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1374         Chain = Hi.getValue(1);
1375         InFlag = Hi.getValue(2);
1376         if (!Subtarget->isLittle())
1377           std::swap (Lo, Hi);
1378         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1379         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1380                           DAG.getConstant(1, MVT::i32));
1381       }
1382     } else {
1383       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1384                                InFlag);
1385       Chain = Val.getValue(1);
1386       InFlag = Val.getValue(2);
1387     }
1388
1389     switch (VA.getLocInfo()) {
1390     default: llvm_unreachable("Unknown loc info!");
1391     case CCValAssign::Full: break;
1392     case CCValAssign::BCvt:
1393       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1394       break;
1395     }
1396
1397     InVals.push_back(Val);
1398   }
1399
1400   return Chain;
1401 }
1402
1403 /// LowerMemOpCallTo - Store the argument to the stack.
1404 SDValue
1405 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1406                                     SDValue StackPtr, SDValue Arg,
1407                                     SDLoc dl, SelectionDAG &DAG,
1408                                     const CCValAssign &VA,
1409                                     ISD::ArgFlagsTy Flags) const {
1410   unsigned LocMemOffset = VA.getLocMemOffset();
1411   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1412   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1413   return DAG.getStore(Chain, dl, Arg, PtrOff,
1414                       MachinePointerInfo::getStack(LocMemOffset),
1415                       false, false, 0);
1416 }
1417
1418 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1419                                          SDValue Chain, SDValue &Arg,
1420                                          RegsToPassVector &RegsToPass,
1421                                          CCValAssign &VA, CCValAssign &NextVA,
1422                                          SDValue &StackPtr,
1423                                          SmallVectorImpl<SDValue> &MemOpChains,
1424                                          ISD::ArgFlagsTy Flags) const {
1425
1426   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1427                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1428   unsigned id = Subtarget->isLittle() ? 0 : 1;
1429   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1430
1431   if (NextVA.isRegLoc())
1432     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1433   else {
1434     assert(NextVA.isMemLoc());
1435     if (!StackPtr.getNode())
1436       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1437
1438     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1439                                            dl, DAG, NextVA,
1440                                            Flags));
1441   }
1442 }
1443
1444 /// LowerCall - Lowering a call into a callseq_start <-
1445 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1446 /// nodes.
1447 SDValue
1448 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1449                              SmallVectorImpl<SDValue> &InVals) const {
1450   SelectionDAG &DAG                     = CLI.DAG;
1451   SDLoc &dl                          = CLI.DL;
1452   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1453   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1454   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1455   SDValue Chain                         = CLI.Chain;
1456   SDValue Callee                        = CLI.Callee;
1457   bool &isTailCall                      = CLI.IsTailCall;
1458   CallingConv::ID CallConv              = CLI.CallConv;
1459   bool doesNotRet                       = CLI.DoesNotReturn;
1460   bool isVarArg                         = CLI.IsVarArg;
1461
1462   MachineFunction &MF = DAG.getMachineFunction();
1463   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1464   bool isThisReturn   = false;
1465   bool isSibCall      = false;
1466
1467   // Disable tail calls if they're not supported.
1468   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1469     isTailCall = false;
1470
1471   if (isTailCall) {
1472     // Check if it's really possible to do a tail call.
1473     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1474                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1475                                                    Outs, OutVals, Ins, DAG);
1476     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1477       report_fatal_error("failed to perform tail call elimination on a call "
1478                          "site marked musttail");
1479     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1480     // detected sibcalls.
1481     if (isTailCall) {
1482       ++NumTailCalls;
1483       isSibCall = true;
1484     }
1485   }
1486
1487   // Analyze operands of the call, assigning locations to each operand.
1488   SmallVector<CCValAssign, 16> ArgLocs;
1489   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1490                     *DAG.getContext(), Call);
1491   CCInfo.AnalyzeCallOperands(Outs,
1492                              CCAssignFnForNode(CallConv, /* Return*/ false,
1493                                                isVarArg));
1494
1495   // Get a count of how many bytes are to be pushed on the stack.
1496   unsigned NumBytes = CCInfo.getNextStackOffset();
1497
1498   // For tail calls, memory operands are available in our caller's stack.
1499   if (isSibCall)
1500     NumBytes = 0;
1501
1502   // Adjust the stack pointer for the new arguments...
1503   // These operations are automatically eliminated by the prolog/epilog pass
1504   if (!isSibCall)
1505     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1506                                  dl);
1507
1508   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1509
1510   RegsToPassVector RegsToPass;
1511   SmallVector<SDValue, 8> MemOpChains;
1512
1513   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1514   // of tail call optimization, arguments are handled later.
1515   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1516        i != e;
1517        ++i, ++realArgIdx) {
1518     CCValAssign &VA = ArgLocs[i];
1519     SDValue Arg = OutVals[realArgIdx];
1520     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1521     bool isByVal = Flags.isByVal();
1522
1523     // Promote the value if needed.
1524     switch (VA.getLocInfo()) {
1525     default: llvm_unreachable("Unknown loc info!");
1526     case CCValAssign::Full: break;
1527     case CCValAssign::SExt:
1528       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1529       break;
1530     case CCValAssign::ZExt:
1531       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1532       break;
1533     case CCValAssign::AExt:
1534       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1535       break;
1536     case CCValAssign::BCvt:
1537       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1538       break;
1539     }
1540
1541     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1542     if (VA.needsCustom()) {
1543       if (VA.getLocVT() == MVT::v2f64) {
1544         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1545                                   DAG.getConstant(0, MVT::i32));
1546         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1547                                   DAG.getConstant(1, MVT::i32));
1548
1549         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1550                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1551
1552         VA = ArgLocs[++i]; // skip ahead to next loc
1553         if (VA.isRegLoc()) {
1554           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1555                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1556         } else {
1557           assert(VA.isMemLoc());
1558
1559           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1560                                                  dl, DAG, VA, Flags));
1561         }
1562       } else {
1563         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1564                          StackPtr, MemOpChains, Flags);
1565       }
1566     } else if (VA.isRegLoc()) {
1567       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1568         assert(VA.getLocVT() == MVT::i32 &&
1569                "unexpected calling convention register assignment");
1570         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1571                "unexpected use of 'returned'");
1572         isThisReturn = true;
1573       }
1574       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1575     } else if (isByVal) {
1576       assert(VA.isMemLoc());
1577       unsigned offset = 0;
1578
1579       // True if this byval aggregate will be split between registers
1580       // and memory.
1581       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1582       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1583
1584       if (CurByValIdx < ByValArgsCount) {
1585
1586         unsigned RegBegin, RegEnd;
1587         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1588
1589         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1590         unsigned int i, j;
1591         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1592           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1593           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1594           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1595                                      MachinePointerInfo(),
1596                                      false, false, false,
1597                                      DAG.InferPtrAlignment(AddArg));
1598           MemOpChains.push_back(Load.getValue(1));
1599           RegsToPass.push_back(std::make_pair(j, Load));
1600         }
1601
1602         // If parameter size outsides register area, "offset" value
1603         // helps us to calculate stack slot for remained part properly.
1604         offset = RegEnd - RegBegin;
1605
1606         CCInfo.nextInRegsParam();
1607       }
1608
1609       if (Flags.getByValSize() > 4*offset) {
1610         unsigned LocMemOffset = VA.getLocMemOffset();
1611         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1612         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1613                                   StkPtrOff);
1614         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1615         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1616         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1617                                            MVT::i32);
1618         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1619
1620         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1621         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1622         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1623                                           Ops));
1624       }
1625     } else if (!isSibCall) {
1626       assert(VA.isMemLoc());
1627
1628       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1629                                              dl, DAG, VA, Flags));
1630     }
1631   }
1632
1633   if (!MemOpChains.empty())
1634     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1635
1636   // Build a sequence of copy-to-reg nodes chained together with token chain
1637   // and flag operands which copy the outgoing args into the appropriate regs.
1638   SDValue InFlag;
1639   // Tail call byval lowering might overwrite argument registers so in case of
1640   // tail call optimization the copies to registers are lowered later.
1641   if (!isTailCall)
1642     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1643       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1644                                RegsToPass[i].second, InFlag);
1645       InFlag = Chain.getValue(1);
1646     }
1647
1648   // For tail calls lower the arguments to the 'real' stack slot.
1649   if (isTailCall) {
1650     // Force all the incoming stack arguments to be loaded from the stack
1651     // before any new outgoing arguments are stored to the stack, because the
1652     // outgoing stack slots may alias the incoming argument stack slots, and
1653     // the alias isn't otherwise explicit. This is slightly more conservative
1654     // than necessary, because it means that each store effectively depends
1655     // on every argument instead of just those arguments it would clobber.
1656
1657     // Do not flag preceding copytoreg stuff together with the following stuff.
1658     InFlag = SDValue();
1659     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1660       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1661                                RegsToPass[i].second, InFlag);
1662       InFlag = Chain.getValue(1);
1663     }
1664     InFlag = SDValue();
1665   }
1666
1667   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1668   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1669   // node so that legalize doesn't hack it.
1670   bool isDirect = false;
1671   bool isARMFunc = false;
1672   bool isLocalARMFunc = false;
1673   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1674
1675   if (EnableARMLongCalls) {
1676     assert((Subtarget->isTargetWindows() ||
1677             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1678            "long-calls with non-static relocation model!");
1679     // Handle a global address or an external symbol. If it's not one of
1680     // those, the target's already in a register, so we don't need to do
1681     // anything extra.
1682     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1683       const GlobalValue *GV = G->getGlobal();
1684       // Create a constant pool entry for the callee address
1685       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1686       ARMConstantPoolValue *CPV =
1687         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1688
1689       // Get the address of the callee into a register
1690       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1691       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1692       Callee = DAG.getLoad(getPointerTy(), dl,
1693                            DAG.getEntryNode(), CPAddr,
1694                            MachinePointerInfo::getConstantPool(),
1695                            false, false, false, 0);
1696     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1697       const char *Sym = S->getSymbol();
1698
1699       // Create a constant pool entry for the callee address
1700       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1701       ARMConstantPoolValue *CPV =
1702         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1703                                       ARMPCLabelIndex, 0);
1704       // Get the address of the callee into a register
1705       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1706       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1707       Callee = DAG.getLoad(getPointerTy(), dl,
1708                            DAG.getEntryNode(), CPAddr,
1709                            MachinePointerInfo::getConstantPool(),
1710                            false, false, false, 0);
1711     }
1712   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1713     const GlobalValue *GV = G->getGlobal();
1714     isDirect = true;
1715     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1716     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1717                    getTargetMachine().getRelocationModel() != Reloc::Static;
1718     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1719     // ARM call to a local ARM function is predicable.
1720     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1721     // tBX takes a register source operand.
1722     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1723       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1724       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1725                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1726                                                       0, ARMII::MO_NONLAZY));
1727       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1728                            MachinePointerInfo::getGOT(), false, false, true, 0);
1729     } else if (Subtarget->isTargetCOFF()) {
1730       assert(Subtarget->isTargetWindows() &&
1731              "Windows is the only supported COFF target");
1732       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1733                                  ? ARMII::MO_DLLIMPORT
1734                                  : ARMII::MO_NO_FLAG;
1735       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1736                                           TargetFlags);
1737       if (GV->hasDLLImportStorageClass())
1738         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1739                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1740                                          Callee), MachinePointerInfo::getGOT(),
1741                              false, false, false, 0);
1742     } else {
1743       // On ELF targets for PIC code, direct calls should go through the PLT
1744       unsigned OpFlags = 0;
1745       if (Subtarget->isTargetELF() &&
1746           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1747         OpFlags = ARMII::MO_PLT;
1748       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1749     }
1750   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1751     isDirect = true;
1752     bool isStub = Subtarget->isTargetMachO() &&
1753                   getTargetMachine().getRelocationModel() != Reloc::Static;
1754     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1755     // tBX takes a register source operand.
1756     const char *Sym = S->getSymbol();
1757     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1758       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1759       ARMConstantPoolValue *CPV =
1760         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1761                                       ARMPCLabelIndex, 4);
1762       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1763       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1764       Callee = DAG.getLoad(getPointerTy(), dl,
1765                            DAG.getEntryNode(), CPAddr,
1766                            MachinePointerInfo::getConstantPool(),
1767                            false, false, false, 0);
1768       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1769       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1770                            getPointerTy(), Callee, PICLabel);
1771     } else {
1772       unsigned OpFlags = 0;
1773       // On ELF targets for PIC code, direct calls should go through the PLT
1774       if (Subtarget->isTargetELF() &&
1775                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1776         OpFlags = ARMII::MO_PLT;
1777       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1778     }
1779   }
1780
1781   // FIXME: handle tail calls differently.
1782   unsigned CallOpc;
1783   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1784   if (Subtarget->isThumb()) {
1785     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1786       CallOpc = ARMISD::CALL_NOLINK;
1787     else
1788       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1789   } else {
1790     if (!isDirect && !Subtarget->hasV5TOps())
1791       CallOpc = ARMISD::CALL_NOLINK;
1792     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1793                // Emit regular call when code size is the priority
1794                !HasMinSizeAttr)
1795       // "mov lr, pc; b _foo" to avoid confusing the RSP
1796       CallOpc = ARMISD::CALL_NOLINK;
1797     else
1798       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1799   }
1800
1801   std::vector<SDValue> Ops;
1802   Ops.push_back(Chain);
1803   Ops.push_back(Callee);
1804
1805   // Add argument registers to the end of the list so that they are known live
1806   // into the call.
1807   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1808     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1809                                   RegsToPass[i].second.getValueType()));
1810
1811   // Add a register mask operand representing the call-preserved registers.
1812   if (!isTailCall) {
1813     const uint32_t *Mask;
1814     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1815     if (isThisReturn) {
1816       // For 'this' returns, use the R0-preserving mask if applicable
1817       Mask = ARI->getThisReturnPreservedMask(CallConv);
1818       if (!Mask) {
1819         // Set isThisReturn to false if the calling convention is not one that
1820         // allows 'returned' to be modeled in this way, so LowerCallResult does
1821         // not try to pass 'this' straight through
1822         isThisReturn = false;
1823         Mask = ARI->getCallPreservedMask(CallConv);
1824       }
1825     } else
1826       Mask = ARI->getCallPreservedMask(CallConv);
1827
1828     assert(Mask && "Missing call preserved mask for calling convention");
1829     Ops.push_back(DAG.getRegisterMask(Mask));
1830   }
1831
1832   if (InFlag.getNode())
1833     Ops.push_back(InFlag);
1834
1835   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1836   if (isTailCall)
1837     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1838
1839   // Returns a chain and a flag for retval copy to use.
1840   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1841   InFlag = Chain.getValue(1);
1842
1843   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1844                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1845   if (!Ins.empty())
1846     InFlag = Chain.getValue(1);
1847
1848   // Handle result values, copying them out of physregs into vregs that we
1849   // return.
1850   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1851                          InVals, isThisReturn,
1852                          isThisReturn ? OutVals[0] : SDValue());
1853 }
1854
1855 /// HandleByVal - Every parameter *after* a byval parameter is passed
1856 /// on the stack.  Remember the next parameter register to allocate,
1857 /// and then confiscate the rest of the parameter registers to insure
1858 /// this.
1859 void
1860 ARMTargetLowering::HandleByVal(
1861     CCState *State, unsigned &size, unsigned Align) const {
1862   unsigned reg = State->AllocateReg(GPRArgRegs);
1863   assert((State->getCallOrPrologue() == Prologue ||
1864           State->getCallOrPrologue() == Call) &&
1865          "unhandled ParmContext");
1866
1867   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1868     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1869       unsigned AlignInRegs = Align / 4;
1870       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1871       for (unsigned i = 0; i < Waste; ++i)
1872         reg = State->AllocateReg(GPRArgRegs);
1873     }
1874     if (reg != 0) {
1875       unsigned excess = 4 * (ARM::R4 - reg);
1876
1877       // Special case when NSAA != SP and parameter size greater than size of
1878       // all remained GPR regs. In that case we can't split parameter, we must
1879       // send it to stack. We also must set NCRN to R4, so waste all
1880       // remained registers.
1881       const unsigned NSAAOffset = State->getNextStackOffset();
1882       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1883         while (State->AllocateReg(GPRArgRegs))
1884           ;
1885         return;
1886       }
1887
1888       // First register for byval parameter is the first register that wasn't
1889       // allocated before this method call, so it would be "reg".
1890       // If parameter is small enough to be saved in range [reg, r4), then
1891       // the end (first after last) register would be reg + param-size-in-regs,
1892       // else parameter would be splitted between registers and stack,
1893       // end register would be r4 in this case.
1894       unsigned ByValRegBegin = reg;
1895       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1896       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1897       // Note, first register is allocated in the beginning of function already,
1898       // allocate remained amount of registers we need.
1899       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1900         State->AllocateReg(GPRArgRegs);
1901       // A byval parameter that is split between registers and memory needs its
1902       // size truncated here.
1903       // In the case where the entire structure fits in registers, we set the
1904       // size in memory to zero.
1905       if (size < excess)
1906         size = 0;
1907       else
1908         size -= excess;
1909     }
1910   }
1911 }
1912
1913 /// MatchingStackOffset - Return true if the given stack call argument is
1914 /// already available in the same position (relatively) of the caller's
1915 /// incoming argument stack.
1916 static
1917 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1918                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1919                          const TargetInstrInfo *TII) {
1920   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1921   int FI = INT_MAX;
1922   if (Arg.getOpcode() == ISD::CopyFromReg) {
1923     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1924     if (!TargetRegisterInfo::isVirtualRegister(VR))
1925       return false;
1926     MachineInstr *Def = MRI->getVRegDef(VR);
1927     if (!Def)
1928       return false;
1929     if (!Flags.isByVal()) {
1930       if (!TII->isLoadFromStackSlot(Def, FI))
1931         return false;
1932     } else {
1933       return false;
1934     }
1935   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1936     if (Flags.isByVal())
1937       // ByVal argument is passed in as a pointer but it's now being
1938       // dereferenced. e.g.
1939       // define @foo(%struct.X* %A) {
1940       //   tail call @bar(%struct.X* byval %A)
1941       // }
1942       return false;
1943     SDValue Ptr = Ld->getBasePtr();
1944     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1945     if (!FINode)
1946       return false;
1947     FI = FINode->getIndex();
1948   } else
1949     return false;
1950
1951   assert(FI != INT_MAX);
1952   if (!MFI->isFixedObjectIndex(FI))
1953     return false;
1954   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1955 }
1956
1957 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1958 /// for tail call optimization. Targets which want to do tail call
1959 /// optimization should implement this function.
1960 bool
1961 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1962                                                      CallingConv::ID CalleeCC,
1963                                                      bool isVarArg,
1964                                                      bool isCalleeStructRet,
1965                                                      bool isCallerStructRet,
1966                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1967                                     const SmallVectorImpl<SDValue> &OutVals,
1968                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1969                                                      SelectionDAG& DAG) const {
1970   const Function *CallerF = DAG.getMachineFunction().getFunction();
1971   CallingConv::ID CallerCC = CallerF->getCallingConv();
1972   bool CCMatch = CallerCC == CalleeCC;
1973
1974   // Look for obvious safe cases to perform tail call optimization that do not
1975   // require ABI changes. This is what gcc calls sibcall.
1976
1977   // Do not sibcall optimize vararg calls unless the call site is not passing
1978   // any arguments.
1979   if (isVarArg && !Outs.empty())
1980     return false;
1981
1982   // Exception-handling functions need a special set of instructions to indicate
1983   // a return to the hardware. Tail-calling another function would probably
1984   // break this.
1985   if (CallerF->hasFnAttribute("interrupt"))
1986     return false;
1987
1988   // Also avoid sibcall optimization if either caller or callee uses struct
1989   // return semantics.
1990   if (isCalleeStructRet || isCallerStructRet)
1991     return false;
1992
1993   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1994   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1995   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1996   // support in the assembler and linker to be used. This would need to be
1997   // fixed to fully support tail calls in Thumb1.
1998   //
1999   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2000   // LR.  This means if we need to reload LR, it takes an extra instructions,
2001   // which outweighs the value of the tail call; but here we don't know yet
2002   // whether LR is going to be used.  Probably the right approach is to
2003   // generate the tail call here and turn it back into CALL/RET in
2004   // emitEpilogue if LR is used.
2005
2006   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2007   // but we need to make sure there are enough registers; the only valid
2008   // registers are the 4 used for parameters.  We don't currently do this
2009   // case.
2010   if (Subtarget->isThumb1Only())
2011     return false;
2012
2013   // Externally-defined functions with weak linkage should not be
2014   // tail-called on ARM when the OS does not support dynamic
2015   // pre-emption of symbols, as the AAELF spec requires normal calls
2016   // to undefined weak functions to be replaced with a NOP or jump to the
2017   // next instruction. The behaviour of branch instructions in this
2018   // situation (as used for tail calls) is implementation-defined, so we
2019   // cannot rely on the linker replacing the tail call with a return.
2020   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2021     const GlobalValue *GV = G->getGlobal();
2022     const Triple TT(getTargetMachine().getTargetTriple());
2023     if (GV->hasExternalWeakLinkage() &&
2024         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2025       return false;
2026   }
2027
2028   // If the calling conventions do not match, then we'd better make sure the
2029   // results are returned in the same way as what the caller expects.
2030   if (!CCMatch) {
2031     SmallVector<CCValAssign, 16> RVLocs1;
2032     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2033                        *DAG.getContext(), Call);
2034     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2035
2036     SmallVector<CCValAssign, 16> RVLocs2;
2037     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2038                        *DAG.getContext(), Call);
2039     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2040
2041     if (RVLocs1.size() != RVLocs2.size())
2042       return false;
2043     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2044       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2045         return false;
2046       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2047         return false;
2048       if (RVLocs1[i].isRegLoc()) {
2049         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2050           return false;
2051       } else {
2052         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2053           return false;
2054       }
2055     }
2056   }
2057
2058   // If Caller's vararg or byval argument has been split between registers and
2059   // stack, do not perform tail call, since part of the argument is in caller's
2060   // local frame.
2061   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2062                                       getInfo<ARMFunctionInfo>();
2063   if (AFI_Caller->getArgRegsSaveSize())
2064     return false;
2065
2066   // If the callee takes no arguments then go on to check the results of the
2067   // call.
2068   if (!Outs.empty()) {
2069     // Check if stack adjustment is needed. For now, do not do this if any
2070     // argument is passed on the stack.
2071     SmallVector<CCValAssign, 16> ArgLocs;
2072     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2073                       *DAG.getContext(), Call);
2074     CCInfo.AnalyzeCallOperands(Outs,
2075                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2076     if (CCInfo.getNextStackOffset()) {
2077       MachineFunction &MF = DAG.getMachineFunction();
2078
2079       // Check if the arguments are already laid out in the right way as
2080       // the caller's fixed stack objects.
2081       MachineFrameInfo *MFI = MF.getFrameInfo();
2082       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2083       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2084       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2085            i != e;
2086            ++i, ++realArgIdx) {
2087         CCValAssign &VA = ArgLocs[i];
2088         EVT RegVT = VA.getLocVT();
2089         SDValue Arg = OutVals[realArgIdx];
2090         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2091         if (VA.getLocInfo() == CCValAssign::Indirect)
2092           return false;
2093         if (VA.needsCustom()) {
2094           // f64 and vector types are split into multiple registers or
2095           // register/stack-slot combinations.  The types will not match
2096           // the registers; give up on memory f64 refs until we figure
2097           // out what to do about this.
2098           if (!VA.isRegLoc())
2099             return false;
2100           if (!ArgLocs[++i].isRegLoc())
2101             return false;
2102           if (RegVT == MVT::v2f64) {
2103             if (!ArgLocs[++i].isRegLoc())
2104               return false;
2105             if (!ArgLocs[++i].isRegLoc())
2106               return false;
2107           }
2108         } else if (!VA.isRegLoc()) {
2109           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2110                                    MFI, MRI, TII))
2111             return false;
2112         }
2113       }
2114     }
2115   }
2116
2117   return true;
2118 }
2119
2120 bool
2121 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2122                                   MachineFunction &MF, bool isVarArg,
2123                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2124                                   LLVMContext &Context) const {
2125   SmallVector<CCValAssign, 16> RVLocs;
2126   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2127   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2128                                                     isVarArg));
2129 }
2130
2131 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2132                                     SDLoc DL, SelectionDAG &DAG) {
2133   const MachineFunction &MF = DAG.getMachineFunction();
2134   const Function *F = MF.getFunction();
2135
2136   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2137
2138   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2139   // version of the "preferred return address". These offsets affect the return
2140   // instruction if this is a return from PL1 without hypervisor extensions.
2141   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2142   //    SWI:     0      "subs pc, lr, #0"
2143   //    ABORT:   +4     "subs pc, lr, #4"
2144   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2145   // UNDEF varies depending on where the exception came from ARM or Thumb
2146   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2147
2148   int64_t LROffset;
2149   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2150       IntKind == "ABORT")
2151     LROffset = 4;
2152   else if (IntKind == "SWI" || IntKind == "UNDEF")
2153     LROffset = 0;
2154   else
2155     report_fatal_error("Unsupported interrupt attribute. If present, value "
2156                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2157
2158   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2159
2160   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2161 }
2162
2163 SDValue
2164 ARMTargetLowering::LowerReturn(SDValue Chain,
2165                                CallingConv::ID CallConv, bool isVarArg,
2166                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2167                                const SmallVectorImpl<SDValue> &OutVals,
2168                                SDLoc dl, SelectionDAG &DAG) const {
2169
2170   // CCValAssign - represent the assignment of the return value to a location.
2171   SmallVector<CCValAssign, 16> RVLocs;
2172
2173   // CCState - Info about the registers and stack slots.
2174   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2175                     *DAG.getContext(), Call);
2176
2177   // Analyze outgoing return values.
2178   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2179                                                isVarArg));
2180
2181   SDValue Flag;
2182   SmallVector<SDValue, 4> RetOps;
2183   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2184   bool isLittleEndian = Subtarget->isLittle();
2185
2186   MachineFunction &MF = DAG.getMachineFunction();
2187   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2188   AFI->setReturnRegsCount(RVLocs.size());
2189
2190   // Copy the result values into the output registers.
2191   for (unsigned i = 0, realRVLocIdx = 0;
2192        i != RVLocs.size();
2193        ++i, ++realRVLocIdx) {
2194     CCValAssign &VA = RVLocs[i];
2195     assert(VA.isRegLoc() && "Can only return in registers!");
2196
2197     SDValue Arg = OutVals[realRVLocIdx];
2198
2199     switch (VA.getLocInfo()) {
2200     default: llvm_unreachable("Unknown loc info!");
2201     case CCValAssign::Full: break;
2202     case CCValAssign::BCvt:
2203       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2204       break;
2205     }
2206
2207     if (VA.needsCustom()) {
2208       if (VA.getLocVT() == MVT::v2f64) {
2209         // Extract the first half and return it in two registers.
2210         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2211                                    DAG.getConstant(0, MVT::i32));
2212         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2213                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2214
2215         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2216                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2217                                  Flag);
2218         Flag = Chain.getValue(1);
2219         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2220         VA = RVLocs[++i]; // skip ahead to next loc
2221         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2222                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2223                                  Flag);
2224         Flag = Chain.getValue(1);
2225         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2226         VA = RVLocs[++i]; // skip ahead to next loc
2227
2228         // Extract the 2nd half and fall through to handle it as an f64 value.
2229         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2230                           DAG.getConstant(1, MVT::i32));
2231       }
2232       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2233       // available.
2234       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2235                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2236       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2237                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2238                                Flag);
2239       Flag = Chain.getValue(1);
2240       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2241       VA = RVLocs[++i]; // skip ahead to next loc
2242       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2243                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2244                                Flag);
2245     } else
2246       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2247
2248     // Guarantee that all emitted copies are
2249     // stuck together, avoiding something bad.
2250     Flag = Chain.getValue(1);
2251     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2252   }
2253
2254   // Update chain and glue.
2255   RetOps[0] = Chain;
2256   if (Flag.getNode())
2257     RetOps.push_back(Flag);
2258
2259   // CPUs which aren't M-class use a special sequence to return from
2260   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2261   // though we use "subs pc, lr, #N").
2262   //
2263   // M-class CPUs actually use a normal return sequence with a special
2264   // (hardware-provided) value in LR, so the normal code path works.
2265   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2266       !Subtarget->isMClass()) {
2267     if (Subtarget->isThumb1Only())
2268       report_fatal_error("interrupt attribute is not supported in Thumb1");
2269     return LowerInterruptReturn(RetOps, dl, DAG);
2270   }
2271
2272   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2273 }
2274
2275 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2276   if (N->getNumValues() != 1)
2277     return false;
2278   if (!N->hasNUsesOfValue(1, 0))
2279     return false;
2280
2281   SDValue TCChain = Chain;
2282   SDNode *Copy = *N->use_begin();
2283   if (Copy->getOpcode() == ISD::CopyToReg) {
2284     // If the copy has a glue operand, we conservatively assume it isn't safe to
2285     // perform a tail call.
2286     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2287       return false;
2288     TCChain = Copy->getOperand(0);
2289   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2290     SDNode *VMov = Copy;
2291     // f64 returned in a pair of GPRs.
2292     SmallPtrSet<SDNode*, 2> Copies;
2293     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2294          UI != UE; ++UI) {
2295       if (UI->getOpcode() != ISD::CopyToReg)
2296         return false;
2297       Copies.insert(*UI);
2298     }
2299     if (Copies.size() > 2)
2300       return false;
2301
2302     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2303          UI != UE; ++UI) {
2304       SDValue UseChain = UI->getOperand(0);
2305       if (Copies.count(UseChain.getNode()))
2306         // Second CopyToReg
2307         Copy = *UI;
2308       else {
2309         // We are at the top of this chain.
2310         // If the copy has a glue operand, we conservatively assume it
2311         // isn't safe to perform a tail call.
2312         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2313           return false;
2314         // First CopyToReg
2315         TCChain = UseChain;
2316       }
2317     }
2318   } else if (Copy->getOpcode() == ISD::BITCAST) {
2319     // f32 returned in a single GPR.
2320     if (!Copy->hasOneUse())
2321       return false;
2322     Copy = *Copy->use_begin();
2323     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2324       return false;
2325     // If the copy has a glue operand, we conservatively assume it isn't safe to
2326     // perform a tail call.
2327     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2328       return false;
2329     TCChain = Copy->getOperand(0);
2330   } else {
2331     return false;
2332   }
2333
2334   bool HasRet = false;
2335   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2336        UI != UE; ++UI) {
2337     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2338         UI->getOpcode() != ARMISD::INTRET_FLAG)
2339       return false;
2340     HasRet = true;
2341   }
2342
2343   if (!HasRet)
2344     return false;
2345
2346   Chain = TCChain;
2347   return true;
2348 }
2349
2350 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2351   if (!Subtarget->supportsTailCall())
2352     return false;
2353
2354   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2355     return false;
2356
2357   return !Subtarget->isThumb1Only();
2358 }
2359
2360 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2361 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2362 // one of the above mentioned nodes. It has to be wrapped because otherwise
2363 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2364 // be used to form addressing mode. These wrapped nodes will be selected
2365 // into MOVi.
2366 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2367   EVT PtrVT = Op.getValueType();
2368   // FIXME there is no actual debug info here
2369   SDLoc dl(Op);
2370   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2371   SDValue Res;
2372   if (CP->isMachineConstantPoolEntry())
2373     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2374                                     CP->getAlignment());
2375   else
2376     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2377                                     CP->getAlignment());
2378   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2379 }
2380
2381 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2382   return MachineJumpTableInfo::EK_Inline;
2383 }
2384
2385 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2386                                              SelectionDAG &DAG) const {
2387   MachineFunction &MF = DAG.getMachineFunction();
2388   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2389   unsigned ARMPCLabelIndex = 0;
2390   SDLoc DL(Op);
2391   EVT PtrVT = getPointerTy();
2392   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2393   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2394   SDValue CPAddr;
2395   if (RelocM == Reloc::Static) {
2396     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2397   } else {
2398     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2399     ARMPCLabelIndex = AFI->createPICLabelUId();
2400     ARMConstantPoolValue *CPV =
2401       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2402                                       ARMCP::CPBlockAddress, PCAdj);
2403     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2404   }
2405   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2406   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2407                                MachinePointerInfo::getConstantPool(),
2408                                false, false, false, 0);
2409   if (RelocM == Reloc::Static)
2410     return Result;
2411   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2412   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2413 }
2414
2415 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2416 SDValue
2417 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2418                                                  SelectionDAG &DAG) const {
2419   SDLoc dl(GA);
2420   EVT PtrVT = getPointerTy();
2421   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2422   MachineFunction &MF = DAG.getMachineFunction();
2423   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2424   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2425   ARMConstantPoolValue *CPV =
2426     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2427                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2428   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2429   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2430   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2431                          MachinePointerInfo::getConstantPool(),
2432                          false, false, false, 0);
2433   SDValue Chain = Argument.getValue(1);
2434
2435   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2436   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2437
2438   // call __tls_get_addr.
2439   ArgListTy Args;
2440   ArgListEntry Entry;
2441   Entry.Node = Argument;
2442   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2443   Args.push_back(Entry);
2444
2445   // FIXME: is there useful debug info available here?
2446   TargetLowering::CallLoweringInfo CLI(DAG);
2447   CLI.setDebugLoc(dl).setChain(Chain)
2448     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2449                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2450                0);
2451
2452   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2453   return CallResult.first;
2454 }
2455
2456 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2457 // "local exec" model.
2458 SDValue
2459 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2460                                         SelectionDAG &DAG,
2461                                         TLSModel::Model model) const {
2462   const GlobalValue *GV = GA->getGlobal();
2463   SDLoc dl(GA);
2464   SDValue Offset;
2465   SDValue Chain = DAG.getEntryNode();
2466   EVT PtrVT = getPointerTy();
2467   // Get the Thread Pointer
2468   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2469
2470   if (model == TLSModel::InitialExec) {
2471     MachineFunction &MF = DAG.getMachineFunction();
2472     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2473     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2474     // Initial exec model.
2475     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2476     ARMConstantPoolValue *CPV =
2477       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2478                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2479                                       true);
2480     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2481     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2482     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2483                          MachinePointerInfo::getConstantPool(),
2484                          false, false, false, 0);
2485     Chain = Offset.getValue(1);
2486
2487     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2488     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2489
2490     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2491                          MachinePointerInfo::getConstantPool(),
2492                          false, false, false, 0);
2493   } else {
2494     // local exec model
2495     assert(model == TLSModel::LocalExec);
2496     ARMConstantPoolValue *CPV =
2497       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2498     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2499     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2500     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2501                          MachinePointerInfo::getConstantPool(),
2502                          false, false, false, 0);
2503   }
2504
2505   // The address of the thread local variable is the add of the thread
2506   // pointer with the offset of the variable.
2507   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2508 }
2509
2510 SDValue
2511 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2512   // TODO: implement the "local dynamic" model
2513   assert(Subtarget->isTargetELF() &&
2514          "TLS not implemented for non-ELF targets");
2515   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2516
2517   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2518
2519   switch (model) {
2520     case TLSModel::GeneralDynamic:
2521     case TLSModel::LocalDynamic:
2522       return LowerToTLSGeneralDynamicModel(GA, DAG);
2523     case TLSModel::InitialExec:
2524     case TLSModel::LocalExec:
2525       return LowerToTLSExecModels(GA, DAG, model);
2526   }
2527   llvm_unreachable("bogus TLS model");
2528 }
2529
2530 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2531                                                  SelectionDAG &DAG) const {
2532   EVT PtrVT = getPointerTy();
2533   SDLoc dl(Op);
2534   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2535   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2536     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2537     ARMConstantPoolValue *CPV =
2538       ARMConstantPoolConstant::Create(GV,
2539                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2540     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2541     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2542     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2543                                  CPAddr,
2544                                  MachinePointerInfo::getConstantPool(),
2545                                  false, false, false, 0);
2546     SDValue Chain = Result.getValue(1);
2547     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2548     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2549     if (!UseGOTOFF)
2550       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2551                            MachinePointerInfo::getGOT(),
2552                            false, false, false, 0);
2553     return Result;
2554   }
2555
2556   // If we have T2 ops, we can materialize the address directly via movt/movw
2557   // pair. This is always cheaper.
2558   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2559     ++NumMovwMovt;
2560     // FIXME: Once remat is capable of dealing with instructions with register
2561     // operands, expand this into two nodes.
2562     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2563                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2564   } else {
2565     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2566     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2567     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2568                        MachinePointerInfo::getConstantPool(),
2569                        false, false, false, 0);
2570   }
2571 }
2572
2573 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2574                                                     SelectionDAG &DAG) const {
2575   EVT PtrVT = getPointerTy();
2576   SDLoc dl(Op);
2577   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2578   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2579
2580   if (Subtarget->useMovt(DAG.getMachineFunction()))
2581     ++NumMovwMovt;
2582
2583   // FIXME: Once remat is capable of dealing with instructions with register
2584   // operands, expand this into multiple nodes
2585   unsigned Wrapper =
2586       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2587
2588   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2589   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2590
2591   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2592     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2593                          MachinePointerInfo::getGOT(), false, false, false, 0);
2594   return Result;
2595 }
2596
2597 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2598                                                      SelectionDAG &DAG) const {
2599   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2600   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2601          "Windows on ARM expects to use movw/movt");
2602
2603   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2604   const ARMII::TOF TargetFlags =
2605     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2606   EVT PtrVT = getPointerTy();
2607   SDValue Result;
2608   SDLoc DL(Op);
2609
2610   ++NumMovwMovt;
2611
2612   // FIXME: Once remat is capable of dealing with instructions with register
2613   // operands, expand this into two nodes.
2614   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2615                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2616                                                   TargetFlags));
2617   if (GV->hasDLLImportStorageClass())
2618     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2619                          MachinePointerInfo::getGOT(), false, false, false, 0);
2620   return Result;
2621 }
2622
2623 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2624                                                     SelectionDAG &DAG) const {
2625   assert(Subtarget->isTargetELF() &&
2626          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2627   MachineFunction &MF = DAG.getMachineFunction();
2628   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2629   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2630   EVT PtrVT = getPointerTy();
2631   SDLoc dl(Op);
2632   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2633   ARMConstantPoolValue *CPV =
2634     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2635                                   ARMPCLabelIndex, PCAdj);
2636   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2637   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2638   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2639                                MachinePointerInfo::getConstantPool(),
2640                                false, false, false, 0);
2641   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2642   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2643 }
2644
2645 SDValue
2646 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2647   SDLoc dl(Op);
2648   SDValue Val = DAG.getConstant(0, MVT::i32);
2649   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2650                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2651                      Op.getOperand(1), Val);
2652 }
2653
2654 SDValue
2655 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2656   SDLoc dl(Op);
2657   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2658                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2659 }
2660
2661 SDValue
2662 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2663                                           const ARMSubtarget *Subtarget) const {
2664   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2665   SDLoc dl(Op);
2666   switch (IntNo) {
2667   default: return SDValue();    // Don't custom lower most intrinsics.
2668   case Intrinsic::arm_rbit: {
2669     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2670            "RBIT intrinsic must have i32 type!");
2671     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2672   }
2673   case Intrinsic::arm_thread_pointer: {
2674     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2675     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2676   }
2677   case Intrinsic::eh_sjlj_lsda: {
2678     MachineFunction &MF = DAG.getMachineFunction();
2679     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2680     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2681     EVT PtrVT = getPointerTy();
2682     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2683     SDValue CPAddr;
2684     unsigned PCAdj = (RelocM != Reloc::PIC_)
2685       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2686     ARMConstantPoolValue *CPV =
2687       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2688                                       ARMCP::CPLSDA, PCAdj);
2689     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2690     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2691     SDValue Result =
2692       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2693                   MachinePointerInfo::getConstantPool(),
2694                   false, false, false, 0);
2695
2696     if (RelocM == Reloc::PIC_) {
2697       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2698       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2699     }
2700     return Result;
2701   }
2702   case Intrinsic::arm_neon_vmulls:
2703   case Intrinsic::arm_neon_vmullu: {
2704     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2705       ? ARMISD::VMULLs : ARMISD::VMULLu;
2706     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2707                        Op.getOperand(1), Op.getOperand(2));
2708   }
2709   }
2710 }
2711
2712 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2713                                  const ARMSubtarget *Subtarget) {
2714   // FIXME: handle "fence singlethread" more efficiently.
2715   SDLoc dl(Op);
2716   if (!Subtarget->hasDataBarrier()) {
2717     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2718     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2719     // here.
2720     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2721            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2722     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2723                        DAG.getConstant(0, MVT::i32));
2724   }
2725
2726   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2727   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2728   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2729   if (Subtarget->isMClass()) {
2730     // Only a full system barrier exists in the M-class architectures.
2731     Domain = ARM_MB::SY;
2732   } else if (Subtarget->isSwift() && Ord == Release) {
2733     // Swift happens to implement ISHST barriers in a way that's compatible with
2734     // Release semantics but weaker than ISH so we'd be fools not to use
2735     // it. Beware: other processors probably don't!
2736     Domain = ARM_MB::ISHST;
2737   }
2738
2739   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2740                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2741                      DAG.getConstant(Domain, MVT::i32));
2742 }
2743
2744 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2745                              const ARMSubtarget *Subtarget) {
2746   // ARM pre v5TE and Thumb1 does not have preload instructions.
2747   if (!(Subtarget->isThumb2() ||
2748         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2749     // Just preserve the chain.
2750     return Op.getOperand(0);
2751
2752   SDLoc dl(Op);
2753   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2754   if (!isRead &&
2755       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2756     // ARMv7 with MP extension has PLDW.
2757     return Op.getOperand(0);
2758
2759   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2760   if (Subtarget->isThumb()) {
2761     // Invert the bits.
2762     isRead = ~isRead & 1;
2763     isData = ~isData & 1;
2764   }
2765
2766   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2767                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2768                      DAG.getConstant(isData, MVT::i32));
2769 }
2770
2771 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2772   MachineFunction &MF = DAG.getMachineFunction();
2773   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2774
2775   // vastart just stores the address of the VarArgsFrameIndex slot into the
2776   // memory location argument.
2777   SDLoc dl(Op);
2778   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2779   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2780   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2781   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2782                       MachinePointerInfo(SV), false, false, 0);
2783 }
2784
2785 SDValue
2786 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2787                                         SDValue &Root, SelectionDAG &DAG,
2788                                         SDLoc dl) const {
2789   MachineFunction &MF = DAG.getMachineFunction();
2790   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2791
2792   const TargetRegisterClass *RC;
2793   if (AFI->isThumb1OnlyFunction())
2794     RC = &ARM::tGPRRegClass;
2795   else
2796     RC = &ARM::GPRRegClass;
2797
2798   // Transform the arguments stored in physical registers into virtual ones.
2799   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2800   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2801
2802   SDValue ArgValue2;
2803   if (NextVA.isMemLoc()) {
2804     MachineFrameInfo *MFI = MF.getFrameInfo();
2805     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2806
2807     // Create load node to retrieve arguments from the stack.
2808     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2809     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2810                             MachinePointerInfo::getFixedStack(FI),
2811                             false, false, false, 0);
2812   } else {
2813     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2814     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2815   }
2816   if (!Subtarget->isLittle())
2817     std::swap (ArgValue, ArgValue2);
2818   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2819 }
2820
2821 void
2822 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2823                                   unsigned InRegsParamRecordIdx,
2824                                   unsigned ArgSize,
2825                                   unsigned &ArgRegsSize,
2826                                   unsigned &ArgRegsSaveSize)
2827   const {
2828   unsigned NumGPRs;
2829   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2830     unsigned RBegin, REnd;
2831     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2832     NumGPRs = REnd - RBegin;
2833   } else {
2834     unsigned int firstUnalloced;
2835     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs);
2836     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2837   }
2838
2839   unsigned Align = Subtarget->getFrameLowering()->getStackAlignment();
2840   ArgRegsSize = NumGPRs * 4;
2841
2842   // If parameter is split between stack and GPRs...
2843   if (NumGPRs && Align > 4 &&
2844       (ArgRegsSize < ArgSize ||
2845         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2846     // Add padding for part of param recovered from GPRs.  For example,
2847     // if Align == 8, its last byte must be at address K*8 - 1.
2848     // We need to do it, since remained (stack) part of parameter has
2849     // stack alignment, and we need to "attach" "GPRs head" without gaps
2850     // to it:
2851     // Stack:
2852     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2853     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2854     //
2855     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2856     unsigned Padding =
2857         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2858     ArgRegsSaveSize = ArgRegsSize + Padding;
2859   } else
2860     // We don't need to extend regs save size for byval parameters if they
2861     // are passed via GPRs only.
2862     ArgRegsSaveSize = ArgRegsSize;
2863 }
2864
2865 // The remaining GPRs hold either the beginning of variable-argument
2866 // data, or the beginning of an aggregate passed by value (usually
2867 // byval).  Either way, we allocate stack slots adjacent to the data
2868 // provided by our caller, and store the unallocated registers there.
2869 // If this is a variadic function, the va_list pointer will begin with
2870 // these values; otherwise, this reassembles a (byval) structure that
2871 // was split between registers and memory.
2872 // Return: The frame index registers were stored into.
2873 int
2874 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2875                                   SDLoc dl, SDValue &Chain,
2876                                   const Value *OrigArg,
2877                                   unsigned InRegsParamRecordIdx,
2878                                   unsigned OffsetFromOrigArg,
2879                                   unsigned ArgOffset,
2880                                   unsigned ArgSize,
2881                                   bool ForceMutable,
2882                                   unsigned ByValStoreOffset,
2883                                   unsigned TotalArgRegsSaveSize) const {
2884
2885   // Currently, two use-cases possible:
2886   // Case #1. Non-var-args function, and we meet first byval parameter.
2887   //          Setup first unallocated register as first byval register;
2888   //          eat all remained registers
2889   //          (these two actions are performed by HandleByVal method).
2890   //          Then, here, we initialize stack frame with
2891   //          "store-reg" instructions.
2892   // Case #2. Var-args function, that doesn't contain byval parameters.
2893   //          The same: eat all remained unallocated registers,
2894   //          initialize stack frame.
2895
2896   MachineFunction &MF = DAG.getMachineFunction();
2897   MachineFrameInfo *MFI = MF.getFrameInfo();
2898   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2899   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2900   unsigned RBegin, REnd;
2901   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2902     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2903     firstRegToSaveIndex = RBegin - ARM::R0;
2904     lastRegToSaveIndex = REnd - ARM::R0;
2905   } else {
2906     firstRegToSaveIndex = CCInfo.getFirstUnallocated(GPRArgRegs);
2907     lastRegToSaveIndex = 4;
2908   }
2909
2910   unsigned ArgRegsSize, ArgRegsSaveSize;
2911   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2912                  ArgRegsSize, ArgRegsSaveSize);
2913
2914   // Store any by-val regs to their spots on the stack so that they may be
2915   // loaded by deferencing the result of formal parameter pointer or va_next.
2916   // Note: once stack area for byval/varargs registers
2917   // was initialized, it can't be initialized again.
2918   if (ArgRegsSaveSize) {
2919     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2920
2921     if (Padding) {
2922       assert(AFI->getStoredByValParamsPadding() == 0 &&
2923              "The only parameter may be padded.");
2924       AFI->setStoredByValParamsPadding(Padding);
2925     }
2926
2927     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2928                                             Padding +
2929                                               ByValStoreOffset -
2930                                               (int64_t)TotalArgRegsSaveSize,
2931                                             false);
2932     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2933     if (Padding) {
2934        MFI->CreateFixedObject(Padding,
2935                               ArgOffset + ByValStoreOffset -
2936                                 (int64_t)ArgRegsSaveSize,
2937                               false);
2938     }
2939
2940     SmallVector<SDValue, 4> MemOps;
2941     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2942          ++firstRegToSaveIndex, ++i) {
2943       const TargetRegisterClass *RC;
2944       if (AFI->isThumb1OnlyFunction())
2945         RC = &ARM::tGPRRegClass;
2946       else
2947         RC = &ARM::GPRRegClass;
2948
2949       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2950       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2951       SDValue Store =
2952         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2953                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2954                      false, false, 0);
2955       MemOps.push_back(Store);
2956       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2957                         DAG.getConstant(4, getPointerTy()));
2958     }
2959
2960     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2961
2962     if (!MemOps.empty())
2963       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2964     return FrameIndex;
2965   } else {
2966     if (ArgSize == 0) {
2967       // We cannot allocate a zero-byte object for the first variadic argument,
2968       // so just make up a size.
2969       ArgSize = 4;
2970     }
2971     // This will point to the next argument passed via stack.
2972     return MFI->CreateFixedObject(
2973       ArgSize, ArgOffset, !ForceMutable);
2974   }
2975 }
2976
2977 // Setup stack frame, the va_list pointer will start from.
2978 void
2979 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2980                                         SDLoc dl, SDValue &Chain,
2981                                         unsigned ArgOffset,
2982                                         unsigned TotalArgRegsSaveSize,
2983                                         bool ForceMutable) const {
2984   MachineFunction &MF = DAG.getMachineFunction();
2985   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2986
2987   // Try to store any remaining integer argument regs
2988   // to their spots on the stack so that they may be loaded by deferencing
2989   // the result of va_next.
2990   // If there is no regs to be stored, just point address after last
2991   // argument passed via stack.
2992   int FrameIndex =
2993     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2994                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2995                    0, TotalArgRegsSaveSize);
2996
2997   AFI->setVarArgsFrameIndex(FrameIndex);
2998 }
2999
3000 SDValue
3001 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3002                                         CallingConv::ID CallConv, bool isVarArg,
3003                                         const SmallVectorImpl<ISD::InputArg>
3004                                           &Ins,
3005                                         SDLoc dl, SelectionDAG &DAG,
3006                                         SmallVectorImpl<SDValue> &InVals)
3007                                           const {
3008   MachineFunction &MF = DAG.getMachineFunction();
3009   MachineFrameInfo *MFI = MF.getFrameInfo();
3010
3011   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3012
3013   // Assign locations to all of the incoming arguments.
3014   SmallVector<CCValAssign, 16> ArgLocs;
3015   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3016                     *DAG.getContext(), Prologue);
3017   CCInfo.AnalyzeFormalArguments(Ins,
3018                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3019                                                   isVarArg));
3020
3021   SmallVector<SDValue, 16> ArgValues;
3022   int lastInsIndex = -1;
3023   SDValue ArgValue;
3024   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3025   unsigned CurArgIdx = 0;
3026
3027   // Initially ArgRegsSaveSize is zero.
3028   // Then we increase this value each time we meet byval parameter.
3029   // We also increase this value in case of varargs function.
3030   AFI->setArgRegsSaveSize(0);
3031
3032   unsigned ByValStoreOffset = 0;
3033   unsigned TotalArgRegsSaveSize = 0;
3034   unsigned ArgRegsSaveSizeMaxAlign = 4;
3035
3036   // Calculate the amount of stack space that we need to allocate to store
3037   // byval and variadic arguments that are passed in registers.
3038   // We need to know this before we allocate the first byval or variadic
3039   // argument, as they will be allocated a stack slot below the CFA (Canonical
3040   // Frame Address, the stack pointer at entry to the function).
3041   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3042     CCValAssign &VA = ArgLocs[i];
3043     if (VA.isMemLoc()) {
3044       int index = VA.getValNo();
3045       if (index != lastInsIndex) {
3046         ISD::ArgFlagsTy Flags = Ins[index].Flags;
3047         if (Flags.isByVal()) {
3048           unsigned ExtraArgRegsSize;
3049           unsigned ExtraArgRegsSaveSize;
3050           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProcessed(),
3051                          Flags.getByValSize(),
3052                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
3053
3054           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3055           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3056               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3057           CCInfo.nextInRegsParam();
3058         }
3059         lastInsIndex = index;
3060       }
3061     }
3062   }
3063   CCInfo.rewindByValRegsInfo();
3064   lastInsIndex = -1;
3065   if (isVarArg && MFI->hasVAStart()) {
3066     unsigned ExtraArgRegsSize;
3067     unsigned ExtraArgRegsSaveSize;
3068     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3069                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
3070     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3071   }
3072   // If the arg regs save area contains N-byte aligned values, the
3073   // bottom of it must be at least N-byte aligned.
3074   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3075   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3076
3077   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3078     CCValAssign &VA = ArgLocs[i];
3079     if (Ins[VA.getValNo()].isOrigArg()) {
3080       std::advance(CurOrigArg,
3081                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3082       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3083     }
3084     // Arguments stored in registers.
3085     if (VA.isRegLoc()) {
3086       EVT RegVT = VA.getLocVT();
3087
3088       if (VA.needsCustom()) {
3089         // f64 and vector types are split up into multiple registers or
3090         // combinations of registers and stack slots.
3091         if (VA.getLocVT() == MVT::v2f64) {
3092           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3093                                                    Chain, DAG, dl);
3094           VA = ArgLocs[++i]; // skip ahead to next loc
3095           SDValue ArgValue2;
3096           if (VA.isMemLoc()) {
3097             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3098             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3099             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3100                                     MachinePointerInfo::getFixedStack(FI),
3101                                     false, false, false, 0);
3102           } else {
3103             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3104                                              Chain, DAG, dl);
3105           }
3106           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3107           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3108                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3109           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3110                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3111         } else
3112           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3113
3114       } else {
3115         const TargetRegisterClass *RC;
3116
3117         if (RegVT == MVT::f32)
3118           RC = &ARM::SPRRegClass;
3119         else if (RegVT == MVT::f64)
3120           RC = &ARM::DPRRegClass;
3121         else if (RegVT == MVT::v2f64)
3122           RC = &ARM::QPRRegClass;
3123         else if (RegVT == MVT::i32)
3124           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3125                                            : &ARM::GPRRegClass;
3126         else
3127           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3128
3129         // Transform the arguments in physical registers into virtual ones.
3130         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3131         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3132       }
3133
3134       // If this is an 8 or 16-bit value, it is really passed promoted
3135       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3136       // truncate to the right size.
3137       switch (VA.getLocInfo()) {
3138       default: llvm_unreachable("Unknown loc info!");
3139       case CCValAssign::Full: break;
3140       case CCValAssign::BCvt:
3141         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3142         break;
3143       case CCValAssign::SExt:
3144         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3145                                DAG.getValueType(VA.getValVT()));
3146         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3147         break;
3148       case CCValAssign::ZExt:
3149         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3150                                DAG.getValueType(VA.getValVT()));
3151         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3152         break;
3153       }
3154
3155       InVals.push_back(ArgValue);
3156
3157     } else { // VA.isRegLoc()
3158
3159       // sanity check
3160       assert(VA.isMemLoc());
3161       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3162
3163       int index = VA.getValNo();
3164
3165       // Some Ins[] entries become multiple ArgLoc[] entries.
3166       // Process them only once.
3167       if (index != lastInsIndex)
3168         {
3169           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3170           // FIXME: For now, all byval parameter objects are marked mutable.
3171           // This can be changed with more analysis.
3172           // In case of tail call optimization mark all arguments mutable.
3173           // Since they could be overwritten by lowering of arguments in case of
3174           // a tail call.
3175           if (Flags.isByVal()) {
3176             assert(Ins[index].isOrigArg() &&
3177                    "Byval arguments cannot be implicit");
3178             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3179
3180             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3181             int FrameIndex = StoreByValRegs(
3182                 CCInfo, DAG, dl, Chain, CurOrigArg,
3183                 CurByValIndex,
3184                 Ins[VA.getValNo()].PartOffset,
3185                 VA.getLocMemOffset(),
3186                 Flags.getByValSize(),
3187                 true /*force mutable frames*/,
3188                 ByValStoreOffset,
3189                 TotalArgRegsSaveSize);
3190             ByValStoreOffset += Flags.getByValSize();
3191             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3192             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3193             CCInfo.nextInRegsParam();
3194           } else {
3195             unsigned FIOffset = VA.getLocMemOffset();
3196             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3197                                             FIOffset, true);
3198
3199             // Create load nodes to retrieve arguments from the stack.
3200             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3201             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3202                                          MachinePointerInfo::getFixedStack(FI),
3203                                          false, false, false, 0));
3204           }
3205           lastInsIndex = index;
3206         }
3207     }
3208   }
3209
3210   // varargs
3211   if (isVarArg && MFI->hasVAStart())
3212     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3213                          CCInfo.getNextStackOffset(),
3214                          TotalArgRegsSaveSize);
3215
3216   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3217
3218   return Chain;
3219 }
3220
3221 /// isFloatingPointZero - Return true if this is +0.0.
3222 static bool isFloatingPointZero(SDValue Op) {
3223   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3224     return CFP->getValueAPF().isPosZero();
3225   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3226     // Maybe this has already been legalized into the constant pool?
3227     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3228       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3229       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3230         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3231           return CFP->getValueAPF().isPosZero();
3232     }
3233   } else if (Op->getOpcode() == ISD::BITCAST &&
3234              Op->getValueType(0) == MVT::f64) {
3235     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3236     // created by LowerConstantFP().
3237     SDValue BitcastOp = Op->getOperand(0);
3238     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3239       SDValue MoveOp = BitcastOp->getOperand(0);
3240       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3241           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3242         return true;
3243       }
3244     }
3245   }
3246   return false;
3247 }
3248
3249 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3250 /// the given operands.
3251 SDValue
3252 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3253                              SDValue &ARMcc, SelectionDAG &DAG,
3254                              SDLoc dl) const {
3255   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3256     unsigned C = RHSC->getZExtValue();
3257     if (!isLegalICmpImmediate(C)) {
3258       // Constant does not fit, try adjusting it by one?
3259       switch (CC) {
3260       default: break;
3261       case ISD::SETLT:
3262       case ISD::SETGE:
3263         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3264           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3265           RHS = DAG.getConstant(C-1, MVT::i32);
3266         }
3267         break;
3268       case ISD::SETULT:
3269       case ISD::SETUGE:
3270         if (C != 0 && isLegalICmpImmediate(C-1)) {
3271           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3272           RHS = DAG.getConstant(C-1, MVT::i32);
3273         }
3274         break;
3275       case ISD::SETLE:
3276       case ISD::SETGT:
3277         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3278           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3279           RHS = DAG.getConstant(C+1, MVT::i32);
3280         }
3281         break;
3282       case ISD::SETULE:
3283       case ISD::SETUGT:
3284         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3285           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3286           RHS = DAG.getConstant(C+1, MVT::i32);
3287         }
3288         break;
3289       }
3290     }
3291   }
3292
3293   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3294   ARMISD::NodeType CompareType;
3295   switch (CondCode) {
3296   default:
3297     CompareType = ARMISD::CMP;
3298     break;
3299   case ARMCC::EQ:
3300   case ARMCC::NE:
3301     // Uses only Z Flag
3302     CompareType = ARMISD::CMPZ;
3303     break;
3304   }
3305   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3306   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3307 }
3308
3309 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3310 SDValue
3311 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3312                              SDLoc dl) const {
3313   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3314   SDValue Cmp;
3315   if (!isFloatingPointZero(RHS))
3316     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3317   else
3318     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3319   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3320 }
3321
3322 /// duplicateCmp - Glue values can have only one use, so this function
3323 /// duplicates a comparison node.
3324 SDValue
3325 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3326   unsigned Opc = Cmp.getOpcode();
3327   SDLoc DL(Cmp);
3328   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3329     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3330
3331   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3332   Cmp = Cmp.getOperand(0);
3333   Opc = Cmp.getOpcode();
3334   if (Opc == ARMISD::CMPFP)
3335     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3336   else {
3337     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3338     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3339   }
3340   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3341 }
3342
3343 std::pair<SDValue, SDValue>
3344 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3345                                  SDValue &ARMcc) const {
3346   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3347
3348   SDValue Value, OverflowCmp;
3349   SDValue LHS = Op.getOperand(0);
3350   SDValue RHS = Op.getOperand(1);
3351
3352
3353   // FIXME: We are currently always generating CMPs because we don't support
3354   // generating CMN through the backend. This is not as good as the natural
3355   // CMP case because it causes a register dependency and cannot be folded
3356   // later.
3357
3358   switch (Op.getOpcode()) {
3359   default:
3360     llvm_unreachable("Unknown overflow instruction!");
3361   case ISD::SADDO:
3362     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3363     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3364     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3365     break;
3366   case ISD::UADDO:
3367     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3368     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3369     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3370     break;
3371   case ISD::SSUBO:
3372     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3373     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3374     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3375     break;
3376   case ISD::USUBO:
3377     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3378     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3379     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3380     break;
3381   } // switch (...)
3382
3383   return std::make_pair(Value, OverflowCmp);
3384 }
3385
3386
3387 SDValue
3388 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3389   // Let legalize expand this if it isn't a legal type yet.
3390   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3391     return SDValue();
3392
3393   SDValue Value, OverflowCmp;
3394   SDValue ARMcc;
3395   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3396   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3397   // We use 0 and 1 as false and true values.
3398   SDValue TVal = DAG.getConstant(1, MVT::i32);
3399   SDValue FVal = DAG.getConstant(0, MVT::i32);
3400   EVT VT = Op.getValueType();
3401
3402   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3403                                  ARMcc, CCR, OverflowCmp);
3404
3405   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3406   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3407 }
3408
3409
3410 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3411   SDValue Cond = Op.getOperand(0);
3412   SDValue SelectTrue = Op.getOperand(1);
3413   SDValue SelectFalse = Op.getOperand(2);
3414   SDLoc dl(Op);
3415   unsigned Opc = Cond.getOpcode();
3416
3417   if (Cond.getResNo() == 1 &&
3418       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3419        Opc == ISD::USUBO)) {
3420     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3421       return SDValue();
3422
3423     SDValue Value, OverflowCmp;
3424     SDValue ARMcc;
3425     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3426     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3427     EVT VT = Op.getValueType();
3428
3429     return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3430                    OverflowCmp, DAG);
3431   }
3432
3433   // Convert:
3434   //
3435   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3436   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3437   //
3438   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3439     const ConstantSDNode *CMOVTrue =
3440       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3441     const ConstantSDNode *CMOVFalse =
3442       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3443
3444     if (CMOVTrue && CMOVFalse) {
3445       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3446       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3447
3448       SDValue True;
3449       SDValue False;
3450       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3451         True = SelectTrue;
3452         False = SelectFalse;
3453       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3454         True = SelectFalse;
3455         False = SelectTrue;
3456       }
3457
3458       if (True.getNode() && False.getNode()) {
3459         EVT VT = Op.getValueType();
3460         SDValue ARMcc = Cond.getOperand(2);
3461         SDValue CCR = Cond.getOperand(3);
3462         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3463         assert(True.getValueType() == VT);
3464         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3465       }
3466     }
3467   }
3468
3469   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3470   // undefined bits before doing a full-word comparison with zero.
3471   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3472                      DAG.getConstant(1, Cond.getValueType()));
3473
3474   return DAG.getSelectCC(dl, Cond,
3475                          DAG.getConstant(0, Cond.getValueType()),
3476                          SelectTrue, SelectFalse, ISD::SETNE);
3477 }
3478
3479 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3480   if (CC == ISD::SETNE)
3481     return ISD::SETEQ;
3482   return ISD::getSetCCInverse(CC, true);
3483 }
3484
3485 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3486                                  bool &swpCmpOps, bool &swpVselOps) {
3487   // Start by selecting the GE condition code for opcodes that return true for
3488   // 'equality'
3489   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3490       CC == ISD::SETULE)
3491     CondCode = ARMCC::GE;
3492
3493   // and GT for opcodes that return false for 'equality'.
3494   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3495            CC == ISD::SETULT)
3496     CondCode = ARMCC::GT;
3497
3498   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3499   // to swap the compare operands.
3500   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3501       CC == ISD::SETULT)
3502     swpCmpOps = true;
3503
3504   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3505   // If we have an unordered opcode, we need to swap the operands to the VSEL
3506   // instruction (effectively negating the condition).
3507   //
3508   // This also has the effect of swapping which one of 'less' or 'greater'
3509   // returns true, so we also swap the compare operands. It also switches
3510   // whether we return true for 'equality', so we compensate by picking the
3511   // opposite condition code to our original choice.
3512   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3513       CC == ISD::SETUGT) {
3514     swpCmpOps = !swpCmpOps;
3515     swpVselOps = !swpVselOps;
3516     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3517   }
3518
3519   // 'ordered' is 'anything but unordered', so use the VS condition code and
3520   // swap the VSEL operands.
3521   if (CC == ISD::SETO) {
3522     CondCode = ARMCC::VS;
3523     swpVselOps = true;
3524   }
3525
3526   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3527   // code and swap the VSEL operands.
3528   if (CC == ISD::SETUNE) {
3529     CondCode = ARMCC::EQ;
3530     swpVselOps = true;
3531   }
3532 }
3533
3534 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3535                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3536                                    SDValue Cmp, SelectionDAG &DAG) const {
3537   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3538     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3539                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3540     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3541                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3542
3543     SDValue TrueLow = TrueVal.getValue(0);
3544     SDValue TrueHigh = TrueVal.getValue(1);
3545     SDValue FalseLow = FalseVal.getValue(0);
3546     SDValue FalseHigh = FalseVal.getValue(1);
3547
3548     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3549                               ARMcc, CCR, Cmp);
3550     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3551                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3552
3553     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3554   } else {
3555     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3556                        Cmp);
3557   }
3558 }
3559
3560 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3561   EVT VT = Op.getValueType();
3562   SDValue LHS = Op.getOperand(0);
3563   SDValue RHS = Op.getOperand(1);
3564   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3565   SDValue TrueVal = Op.getOperand(2);
3566   SDValue FalseVal = Op.getOperand(3);
3567   SDLoc dl(Op);
3568
3569   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3570     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3571                                                     dl);
3572
3573     // If softenSetCCOperands only returned one value, we should compare it to
3574     // zero.
3575     if (!RHS.getNode()) {
3576       RHS = DAG.getConstant(0, LHS.getValueType());
3577       CC = ISD::SETNE;
3578     }
3579   }
3580
3581   if (LHS.getValueType() == MVT::i32) {
3582     // Try to generate VSEL on ARMv8.
3583     // The VSEL instruction can't use all the usual ARM condition
3584     // codes: it only has two bits to select the condition code, so it's
3585     // constrained to use only GE, GT, VS and EQ.
3586     //
3587     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3588     // swap the operands of the previous compare instruction (effectively
3589     // inverting the compare condition, swapping 'less' and 'greater') and
3590     // sometimes need to swap the operands to the VSEL (which inverts the
3591     // condition in the sense of firing whenever the previous condition didn't)
3592     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3593                                     TrueVal.getValueType() == MVT::f64)) {
3594       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3595       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3596           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3597         CC = getInverseCCForVSEL(CC);
3598         std::swap(TrueVal, FalseVal);
3599       }
3600     }
3601
3602     SDValue ARMcc;
3603     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3604     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3605     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3606   }
3607
3608   ARMCC::CondCodes CondCode, CondCode2;
3609   FPCCToARMCC(CC, CondCode, CondCode2);
3610
3611   // Try to generate VSEL on ARMv8.
3612   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3613                                   TrueVal.getValueType() == MVT::f64)) {
3614     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3615     // same operands, as follows:
3616     //   c = fcmp [ogt, olt, ugt, ult] a, b
3617     //   select c, a, b
3618     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3619     // handled differently than the original code sequence.
3620     if (getTargetMachine().Options.UnsafeFPMath) {
3621       if (LHS == TrueVal && RHS == FalseVal) {
3622         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3623           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3624         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3625           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3626       } else if (LHS == FalseVal && RHS == TrueVal) {
3627         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3628           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3629         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3630           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3631       }
3632     }
3633
3634     bool swpCmpOps = false;
3635     bool swpVselOps = false;
3636     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3637
3638     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3639         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3640       if (swpCmpOps)
3641         std::swap(LHS, RHS);
3642       if (swpVselOps)
3643         std::swap(TrueVal, FalseVal);
3644     }
3645   }
3646
3647   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3648   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3649   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3650   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3651   if (CondCode2 != ARMCC::AL) {
3652     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3653     // FIXME: Needs another CMP because flag can have but one use.
3654     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3655     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3656   }
3657   return Result;
3658 }
3659
3660 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3661 /// to morph to an integer compare sequence.
3662 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3663                            const ARMSubtarget *Subtarget) {
3664   SDNode *N = Op.getNode();
3665   if (!N->hasOneUse())
3666     // Otherwise it requires moving the value from fp to integer registers.
3667     return false;
3668   if (!N->getNumValues())
3669     return false;
3670   EVT VT = Op.getValueType();
3671   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3672     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3673     // vmrs are very slow, e.g. cortex-a8.
3674     return false;
3675
3676   if (isFloatingPointZero(Op)) {
3677     SeenZero = true;
3678     return true;
3679   }
3680   return ISD::isNormalLoad(N);
3681 }
3682
3683 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3684   if (isFloatingPointZero(Op))
3685     return DAG.getConstant(0, MVT::i32);
3686
3687   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3688     return DAG.getLoad(MVT::i32, SDLoc(Op),
3689                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3690                        Ld->isVolatile(), Ld->isNonTemporal(),
3691                        Ld->isInvariant(), Ld->getAlignment());
3692
3693   llvm_unreachable("Unknown VFP cmp argument!");
3694 }
3695
3696 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3697                            SDValue &RetVal1, SDValue &RetVal2) {
3698   if (isFloatingPointZero(Op)) {
3699     RetVal1 = DAG.getConstant(0, MVT::i32);
3700     RetVal2 = DAG.getConstant(0, MVT::i32);
3701     return;
3702   }
3703
3704   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3705     SDValue Ptr = Ld->getBasePtr();
3706     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3707                           Ld->getChain(), Ptr,
3708                           Ld->getPointerInfo(),
3709                           Ld->isVolatile(), Ld->isNonTemporal(),
3710                           Ld->isInvariant(), Ld->getAlignment());
3711
3712     EVT PtrType = Ptr.getValueType();
3713     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3714     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3715                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3716     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3717                           Ld->getChain(), NewPtr,
3718                           Ld->getPointerInfo().getWithOffset(4),
3719                           Ld->isVolatile(), Ld->isNonTemporal(),
3720                           Ld->isInvariant(), NewAlign);
3721     return;
3722   }
3723
3724   llvm_unreachable("Unknown VFP cmp argument!");
3725 }
3726
3727 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3728 /// f32 and even f64 comparisons to integer ones.
3729 SDValue
3730 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3731   SDValue Chain = Op.getOperand(0);
3732   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3733   SDValue LHS = Op.getOperand(2);
3734   SDValue RHS = Op.getOperand(3);
3735   SDValue Dest = Op.getOperand(4);
3736   SDLoc dl(Op);
3737
3738   bool LHSSeenZero = false;
3739   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3740   bool RHSSeenZero = false;
3741   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3742   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3743     // If unsafe fp math optimization is enabled and there are no other uses of
3744     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3745     // to an integer comparison.
3746     if (CC == ISD::SETOEQ)
3747       CC = ISD::SETEQ;
3748     else if (CC == ISD::SETUNE)
3749       CC = ISD::SETNE;
3750
3751     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3752     SDValue ARMcc;
3753     if (LHS.getValueType() == MVT::f32) {
3754       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3755                         bitcastf32Toi32(LHS, DAG), Mask);
3756       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3757                         bitcastf32Toi32(RHS, DAG), Mask);
3758       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3759       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3760       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3761                          Chain, Dest, ARMcc, CCR, Cmp);
3762     }
3763
3764     SDValue LHS1, LHS2;
3765     SDValue RHS1, RHS2;
3766     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3767     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3768     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3769     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3770     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3771     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3772     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3773     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3774     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3775   }
3776
3777   return SDValue();
3778 }
3779
3780 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3781   SDValue Chain = Op.getOperand(0);
3782   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3783   SDValue LHS = Op.getOperand(2);
3784   SDValue RHS = Op.getOperand(3);
3785   SDValue Dest = Op.getOperand(4);
3786   SDLoc dl(Op);
3787
3788   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3789     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3790                                                     dl);
3791
3792     // If softenSetCCOperands only returned one value, we should compare it to
3793     // zero.
3794     if (!RHS.getNode()) {
3795       RHS = DAG.getConstant(0, LHS.getValueType());
3796       CC = ISD::SETNE;
3797     }
3798   }
3799
3800   if (LHS.getValueType() == MVT::i32) {
3801     SDValue ARMcc;
3802     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3803     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3804     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3805                        Chain, Dest, ARMcc, CCR, Cmp);
3806   }
3807
3808   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3809
3810   if (getTargetMachine().Options.UnsafeFPMath &&
3811       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3812        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3813     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3814     if (Result.getNode())
3815       return Result;
3816   }
3817
3818   ARMCC::CondCodes CondCode, CondCode2;
3819   FPCCToARMCC(CC, CondCode, CondCode2);
3820
3821   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3822   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3823   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3824   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3825   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3826   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3827   if (CondCode2 != ARMCC::AL) {
3828     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3829     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3830     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3831   }
3832   return Res;
3833 }
3834
3835 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3836   SDValue Chain = Op.getOperand(0);
3837   SDValue Table = Op.getOperand(1);
3838   SDValue Index = Op.getOperand(2);
3839   SDLoc dl(Op);
3840
3841   EVT PTy = getPointerTy();
3842   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3843   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3844   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3845   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3846   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3847   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3848   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3849   if (Subtarget->isThumb2()) {
3850     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3851     // which does another jump to the destination. This also makes it easier
3852     // to translate it to TBB / TBH later.
3853     // FIXME: This might not work if the function is extremely large.
3854     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3855                        Addr, Op.getOperand(2), JTI, UId);
3856   }
3857   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3858     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3859                        MachinePointerInfo::getJumpTable(),
3860                        false, false, false, 0);
3861     Chain = Addr.getValue(1);
3862     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3863     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3864   } else {
3865     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3866                        MachinePointerInfo::getJumpTable(),
3867                        false, false, false, 0);
3868     Chain = Addr.getValue(1);
3869     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3870   }
3871 }
3872
3873 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3874   EVT VT = Op.getValueType();
3875   SDLoc dl(Op);
3876
3877   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3878     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3879       return Op;
3880     return DAG.UnrollVectorOp(Op.getNode());
3881   }
3882
3883   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3884          "Invalid type for custom lowering!");
3885   if (VT != MVT::v4i16)
3886     return DAG.UnrollVectorOp(Op.getNode());
3887
3888   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3889   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3890 }
3891
3892 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3893   EVT VT = Op.getValueType();
3894   if (VT.isVector())
3895     return LowerVectorFP_TO_INT(Op, DAG);
3896
3897   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3898     RTLIB::Libcall LC;
3899     if (Op.getOpcode() == ISD::FP_TO_SINT)
3900       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3901                               Op.getValueType());
3902     else
3903       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3904                               Op.getValueType());
3905     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3906                        /*isSigned*/ false, SDLoc(Op)).first;
3907   }
3908
3909   SDLoc dl(Op);
3910   unsigned Opc;
3911
3912   switch (Op.getOpcode()) {
3913   default: llvm_unreachable("Invalid opcode!");
3914   case ISD::FP_TO_SINT:
3915     Opc = ARMISD::FTOSI;
3916     break;
3917   case ISD::FP_TO_UINT:
3918     Opc = ARMISD::FTOUI;
3919     break;
3920   }
3921   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3922   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3923 }
3924
3925 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3926   EVT VT = Op.getValueType();
3927   SDLoc dl(Op);
3928
3929   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3930     if (VT.getVectorElementType() == MVT::f32)
3931       return Op;
3932     return DAG.UnrollVectorOp(Op.getNode());
3933   }
3934
3935   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3936          "Invalid type for custom lowering!");
3937   if (VT != MVT::v4f32)
3938     return DAG.UnrollVectorOp(Op.getNode());
3939
3940   unsigned CastOpc;
3941   unsigned Opc;
3942   switch (Op.getOpcode()) {
3943   default: llvm_unreachable("Invalid opcode!");
3944   case ISD::SINT_TO_FP:
3945     CastOpc = ISD::SIGN_EXTEND;
3946     Opc = ISD::SINT_TO_FP;
3947     break;
3948   case ISD::UINT_TO_FP:
3949     CastOpc = ISD::ZERO_EXTEND;
3950     Opc = ISD::UINT_TO_FP;
3951     break;
3952   }
3953
3954   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3955   return DAG.getNode(Opc, dl, VT, Op);
3956 }
3957
3958 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3959   EVT VT = Op.getValueType();
3960   if (VT.isVector())
3961     return LowerVectorINT_TO_FP(Op, DAG);
3962
3963   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3964     RTLIB::Libcall LC;
3965     if (Op.getOpcode() == ISD::SINT_TO_FP)
3966       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3967                               Op.getValueType());
3968     else
3969       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3970                               Op.getValueType());
3971     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3972                        /*isSigned*/ false, SDLoc(Op)).first;
3973   }
3974
3975   SDLoc dl(Op);
3976   unsigned Opc;
3977
3978   switch (Op.getOpcode()) {
3979   default: llvm_unreachable("Invalid opcode!");
3980   case ISD::SINT_TO_FP:
3981     Opc = ARMISD::SITOF;
3982     break;
3983   case ISD::UINT_TO_FP:
3984     Opc = ARMISD::UITOF;
3985     break;
3986   }
3987
3988   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3989   return DAG.getNode(Opc, dl, VT, Op);
3990 }
3991
3992 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3993   // Implement fcopysign with a fabs and a conditional fneg.
3994   SDValue Tmp0 = Op.getOperand(0);
3995   SDValue Tmp1 = Op.getOperand(1);
3996   SDLoc dl(Op);
3997   EVT VT = Op.getValueType();
3998   EVT SrcVT = Tmp1.getValueType();
3999   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4000     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4001   bool UseNEON = !InGPR && Subtarget->hasNEON();
4002
4003   if (UseNEON) {
4004     // Use VBSL to copy the sign bit.
4005     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4006     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4007                                DAG.getTargetConstant(EncodedVal, MVT::i32));
4008     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4009     if (VT == MVT::f64)
4010       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4011                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4012                          DAG.getConstant(32, MVT::i32));
4013     else /*if (VT == MVT::f32)*/
4014       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4015     if (SrcVT == MVT::f32) {
4016       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4017       if (VT == MVT::f64)
4018         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4019                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4020                            DAG.getConstant(32, MVT::i32));
4021     } else if (VT == MVT::f32)
4022       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4023                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4024                          DAG.getConstant(32, MVT::i32));
4025     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4026     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4027
4028     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4029                                             MVT::i32);
4030     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4031     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4032                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4033
4034     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4035                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4036                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4037     if (VT == MVT::f32) {
4038       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4039       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4040                         DAG.getConstant(0, MVT::i32));
4041     } else {
4042       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4043     }
4044
4045     return Res;
4046   }
4047
4048   // Bitcast operand 1 to i32.
4049   if (SrcVT == MVT::f64)
4050     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4051                        Tmp1).getValue(1);
4052   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4053
4054   // Or in the signbit with integer operations.
4055   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4056   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4057   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4058   if (VT == MVT::f32) {
4059     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4060                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4061     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4062                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4063   }
4064
4065   // f64: Or the high part with signbit and then combine two parts.
4066   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4067                      Tmp0);
4068   SDValue Lo = Tmp0.getValue(0);
4069   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4070   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4071   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4072 }
4073
4074 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4075   MachineFunction &MF = DAG.getMachineFunction();
4076   MachineFrameInfo *MFI = MF.getFrameInfo();
4077   MFI->setReturnAddressIsTaken(true);
4078
4079   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4080     return SDValue();
4081
4082   EVT VT = Op.getValueType();
4083   SDLoc dl(Op);
4084   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4085   if (Depth) {
4086     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4087     SDValue Offset = DAG.getConstant(4, MVT::i32);
4088     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4089                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4090                        MachinePointerInfo(), false, false, false, 0);
4091   }
4092
4093   // Return LR, which contains the return address. Mark it an implicit live-in.
4094   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4095   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4096 }
4097
4098 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4099   const ARMBaseRegisterInfo &ARI =
4100     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4101   MachineFunction &MF = DAG.getMachineFunction();
4102   MachineFrameInfo *MFI = MF.getFrameInfo();
4103   MFI->setFrameAddressIsTaken(true);
4104
4105   EVT VT = Op.getValueType();
4106   SDLoc dl(Op);  // FIXME probably not meaningful
4107   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4108   unsigned FrameReg = ARI.getFrameRegister(MF);
4109   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4110   while (Depth--)
4111     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4112                             MachinePointerInfo(),
4113                             false, false, false, 0);
4114   return FrameAddr;
4115 }
4116
4117 // FIXME? Maybe this could be a TableGen attribute on some registers and
4118 // this table could be generated automatically from RegInfo.
4119 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4120                                               EVT VT) const {
4121   unsigned Reg = StringSwitch<unsigned>(RegName)
4122                        .Case("sp", ARM::SP)
4123                        .Default(0);
4124   if (Reg)
4125     return Reg;
4126   report_fatal_error("Invalid register name global variable");
4127 }
4128
4129 /// ExpandBITCAST - If the target supports VFP, this function is called to
4130 /// expand a bit convert where either the source or destination type is i64 to
4131 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4132 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4133 /// vectors), since the legalizer won't know what to do with that.
4134 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4135   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4136   SDLoc dl(N);
4137   SDValue Op = N->getOperand(0);
4138
4139   // This function is only supposed to be called for i64 types, either as the
4140   // source or destination of the bit convert.
4141   EVT SrcVT = Op.getValueType();
4142   EVT DstVT = N->getValueType(0);
4143   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4144          "ExpandBITCAST called for non-i64 type");
4145
4146   // Turn i64->f64 into VMOVDRR.
4147   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4148     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4149                              DAG.getConstant(0, MVT::i32));
4150     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4151                              DAG.getConstant(1, MVT::i32));
4152     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4153                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4154   }
4155
4156   // Turn f64->i64 into VMOVRRD.
4157   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4158     SDValue Cvt;
4159     if (TLI.isBigEndian() && SrcVT.isVector() &&
4160         SrcVT.getVectorNumElements() > 1)
4161       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4162                         DAG.getVTList(MVT::i32, MVT::i32),
4163                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4164     else
4165       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4166                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4167     // Merge the pieces into a single i64 value.
4168     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4169   }
4170
4171   return SDValue();
4172 }
4173
4174 /// getZeroVector - Returns a vector of specified type with all zero elements.
4175 /// Zero vectors are used to represent vector negation and in those cases
4176 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4177 /// not support i64 elements, so sometimes the zero vectors will need to be
4178 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4179 /// zero vector.
4180 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4181   assert(VT.isVector() && "Expected a vector type");
4182   // The canonical modified immediate encoding of a zero vector is....0!
4183   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4184   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4185   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4186   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4187 }
4188
4189 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4190 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4191 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4192                                                 SelectionDAG &DAG) const {
4193   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4194   EVT VT = Op.getValueType();
4195   unsigned VTBits = VT.getSizeInBits();
4196   SDLoc dl(Op);
4197   SDValue ShOpLo = Op.getOperand(0);
4198   SDValue ShOpHi = Op.getOperand(1);
4199   SDValue ShAmt  = Op.getOperand(2);
4200   SDValue ARMcc;
4201   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4202
4203   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4204
4205   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4206                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4207   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4208   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4209                                    DAG.getConstant(VTBits, MVT::i32));
4210   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4211   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4212   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4213
4214   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4215   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4216                           ARMcc, DAG, dl);
4217   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4218   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4219                            CCR, Cmp);
4220
4221   SDValue Ops[2] = { Lo, Hi };
4222   return DAG.getMergeValues(Ops, dl);
4223 }
4224
4225 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4226 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4227 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4228                                                SelectionDAG &DAG) const {
4229   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4230   EVT VT = Op.getValueType();
4231   unsigned VTBits = VT.getSizeInBits();
4232   SDLoc dl(Op);
4233   SDValue ShOpLo = Op.getOperand(0);
4234   SDValue ShOpHi = Op.getOperand(1);
4235   SDValue ShAmt  = Op.getOperand(2);
4236   SDValue ARMcc;
4237
4238   assert(Op.getOpcode() == ISD::SHL_PARTS);
4239   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4240                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4241   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4242   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4243                                    DAG.getConstant(VTBits, MVT::i32));
4244   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4245   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4246
4247   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4248   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4249   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4250                           ARMcc, DAG, dl);
4251   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4252   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4253                            CCR, Cmp);
4254
4255   SDValue Ops[2] = { Lo, Hi };
4256   return DAG.getMergeValues(Ops, dl);
4257 }
4258
4259 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4260                                             SelectionDAG &DAG) const {
4261   // The rounding mode is in bits 23:22 of the FPSCR.
4262   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4263   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4264   // so that the shift + and get folded into a bitfield extract.
4265   SDLoc dl(Op);
4266   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4267                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4268                                               MVT::i32));
4269   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4270                                   DAG.getConstant(1U << 22, MVT::i32));
4271   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4272                               DAG.getConstant(22, MVT::i32));
4273   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4274                      DAG.getConstant(3, MVT::i32));
4275 }
4276
4277 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4278                          const ARMSubtarget *ST) {
4279   EVT VT = N->getValueType(0);
4280   SDLoc dl(N);
4281
4282   if (!ST->hasV6T2Ops())
4283     return SDValue();
4284
4285   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4286   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4287 }
4288
4289 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4290 /// for each 16-bit element from operand, repeated.  The basic idea is to
4291 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4292 ///
4293 /// Trace for v4i16:
4294 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4295 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4296 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4297 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4298 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4299 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4300 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4301 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4302 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4303   EVT VT = N->getValueType(0);
4304   SDLoc DL(N);
4305
4306   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4307   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4308   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4309   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4310   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4311   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4312 }
4313
4314 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4315 /// bit-count for each 16-bit element from the operand.  We need slightly
4316 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4317 /// 64/128-bit registers.
4318 ///
4319 /// Trace for v4i16:
4320 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4321 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4322 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4323 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4324 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4325   EVT VT = N->getValueType(0);
4326   SDLoc DL(N);
4327
4328   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4329   if (VT.is64BitVector()) {
4330     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4331     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4332                        DAG.getIntPtrConstant(0));
4333   } else {
4334     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4335                                     BitCounts, DAG.getIntPtrConstant(0));
4336     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4337   }
4338 }
4339
4340 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4341 /// bit-count for each 32-bit element from the operand.  The idea here is
4342 /// to split the vector into 16-bit elements, leverage the 16-bit count
4343 /// routine, and then combine the results.
4344 ///
4345 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4346 /// input    = [v0    v1    ] (vi: 32-bit elements)
4347 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4348 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4349 /// vrev: N0 = [k1 k0 k3 k2 ]
4350 ///            [k0 k1 k2 k3 ]
4351 ///       N1 =+[k1 k0 k3 k2 ]
4352 ///            [k0 k2 k1 k3 ]
4353 ///       N2 =+[k1 k3 k0 k2 ]
4354 ///            [k0    k2    k1    k3    ]
4355 /// Extended =+[k1    k3    k0    k2    ]
4356 ///            [k0    k2    ]
4357 /// Extracted=+[k1    k3    ]
4358 ///
4359 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4360   EVT VT = N->getValueType(0);
4361   SDLoc DL(N);
4362
4363   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4364
4365   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4366   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4367   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4368   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4369   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4370
4371   if (VT.is64BitVector()) {
4372     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4373     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4374                        DAG.getIntPtrConstant(0));
4375   } else {
4376     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4377                                     DAG.getIntPtrConstant(0));
4378     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4379   }
4380 }
4381
4382 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4383                           const ARMSubtarget *ST) {
4384   EVT VT = N->getValueType(0);
4385
4386   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4387   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4388           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4389          "Unexpected type for custom ctpop lowering");
4390
4391   if (VT.getVectorElementType() == MVT::i32)
4392     return lowerCTPOP32BitElements(N, DAG);
4393   else
4394     return lowerCTPOP16BitElements(N, DAG);
4395 }
4396
4397 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4398                           const ARMSubtarget *ST) {
4399   EVT VT = N->getValueType(0);
4400   SDLoc dl(N);
4401
4402   if (!VT.isVector())
4403     return SDValue();
4404
4405   // Lower vector shifts on NEON to use VSHL.
4406   assert(ST->hasNEON() && "unexpected vector shift");
4407
4408   // Left shifts translate directly to the vshiftu intrinsic.
4409   if (N->getOpcode() == ISD::SHL)
4410     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4411                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4412                        N->getOperand(0), N->getOperand(1));
4413
4414   assert((N->getOpcode() == ISD::SRA ||
4415           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4416
4417   // NEON uses the same intrinsics for both left and right shifts.  For
4418   // right shifts, the shift amounts are negative, so negate the vector of
4419   // shift amounts.
4420   EVT ShiftVT = N->getOperand(1).getValueType();
4421   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4422                                      getZeroVector(ShiftVT, DAG, dl),
4423                                      N->getOperand(1));
4424   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4425                              Intrinsic::arm_neon_vshifts :
4426                              Intrinsic::arm_neon_vshiftu);
4427   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4428                      DAG.getConstant(vshiftInt, MVT::i32),
4429                      N->getOperand(0), NegatedCount);
4430 }
4431
4432 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4433                                 const ARMSubtarget *ST) {
4434   EVT VT = N->getValueType(0);
4435   SDLoc dl(N);
4436
4437   // We can get here for a node like i32 = ISD::SHL i32, i64
4438   if (VT != MVT::i64)
4439     return SDValue();
4440
4441   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4442          "Unknown shift to lower!");
4443
4444   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4445   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4446       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4447     return SDValue();
4448
4449   // If we are in thumb mode, we don't have RRX.
4450   if (ST->isThumb1Only()) return SDValue();
4451
4452   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4453   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4454                            DAG.getConstant(0, MVT::i32));
4455   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4456                            DAG.getConstant(1, MVT::i32));
4457
4458   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4459   // captures the result into a carry flag.
4460   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4461   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4462
4463   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4464   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4465
4466   // Merge the pieces into a single i64 value.
4467  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4468 }
4469
4470 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4471   SDValue TmpOp0, TmpOp1;
4472   bool Invert = false;
4473   bool Swap = false;
4474   unsigned Opc = 0;
4475
4476   SDValue Op0 = Op.getOperand(0);
4477   SDValue Op1 = Op.getOperand(1);
4478   SDValue CC = Op.getOperand(2);
4479   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4480   EVT VT = Op.getValueType();
4481   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4482   SDLoc dl(Op);
4483
4484   if (Op1.getValueType().isFloatingPoint()) {
4485     switch (SetCCOpcode) {
4486     default: llvm_unreachable("Illegal FP comparison");
4487     case ISD::SETUNE:
4488     case ISD::SETNE:  Invert = true; // Fallthrough
4489     case ISD::SETOEQ:
4490     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4491     case ISD::SETOLT:
4492     case ISD::SETLT: Swap = true; // Fallthrough
4493     case ISD::SETOGT:
4494     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4495     case ISD::SETOLE:
4496     case ISD::SETLE:  Swap = true; // Fallthrough
4497     case ISD::SETOGE:
4498     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4499     case ISD::SETUGE: Swap = true; // Fallthrough
4500     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4501     case ISD::SETUGT: Swap = true; // Fallthrough
4502     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4503     case ISD::SETUEQ: Invert = true; // Fallthrough
4504     case ISD::SETONE:
4505       // Expand this to (OLT | OGT).
4506       TmpOp0 = Op0;
4507       TmpOp1 = Op1;
4508       Opc = ISD::OR;
4509       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4510       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4511       break;
4512     case ISD::SETUO: Invert = true; // Fallthrough
4513     case ISD::SETO:
4514       // Expand this to (OLT | OGE).
4515       TmpOp0 = Op0;
4516       TmpOp1 = Op1;
4517       Opc = ISD::OR;
4518       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4519       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4520       break;
4521     }
4522   } else {
4523     // Integer comparisons.
4524     switch (SetCCOpcode) {
4525     default: llvm_unreachable("Illegal integer comparison");
4526     case ISD::SETNE:  Invert = true;
4527     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4528     case ISD::SETLT:  Swap = true;
4529     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4530     case ISD::SETLE:  Swap = true;
4531     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4532     case ISD::SETULT: Swap = true;
4533     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4534     case ISD::SETULE: Swap = true;
4535     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4536     }
4537
4538     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4539     if (Opc == ARMISD::VCEQ) {
4540
4541       SDValue AndOp;
4542       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4543         AndOp = Op0;
4544       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4545         AndOp = Op1;
4546
4547       // Ignore bitconvert.
4548       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4549         AndOp = AndOp.getOperand(0);
4550
4551       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4552         Opc = ARMISD::VTST;
4553         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4554         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4555         Invert = !Invert;
4556       }
4557     }
4558   }
4559
4560   if (Swap)
4561     std::swap(Op0, Op1);
4562
4563   // If one of the operands is a constant vector zero, attempt to fold the
4564   // comparison to a specialized compare-against-zero form.
4565   SDValue SingleOp;
4566   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4567     SingleOp = Op0;
4568   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4569     if (Opc == ARMISD::VCGE)
4570       Opc = ARMISD::VCLEZ;
4571     else if (Opc == ARMISD::VCGT)
4572       Opc = ARMISD::VCLTZ;
4573     SingleOp = Op1;
4574   }
4575
4576   SDValue Result;
4577   if (SingleOp.getNode()) {
4578     switch (Opc) {
4579     case ARMISD::VCEQ:
4580       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4581     case ARMISD::VCGE:
4582       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4583     case ARMISD::VCLEZ:
4584       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4585     case ARMISD::VCGT:
4586       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4587     case ARMISD::VCLTZ:
4588       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4589     default:
4590       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4591     }
4592   } else {
4593      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4594   }
4595
4596   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4597
4598   if (Invert)
4599     Result = DAG.getNOT(dl, Result, VT);
4600
4601   return Result;
4602 }
4603
4604 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4605 /// valid vector constant for a NEON instruction with a "modified immediate"
4606 /// operand (e.g., VMOV).  If so, return the encoded value.
4607 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4608                                  unsigned SplatBitSize, SelectionDAG &DAG,
4609                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4610   unsigned OpCmode, Imm;
4611
4612   // SplatBitSize is set to the smallest size that splats the vector, so a
4613   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4614   // immediate instructions others than VMOV do not support the 8-bit encoding
4615   // of a zero vector, and the default encoding of zero is supposed to be the
4616   // 32-bit version.
4617   if (SplatBits == 0)
4618     SplatBitSize = 32;
4619
4620   switch (SplatBitSize) {
4621   case 8:
4622     if (type != VMOVModImm)
4623       return SDValue();
4624     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4625     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4626     OpCmode = 0xe;
4627     Imm = SplatBits;
4628     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4629     break;
4630
4631   case 16:
4632     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4633     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4634     if ((SplatBits & ~0xff) == 0) {
4635       // Value = 0x00nn: Op=x, Cmode=100x.
4636       OpCmode = 0x8;
4637       Imm = SplatBits;
4638       break;
4639     }
4640     if ((SplatBits & ~0xff00) == 0) {
4641       // Value = 0xnn00: Op=x, Cmode=101x.
4642       OpCmode = 0xa;
4643       Imm = SplatBits >> 8;
4644       break;
4645     }
4646     return SDValue();
4647
4648   case 32:
4649     // NEON's 32-bit VMOV supports splat values where:
4650     // * only one byte is nonzero, or
4651     // * the least significant byte is 0xff and the second byte is nonzero, or
4652     // * the least significant 2 bytes are 0xff and the third is nonzero.
4653     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4654     if ((SplatBits & ~0xff) == 0) {
4655       // Value = 0x000000nn: Op=x, Cmode=000x.
4656       OpCmode = 0;
4657       Imm = SplatBits;
4658       break;
4659     }
4660     if ((SplatBits & ~0xff00) == 0) {
4661       // Value = 0x0000nn00: Op=x, Cmode=001x.
4662       OpCmode = 0x2;
4663       Imm = SplatBits >> 8;
4664       break;
4665     }
4666     if ((SplatBits & ~0xff0000) == 0) {
4667       // Value = 0x00nn0000: Op=x, Cmode=010x.
4668       OpCmode = 0x4;
4669       Imm = SplatBits >> 16;
4670       break;
4671     }
4672     if ((SplatBits & ~0xff000000) == 0) {
4673       // Value = 0xnn000000: Op=x, Cmode=011x.
4674       OpCmode = 0x6;
4675       Imm = SplatBits >> 24;
4676       break;
4677     }
4678
4679     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4680     if (type == OtherModImm) return SDValue();
4681
4682     if ((SplatBits & ~0xffff) == 0 &&
4683         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4684       // Value = 0x0000nnff: Op=x, Cmode=1100.
4685       OpCmode = 0xc;
4686       Imm = SplatBits >> 8;
4687       break;
4688     }
4689
4690     if ((SplatBits & ~0xffffff) == 0 &&
4691         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4692       // Value = 0x00nnffff: Op=x, Cmode=1101.
4693       OpCmode = 0xd;
4694       Imm = SplatBits >> 16;
4695       break;
4696     }
4697
4698     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4699     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4700     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4701     // and fall through here to test for a valid 64-bit splat.  But, then the
4702     // caller would also need to check and handle the change in size.
4703     return SDValue();
4704
4705   case 64: {
4706     if (type != VMOVModImm)
4707       return SDValue();
4708     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4709     uint64_t BitMask = 0xff;
4710     uint64_t Val = 0;
4711     unsigned ImmMask = 1;
4712     Imm = 0;
4713     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4714       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4715         Val |= BitMask;
4716         Imm |= ImmMask;
4717       } else if ((SplatBits & BitMask) != 0) {
4718         return SDValue();
4719       }
4720       BitMask <<= 8;
4721       ImmMask <<= 1;
4722     }
4723
4724     if (DAG.getTargetLoweringInfo().isBigEndian())
4725       // swap higher and lower 32 bit word
4726       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4727
4728     // Op=1, Cmode=1110.
4729     OpCmode = 0x1e;
4730     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4731     break;
4732   }
4733
4734   default:
4735     llvm_unreachable("unexpected size for isNEONModifiedImm");
4736   }
4737
4738   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4739   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4740 }
4741
4742 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4743                                            const ARMSubtarget *ST) const {
4744   if (!ST->hasVFP3())
4745     return SDValue();
4746
4747   bool IsDouble = Op.getValueType() == MVT::f64;
4748   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4749
4750   // Use the default (constant pool) lowering for double constants when we have
4751   // an SP-only FPU
4752   if (IsDouble && Subtarget->isFPOnlySP())
4753     return SDValue();
4754
4755   // Try splatting with a VMOV.f32...
4756   APFloat FPVal = CFP->getValueAPF();
4757   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4758
4759   if (ImmVal != -1) {
4760     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4761       // We have code in place to select a valid ConstantFP already, no need to
4762       // do any mangling.
4763       return Op;
4764     }
4765
4766     // It's a float and we are trying to use NEON operations where
4767     // possible. Lower it to a splat followed by an extract.
4768     SDLoc DL(Op);
4769     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4770     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4771                                       NewVal);
4772     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4773                        DAG.getConstant(0, MVT::i32));
4774   }
4775
4776   // The rest of our options are NEON only, make sure that's allowed before
4777   // proceeding..
4778   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4779     return SDValue();
4780
4781   EVT VMovVT;
4782   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4783
4784   // It wouldn't really be worth bothering for doubles except for one very
4785   // important value, which does happen to match: 0.0. So make sure we don't do
4786   // anything stupid.
4787   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4788     return SDValue();
4789
4790   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4791   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4792                                      false, VMOVModImm);
4793   if (NewVal != SDValue()) {
4794     SDLoc DL(Op);
4795     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4796                                       NewVal);
4797     if (IsDouble)
4798       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4799
4800     // It's a float: cast and extract a vector element.
4801     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4802                                        VecConstant);
4803     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4804                        DAG.getConstant(0, MVT::i32));
4805   }
4806
4807   // Finally, try a VMVN.i32
4808   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4809                              false, VMVNModImm);
4810   if (NewVal != SDValue()) {
4811     SDLoc DL(Op);
4812     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4813
4814     if (IsDouble)
4815       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4816
4817     // It's a float: cast and extract a vector element.
4818     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4819                                        VecConstant);
4820     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4821                        DAG.getConstant(0, MVT::i32));
4822   }
4823
4824   return SDValue();
4825 }
4826
4827 // check if an VEXT instruction can handle the shuffle mask when the
4828 // vector sources of the shuffle are the same.
4829 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4830   unsigned NumElts = VT.getVectorNumElements();
4831
4832   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4833   if (M[0] < 0)
4834     return false;
4835
4836   Imm = M[0];
4837
4838   // If this is a VEXT shuffle, the immediate value is the index of the first
4839   // element.  The other shuffle indices must be the successive elements after
4840   // the first one.
4841   unsigned ExpectedElt = Imm;
4842   for (unsigned i = 1; i < NumElts; ++i) {
4843     // Increment the expected index.  If it wraps around, just follow it
4844     // back to index zero and keep going.
4845     ++ExpectedElt;
4846     if (ExpectedElt == NumElts)
4847       ExpectedElt = 0;
4848
4849     if (M[i] < 0) continue; // ignore UNDEF indices
4850     if (ExpectedElt != static_cast<unsigned>(M[i]))
4851       return false;
4852   }
4853
4854   return true;
4855 }
4856
4857
4858 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4859                        bool &ReverseVEXT, unsigned &Imm) {
4860   unsigned NumElts = VT.getVectorNumElements();
4861   ReverseVEXT = false;
4862
4863   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4864   if (M[0] < 0)
4865     return false;
4866
4867   Imm = M[0];
4868
4869   // If this is a VEXT shuffle, the immediate value is the index of the first
4870   // element.  The other shuffle indices must be the successive elements after
4871   // the first one.
4872   unsigned ExpectedElt = Imm;
4873   for (unsigned i = 1; i < NumElts; ++i) {
4874     // Increment the expected index.  If it wraps around, it may still be
4875     // a VEXT but the source vectors must be swapped.
4876     ExpectedElt += 1;
4877     if (ExpectedElt == NumElts * 2) {
4878       ExpectedElt = 0;
4879       ReverseVEXT = true;
4880     }
4881
4882     if (M[i] < 0) continue; // ignore UNDEF indices
4883     if (ExpectedElt != static_cast<unsigned>(M[i]))
4884       return false;
4885   }
4886
4887   // Adjust the index value if the source operands will be swapped.
4888   if (ReverseVEXT)
4889     Imm -= NumElts;
4890
4891   return true;
4892 }
4893
4894 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4895 /// instruction with the specified blocksize.  (The order of the elements
4896 /// within each block of the vector is reversed.)
4897 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4898   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4899          "Only possible block sizes for VREV are: 16, 32, 64");
4900
4901   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4902   if (EltSz == 64)
4903     return false;
4904
4905   unsigned NumElts = VT.getVectorNumElements();
4906   unsigned BlockElts = M[0] + 1;
4907   // If the first shuffle index is UNDEF, be optimistic.
4908   if (M[0] < 0)
4909     BlockElts = BlockSize / EltSz;
4910
4911   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4912     return false;
4913
4914   for (unsigned i = 0; i < NumElts; ++i) {
4915     if (M[i] < 0) continue; // ignore UNDEF indices
4916     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4917       return false;
4918   }
4919
4920   return true;
4921 }
4922
4923 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4924   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4925   // range, then 0 is placed into the resulting vector. So pretty much any mask
4926   // of 8 elements can work here.
4927   return VT == MVT::v8i8 && M.size() == 8;
4928 }
4929
4930 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4931   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4932   if (EltSz == 64)
4933     return false;
4934
4935   unsigned NumElts = VT.getVectorNumElements();
4936   WhichResult = (M[0] == 0 ? 0 : 1);
4937   for (unsigned i = 0; i < NumElts; i += 2) {
4938     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4939         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4940       return false;
4941   }
4942   return true;
4943 }
4944
4945 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4946 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4947 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4948 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4949   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4950   if (EltSz == 64)
4951     return false;
4952
4953   unsigned NumElts = VT.getVectorNumElements();
4954   WhichResult = (M[0] == 0 ? 0 : 1);
4955   for (unsigned i = 0; i < NumElts; i += 2) {
4956     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4957         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4958       return false;
4959   }
4960   return true;
4961 }
4962
4963 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4964   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4965   if (EltSz == 64)
4966     return false;
4967
4968   unsigned NumElts = VT.getVectorNumElements();
4969   WhichResult = (M[0] == 0 ? 0 : 1);
4970   for (unsigned i = 0; i != NumElts; ++i) {
4971     if (M[i] < 0) continue; // ignore UNDEF indices
4972     if ((unsigned) M[i] != 2 * i + WhichResult)
4973       return false;
4974   }
4975
4976   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4977   if (VT.is64BitVector() && EltSz == 32)
4978     return false;
4979
4980   return true;
4981 }
4982
4983 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4984 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4985 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4986 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4987   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4988   if (EltSz == 64)
4989     return false;
4990
4991   unsigned Half = VT.getVectorNumElements() / 2;
4992   WhichResult = (M[0] == 0 ? 0 : 1);
4993   for (unsigned j = 0; j != 2; ++j) {
4994     unsigned Idx = WhichResult;
4995     for (unsigned i = 0; i != Half; ++i) {
4996       int MIdx = M[i + j * Half];
4997       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4998         return false;
4999       Idx += 2;
5000     }
5001   }
5002
5003   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5004   if (VT.is64BitVector() && EltSz == 32)
5005     return false;
5006
5007   return true;
5008 }
5009
5010 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5011   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5012   if (EltSz == 64)
5013     return false;
5014
5015   unsigned NumElts = VT.getVectorNumElements();
5016   WhichResult = (M[0] == 0 ? 0 : 1);
5017   unsigned Idx = WhichResult * NumElts / 2;
5018   for (unsigned i = 0; i != NumElts; i += 2) {
5019     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5020         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5021       return false;
5022     Idx += 1;
5023   }
5024
5025   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5026   if (VT.is64BitVector() && EltSz == 32)
5027     return false;
5028
5029   return true;
5030 }
5031
5032 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5033 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5034 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5035 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5036   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5037   if (EltSz == 64)
5038     return false;
5039
5040   unsigned NumElts = VT.getVectorNumElements();
5041   WhichResult = (M[0] == 0 ? 0 : 1);
5042   unsigned Idx = WhichResult * NumElts / 2;
5043   for (unsigned i = 0; i != NumElts; i += 2) {
5044     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5045         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5046       return false;
5047     Idx += 1;
5048   }
5049
5050   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5051   if (VT.is64BitVector() && EltSz == 32)
5052     return false;
5053
5054   return true;
5055 }
5056
5057 /// \return true if this is a reverse operation on an vector.
5058 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5059   unsigned NumElts = VT.getVectorNumElements();
5060   // Make sure the mask has the right size.
5061   if (NumElts != M.size())
5062       return false;
5063
5064   // Look for <15, ..., 3, -1, 1, 0>.
5065   for (unsigned i = 0; i != NumElts; ++i)
5066     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5067       return false;
5068
5069   return true;
5070 }
5071
5072 // If N is an integer constant that can be moved into a register in one
5073 // instruction, return an SDValue of such a constant (will become a MOV
5074 // instruction).  Otherwise return null.
5075 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5076                                      const ARMSubtarget *ST, SDLoc dl) {
5077   uint64_t Val;
5078   if (!isa<ConstantSDNode>(N))
5079     return SDValue();
5080   Val = cast<ConstantSDNode>(N)->getZExtValue();
5081
5082   if (ST->isThumb1Only()) {
5083     if (Val <= 255 || ~Val <= 255)
5084       return DAG.getConstant(Val, MVT::i32);
5085   } else {
5086     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5087       return DAG.getConstant(Val, MVT::i32);
5088   }
5089   return SDValue();
5090 }
5091
5092 // If this is a case we can't handle, return null and let the default
5093 // expansion code take care of it.
5094 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5095                                              const ARMSubtarget *ST) const {
5096   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5097   SDLoc dl(Op);
5098   EVT VT = Op.getValueType();
5099
5100   APInt SplatBits, SplatUndef;
5101   unsigned SplatBitSize;
5102   bool HasAnyUndefs;
5103   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5104     if (SplatBitSize <= 64) {
5105       // Check if an immediate VMOV works.
5106       EVT VmovVT;
5107       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5108                                       SplatUndef.getZExtValue(), SplatBitSize,
5109                                       DAG, VmovVT, VT.is128BitVector(),
5110                                       VMOVModImm);
5111       if (Val.getNode()) {
5112         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5113         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5114       }
5115
5116       // Try an immediate VMVN.
5117       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5118       Val = isNEONModifiedImm(NegatedImm,
5119                                       SplatUndef.getZExtValue(), SplatBitSize,
5120                                       DAG, VmovVT, VT.is128BitVector(),
5121                                       VMVNModImm);
5122       if (Val.getNode()) {
5123         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5124         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5125       }
5126
5127       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5128       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5129         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5130         if (ImmVal != -1) {
5131           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5132           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5133         }
5134       }
5135     }
5136   }
5137
5138   // Scan through the operands to see if only one value is used.
5139   //
5140   // As an optimisation, even if more than one value is used it may be more
5141   // profitable to splat with one value then change some lanes.
5142   //
5143   // Heuristically we decide to do this if the vector has a "dominant" value,
5144   // defined as splatted to more than half of the lanes.
5145   unsigned NumElts = VT.getVectorNumElements();
5146   bool isOnlyLowElement = true;
5147   bool usesOnlyOneValue = true;
5148   bool hasDominantValue = false;
5149   bool isConstant = true;
5150
5151   // Map of the number of times a particular SDValue appears in the
5152   // element list.
5153   DenseMap<SDValue, unsigned> ValueCounts;
5154   SDValue Value;
5155   for (unsigned i = 0; i < NumElts; ++i) {
5156     SDValue V = Op.getOperand(i);
5157     if (V.getOpcode() == ISD::UNDEF)
5158       continue;
5159     if (i > 0)
5160       isOnlyLowElement = false;
5161     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5162       isConstant = false;
5163
5164     ValueCounts.insert(std::make_pair(V, 0));
5165     unsigned &Count = ValueCounts[V];
5166
5167     // Is this value dominant? (takes up more than half of the lanes)
5168     if (++Count > (NumElts / 2)) {
5169       hasDominantValue = true;
5170       Value = V;
5171     }
5172   }
5173   if (ValueCounts.size() != 1)
5174     usesOnlyOneValue = false;
5175   if (!Value.getNode() && ValueCounts.size() > 0)
5176     Value = ValueCounts.begin()->first;
5177
5178   if (ValueCounts.size() == 0)
5179     return DAG.getUNDEF(VT);
5180
5181   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5182   // Keep going if we are hitting this case.
5183   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5184     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5185
5186   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5187
5188   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5189   // i32 and try again.
5190   if (hasDominantValue && EltSize <= 32) {
5191     if (!isConstant) {
5192       SDValue N;
5193
5194       // If we are VDUPing a value that comes directly from a vector, that will
5195       // cause an unnecessary move to and from a GPR, where instead we could
5196       // just use VDUPLANE. We can only do this if the lane being extracted
5197       // is at a constant index, as the VDUP from lane instructions only have
5198       // constant-index forms.
5199       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5200           isa<ConstantSDNode>(Value->getOperand(1))) {
5201         // We need to create a new undef vector to use for the VDUPLANE if the
5202         // size of the vector from which we get the value is different than the
5203         // size of the vector that we need to create. We will insert the element
5204         // such that the register coalescer will remove unnecessary copies.
5205         if (VT != Value->getOperand(0).getValueType()) {
5206           ConstantSDNode *constIndex;
5207           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5208           assert(constIndex && "The index is not a constant!");
5209           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5210                              VT.getVectorNumElements();
5211           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5212                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5213                         Value, DAG.getConstant(index, MVT::i32)),
5214                            DAG.getConstant(index, MVT::i32));
5215         } else
5216           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5217                         Value->getOperand(0), Value->getOperand(1));
5218       } else
5219         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5220
5221       if (!usesOnlyOneValue) {
5222         // The dominant value was splatted as 'N', but we now have to insert
5223         // all differing elements.
5224         for (unsigned I = 0; I < NumElts; ++I) {
5225           if (Op.getOperand(I) == Value)
5226             continue;
5227           SmallVector<SDValue, 3> Ops;
5228           Ops.push_back(N);
5229           Ops.push_back(Op.getOperand(I));
5230           Ops.push_back(DAG.getConstant(I, MVT::i32));
5231           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5232         }
5233       }
5234       return N;
5235     }
5236     if (VT.getVectorElementType().isFloatingPoint()) {
5237       SmallVector<SDValue, 8> Ops;
5238       for (unsigned i = 0; i < NumElts; ++i)
5239         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5240                                   Op.getOperand(i)));
5241       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5242       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5243       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5244       if (Val.getNode())
5245         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5246     }
5247     if (usesOnlyOneValue) {
5248       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5249       if (isConstant && Val.getNode())
5250         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5251     }
5252   }
5253
5254   // If all elements are constants and the case above didn't get hit, fall back
5255   // to the default expansion, which will generate a load from the constant
5256   // pool.
5257   if (isConstant)
5258     return SDValue();
5259
5260   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5261   if (NumElts >= 4) {
5262     SDValue shuffle = ReconstructShuffle(Op, DAG);
5263     if (shuffle != SDValue())
5264       return shuffle;
5265   }
5266
5267   // Vectors with 32- or 64-bit elements can be built by directly assigning
5268   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5269   // will be legalized.
5270   if (EltSize >= 32) {
5271     // Do the expansion with floating-point types, since that is what the VFP
5272     // registers are defined to use, and since i64 is not legal.
5273     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5274     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5275     SmallVector<SDValue, 8> Ops;
5276     for (unsigned i = 0; i < NumElts; ++i)
5277       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5278     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5279     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5280   }
5281
5282   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5283   // know the default expansion would otherwise fall back on something even
5284   // worse. For a vector with one or two non-undef values, that's
5285   // scalar_to_vector for the elements followed by a shuffle (provided the
5286   // shuffle is valid for the target) and materialization element by element
5287   // on the stack followed by a load for everything else.
5288   if (!isConstant && !usesOnlyOneValue) {
5289     SDValue Vec = DAG.getUNDEF(VT);
5290     for (unsigned i = 0 ; i < NumElts; ++i) {
5291       SDValue V = Op.getOperand(i);
5292       if (V.getOpcode() == ISD::UNDEF)
5293         continue;
5294       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5295       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5296     }
5297     return Vec;
5298   }
5299
5300   return SDValue();
5301 }
5302
5303 // Gather data to see if the operation can be modelled as a
5304 // shuffle in combination with VEXTs.
5305 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5306                                               SelectionDAG &DAG) const {
5307   SDLoc dl(Op);
5308   EVT VT = Op.getValueType();
5309   unsigned NumElts = VT.getVectorNumElements();
5310
5311   SmallVector<SDValue, 2> SourceVecs;
5312   SmallVector<unsigned, 2> MinElts;
5313   SmallVector<unsigned, 2> MaxElts;
5314
5315   for (unsigned i = 0; i < NumElts; ++i) {
5316     SDValue V = Op.getOperand(i);
5317     if (V.getOpcode() == ISD::UNDEF)
5318       continue;
5319     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5320       // A shuffle can only come from building a vector from various
5321       // elements of other vectors.
5322       return SDValue();
5323     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5324                VT.getVectorElementType()) {
5325       // This code doesn't know how to handle shuffles where the vector
5326       // element types do not match (this happens because type legalization
5327       // promotes the return type of EXTRACT_VECTOR_ELT).
5328       // FIXME: It might be appropriate to extend this code to handle
5329       // mismatched types.
5330       return SDValue();
5331     }
5332
5333     // Record this extraction against the appropriate vector if possible...
5334     SDValue SourceVec = V.getOperand(0);
5335     // If the element number isn't a constant, we can't effectively
5336     // analyze what's going on.
5337     if (!isa<ConstantSDNode>(V.getOperand(1)))
5338       return SDValue();
5339     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5340     bool FoundSource = false;
5341     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5342       if (SourceVecs[j] == SourceVec) {
5343         if (MinElts[j] > EltNo)
5344           MinElts[j] = EltNo;
5345         if (MaxElts[j] < EltNo)
5346           MaxElts[j] = EltNo;
5347         FoundSource = true;
5348         break;
5349       }
5350     }
5351
5352     // Or record a new source if not...
5353     if (!FoundSource) {
5354       SourceVecs.push_back(SourceVec);
5355       MinElts.push_back(EltNo);
5356       MaxElts.push_back(EltNo);
5357     }
5358   }
5359
5360   // Currently only do something sane when at most two source vectors
5361   // involved.
5362   if (SourceVecs.size() > 2)
5363     return SDValue();
5364
5365   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5366   int VEXTOffsets[2] = {0, 0};
5367
5368   // This loop extracts the usage patterns of the source vectors
5369   // and prepares appropriate SDValues for a shuffle if possible.
5370   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5371     if (SourceVecs[i].getValueType() == VT) {
5372       // No VEXT necessary
5373       ShuffleSrcs[i] = SourceVecs[i];
5374       VEXTOffsets[i] = 0;
5375       continue;
5376     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5377       // It probably isn't worth padding out a smaller vector just to
5378       // break it down again in a shuffle.
5379       return SDValue();
5380     }
5381
5382     // Since only 64-bit and 128-bit vectors are legal on ARM and
5383     // we've eliminated the other cases...
5384     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5385            "unexpected vector sizes in ReconstructShuffle");
5386
5387     if (MaxElts[i] - MinElts[i] >= NumElts) {
5388       // Span too large for a VEXT to cope
5389       return SDValue();
5390     }
5391
5392     if (MinElts[i] >= NumElts) {
5393       // The extraction can just take the second half
5394       VEXTOffsets[i] = NumElts;
5395       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5396                                    SourceVecs[i],
5397                                    DAG.getIntPtrConstant(NumElts));
5398     } else if (MaxElts[i] < NumElts) {
5399       // The extraction can just take the first half
5400       VEXTOffsets[i] = 0;
5401       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5402                                    SourceVecs[i],
5403                                    DAG.getIntPtrConstant(0));
5404     } else {
5405       // An actual VEXT is needed
5406       VEXTOffsets[i] = MinElts[i];
5407       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5408                                      SourceVecs[i],
5409                                      DAG.getIntPtrConstant(0));
5410       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5411                                      SourceVecs[i],
5412                                      DAG.getIntPtrConstant(NumElts));
5413       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5414                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5415     }
5416   }
5417
5418   SmallVector<int, 8> Mask;
5419
5420   for (unsigned i = 0; i < NumElts; ++i) {
5421     SDValue Entry = Op.getOperand(i);
5422     if (Entry.getOpcode() == ISD::UNDEF) {
5423       Mask.push_back(-1);
5424       continue;
5425     }
5426
5427     SDValue ExtractVec = Entry.getOperand(0);
5428     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5429                                           .getOperand(1))->getSExtValue();
5430     if (ExtractVec == SourceVecs[0]) {
5431       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5432     } else {
5433       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5434     }
5435   }
5436
5437   // Final check before we try to produce nonsense...
5438   if (isShuffleMaskLegal(Mask, VT))
5439     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5440                                 &Mask[0]);
5441
5442   return SDValue();
5443 }
5444
5445 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5446 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5447 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5448 /// are assumed to be legal.
5449 bool
5450 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5451                                       EVT VT) const {
5452   if (VT.getVectorNumElements() == 4 &&
5453       (VT.is128BitVector() || VT.is64BitVector())) {
5454     unsigned PFIndexes[4];
5455     for (unsigned i = 0; i != 4; ++i) {
5456       if (M[i] < 0)
5457         PFIndexes[i] = 8;
5458       else
5459         PFIndexes[i] = M[i];
5460     }
5461
5462     // Compute the index in the perfect shuffle table.
5463     unsigned PFTableIndex =
5464       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5465     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5466     unsigned Cost = (PFEntry >> 30);
5467
5468     if (Cost <= 4)
5469       return true;
5470   }
5471
5472   bool ReverseVEXT;
5473   unsigned Imm, WhichResult;
5474
5475   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5476   return (EltSize >= 32 ||
5477           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5478           isVREVMask(M, VT, 64) ||
5479           isVREVMask(M, VT, 32) ||
5480           isVREVMask(M, VT, 16) ||
5481           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5482           isVTBLMask(M, VT) ||
5483           isVTRNMask(M, VT, WhichResult) ||
5484           isVUZPMask(M, VT, WhichResult) ||
5485           isVZIPMask(M, VT, WhichResult) ||
5486           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5487           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5488           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5489           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5490 }
5491
5492 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5493 /// the specified operations to build the shuffle.
5494 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5495                                       SDValue RHS, SelectionDAG &DAG,
5496                                       SDLoc dl) {
5497   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5498   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5499   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5500
5501   enum {
5502     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5503     OP_VREV,
5504     OP_VDUP0,
5505     OP_VDUP1,
5506     OP_VDUP2,
5507     OP_VDUP3,
5508     OP_VEXT1,
5509     OP_VEXT2,
5510     OP_VEXT3,
5511     OP_VUZPL, // VUZP, left result
5512     OP_VUZPR, // VUZP, right result
5513     OP_VZIPL, // VZIP, left result
5514     OP_VZIPR, // VZIP, right result
5515     OP_VTRNL, // VTRN, left result
5516     OP_VTRNR  // VTRN, right result
5517   };
5518
5519   if (OpNum == OP_COPY) {
5520     if (LHSID == (1*9+2)*9+3) return LHS;
5521     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5522     return RHS;
5523   }
5524
5525   SDValue OpLHS, OpRHS;
5526   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5527   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5528   EVT VT = OpLHS.getValueType();
5529
5530   switch (OpNum) {
5531   default: llvm_unreachable("Unknown shuffle opcode!");
5532   case OP_VREV:
5533     // VREV divides the vector in half and swaps within the half.
5534     if (VT.getVectorElementType() == MVT::i32 ||
5535         VT.getVectorElementType() == MVT::f32)
5536       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5537     // vrev <4 x i16> -> VREV32
5538     if (VT.getVectorElementType() == MVT::i16)
5539       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5540     // vrev <4 x i8> -> VREV16
5541     assert(VT.getVectorElementType() == MVT::i8);
5542     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5543   case OP_VDUP0:
5544   case OP_VDUP1:
5545   case OP_VDUP2:
5546   case OP_VDUP3:
5547     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5548                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5549   case OP_VEXT1:
5550   case OP_VEXT2:
5551   case OP_VEXT3:
5552     return DAG.getNode(ARMISD::VEXT, dl, VT,
5553                        OpLHS, OpRHS,
5554                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5555   case OP_VUZPL:
5556   case OP_VUZPR:
5557     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5558                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5559   case OP_VZIPL:
5560   case OP_VZIPR:
5561     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5562                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5563   case OP_VTRNL:
5564   case OP_VTRNR:
5565     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5566                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5567   }
5568 }
5569
5570 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5571                                        ArrayRef<int> ShuffleMask,
5572                                        SelectionDAG &DAG) {
5573   // Check to see if we can use the VTBL instruction.
5574   SDValue V1 = Op.getOperand(0);
5575   SDValue V2 = Op.getOperand(1);
5576   SDLoc DL(Op);
5577
5578   SmallVector<SDValue, 8> VTBLMask;
5579   for (ArrayRef<int>::iterator
5580          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5581     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5582
5583   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5584     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5585                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5586
5587   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5588                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5589 }
5590
5591 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5592                                                       SelectionDAG &DAG) {
5593   SDLoc DL(Op);
5594   SDValue OpLHS = Op.getOperand(0);
5595   EVT VT = OpLHS.getValueType();
5596
5597   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5598          "Expect an v8i16/v16i8 type");
5599   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5600   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5601   // extract the first 8 bytes into the top double word and the last 8 bytes
5602   // into the bottom double word. The v8i16 case is similar.
5603   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5604   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5605                      DAG.getConstant(ExtractNum, MVT::i32));
5606 }
5607
5608 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5609   SDValue V1 = Op.getOperand(0);
5610   SDValue V2 = Op.getOperand(1);
5611   SDLoc dl(Op);
5612   EVT VT = Op.getValueType();
5613   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5614
5615   // Convert shuffles that are directly supported on NEON to target-specific
5616   // DAG nodes, instead of keeping them as shuffles and matching them again
5617   // during code selection.  This is more efficient and avoids the possibility
5618   // of inconsistencies between legalization and selection.
5619   // FIXME: floating-point vectors should be canonicalized to integer vectors
5620   // of the same time so that they get CSEd properly.
5621   ArrayRef<int> ShuffleMask = SVN->getMask();
5622
5623   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5624   if (EltSize <= 32) {
5625     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5626       int Lane = SVN->getSplatIndex();
5627       // If this is undef splat, generate it via "just" vdup, if possible.
5628       if (Lane == -1) Lane = 0;
5629
5630       // Test if V1 is a SCALAR_TO_VECTOR.
5631       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5632         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5633       }
5634       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5635       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5636       // reaches it).
5637       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5638           !isa<ConstantSDNode>(V1.getOperand(0))) {
5639         bool IsScalarToVector = true;
5640         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5641           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5642             IsScalarToVector = false;
5643             break;
5644           }
5645         if (IsScalarToVector)
5646           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5647       }
5648       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5649                          DAG.getConstant(Lane, MVT::i32));
5650     }
5651
5652     bool ReverseVEXT;
5653     unsigned Imm;
5654     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5655       if (ReverseVEXT)
5656         std::swap(V1, V2);
5657       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5658                          DAG.getConstant(Imm, MVT::i32));
5659     }
5660
5661     if (isVREVMask(ShuffleMask, VT, 64))
5662       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5663     if (isVREVMask(ShuffleMask, VT, 32))
5664       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5665     if (isVREVMask(ShuffleMask, VT, 16))
5666       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5667
5668     if (V2->getOpcode() == ISD::UNDEF &&
5669         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5670       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5671                          DAG.getConstant(Imm, MVT::i32));
5672     }
5673
5674     // Check for Neon shuffles that modify both input vectors in place.
5675     // If both results are used, i.e., if there are two shuffles with the same
5676     // source operands and with masks corresponding to both results of one of
5677     // these operations, DAG memoization will ensure that a single node is
5678     // used for both shuffles.
5679     unsigned WhichResult;
5680     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5681       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5682                          V1, V2).getValue(WhichResult);
5683     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5684       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5685                          V1, V2).getValue(WhichResult);
5686     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5687       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5688                          V1, V2).getValue(WhichResult);
5689
5690     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5691       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5692                          V1, V1).getValue(WhichResult);
5693     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5694       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5695                          V1, V1).getValue(WhichResult);
5696     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5697       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5698                          V1, V1).getValue(WhichResult);
5699   }
5700
5701   // If the shuffle is not directly supported and it has 4 elements, use
5702   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5703   unsigned NumElts = VT.getVectorNumElements();
5704   if (NumElts == 4) {
5705     unsigned PFIndexes[4];
5706     for (unsigned i = 0; i != 4; ++i) {
5707       if (ShuffleMask[i] < 0)
5708         PFIndexes[i] = 8;
5709       else
5710         PFIndexes[i] = ShuffleMask[i];
5711     }
5712
5713     // Compute the index in the perfect shuffle table.
5714     unsigned PFTableIndex =
5715       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5716     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5717     unsigned Cost = (PFEntry >> 30);
5718
5719     if (Cost <= 4)
5720       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5721   }
5722
5723   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5724   if (EltSize >= 32) {
5725     // Do the expansion with floating-point types, since that is what the VFP
5726     // registers are defined to use, and since i64 is not legal.
5727     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5728     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5729     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5730     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5731     SmallVector<SDValue, 8> Ops;
5732     for (unsigned i = 0; i < NumElts; ++i) {
5733       if (ShuffleMask[i] < 0)
5734         Ops.push_back(DAG.getUNDEF(EltVT));
5735       else
5736         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5737                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5738                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5739                                                   MVT::i32)));
5740     }
5741     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5742     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5743   }
5744
5745   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5746     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5747
5748   if (VT == MVT::v8i8) {
5749     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5750     if (NewOp.getNode())
5751       return NewOp;
5752   }
5753
5754   return SDValue();
5755 }
5756
5757 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5758   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5759   SDValue Lane = Op.getOperand(2);
5760   if (!isa<ConstantSDNode>(Lane))
5761     return SDValue();
5762
5763   return Op;
5764 }
5765
5766 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5767   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5768   SDValue Lane = Op.getOperand(1);
5769   if (!isa<ConstantSDNode>(Lane))
5770     return SDValue();
5771
5772   SDValue Vec = Op.getOperand(0);
5773   if (Op.getValueType() == MVT::i32 &&
5774       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5775     SDLoc dl(Op);
5776     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5777   }
5778
5779   return Op;
5780 }
5781
5782 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5783   // The only time a CONCAT_VECTORS operation can have legal types is when
5784   // two 64-bit vectors are concatenated to a 128-bit vector.
5785   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5786          "unexpected CONCAT_VECTORS");
5787   SDLoc dl(Op);
5788   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5789   SDValue Op0 = Op.getOperand(0);
5790   SDValue Op1 = Op.getOperand(1);
5791   if (Op0.getOpcode() != ISD::UNDEF)
5792     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5793                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5794                       DAG.getIntPtrConstant(0));
5795   if (Op1.getOpcode() != ISD::UNDEF)
5796     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5797                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5798                       DAG.getIntPtrConstant(1));
5799   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5800 }
5801
5802 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5803 /// element has been zero/sign-extended, depending on the isSigned parameter,
5804 /// from an integer type half its size.
5805 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5806                                    bool isSigned) {
5807   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5808   EVT VT = N->getValueType(0);
5809   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5810     SDNode *BVN = N->getOperand(0).getNode();
5811     if (BVN->getValueType(0) != MVT::v4i32 ||
5812         BVN->getOpcode() != ISD::BUILD_VECTOR)
5813       return false;
5814     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5815     unsigned HiElt = 1 - LoElt;
5816     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5817     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5818     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5819     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5820     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5821       return false;
5822     if (isSigned) {
5823       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5824           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5825         return true;
5826     } else {
5827       if (Hi0->isNullValue() && Hi1->isNullValue())
5828         return true;
5829     }
5830     return false;
5831   }
5832
5833   if (N->getOpcode() != ISD::BUILD_VECTOR)
5834     return false;
5835
5836   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5837     SDNode *Elt = N->getOperand(i).getNode();
5838     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5839       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5840       unsigned HalfSize = EltSize / 2;
5841       if (isSigned) {
5842         if (!isIntN(HalfSize, C->getSExtValue()))
5843           return false;
5844       } else {
5845         if (!isUIntN(HalfSize, C->getZExtValue()))
5846           return false;
5847       }
5848       continue;
5849     }
5850     return false;
5851   }
5852
5853   return true;
5854 }
5855
5856 /// isSignExtended - Check if a node is a vector value that is sign-extended
5857 /// or a constant BUILD_VECTOR with sign-extended elements.
5858 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5859   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5860     return true;
5861   if (isExtendedBUILD_VECTOR(N, DAG, true))
5862     return true;
5863   return false;
5864 }
5865
5866 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5867 /// or a constant BUILD_VECTOR with zero-extended elements.
5868 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5869   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5870     return true;
5871   if (isExtendedBUILD_VECTOR(N, DAG, false))
5872     return true;
5873   return false;
5874 }
5875
5876 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5877   if (OrigVT.getSizeInBits() >= 64)
5878     return OrigVT;
5879
5880   assert(OrigVT.isSimple() && "Expecting a simple value type");
5881
5882   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5883   switch (OrigSimpleTy) {
5884   default: llvm_unreachable("Unexpected Vector Type");
5885   case MVT::v2i8:
5886   case MVT::v2i16:
5887      return MVT::v2i32;
5888   case MVT::v4i8:
5889     return  MVT::v4i16;
5890   }
5891 }
5892
5893 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5894 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5895 /// We insert the required extension here to get the vector to fill a D register.
5896 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5897                                             const EVT &OrigTy,
5898                                             const EVT &ExtTy,
5899                                             unsigned ExtOpcode) {
5900   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5901   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5902   // 64-bits we need to insert a new extension so that it will be 64-bits.
5903   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5904   if (OrigTy.getSizeInBits() >= 64)
5905     return N;
5906
5907   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5908   EVT NewVT = getExtensionTo64Bits(OrigTy);
5909
5910   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5911 }
5912
5913 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5914 /// does not do any sign/zero extension. If the original vector is less
5915 /// than 64 bits, an appropriate extension will be added after the load to
5916 /// reach a total size of 64 bits. We have to add the extension separately
5917 /// because ARM does not have a sign/zero extending load for vectors.
5918 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5919   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5920
5921   // The load already has the right type.
5922   if (ExtendedTy == LD->getMemoryVT())
5923     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5924                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5925                 LD->isNonTemporal(), LD->isInvariant(),
5926                 LD->getAlignment());
5927
5928   // We need to create a zextload/sextload. We cannot just create a load
5929   // followed by a zext/zext node because LowerMUL is also run during normal
5930   // operation legalization where we can't create illegal types.
5931   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5932                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5933                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5934                         LD->isNonTemporal(), LD->getAlignment());
5935 }
5936
5937 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5938 /// extending load, or BUILD_VECTOR with extended elements, return the
5939 /// unextended value. The unextended vector should be 64 bits so that it can
5940 /// be used as an operand to a VMULL instruction. If the original vector size
5941 /// before extension is less than 64 bits we add a an extension to resize
5942 /// the vector to 64 bits.
5943 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5944   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5945     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5946                                         N->getOperand(0)->getValueType(0),
5947                                         N->getValueType(0),
5948                                         N->getOpcode());
5949
5950   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5951     return SkipLoadExtensionForVMULL(LD, DAG);
5952
5953   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5954   // have been legalized as a BITCAST from v4i32.
5955   if (N->getOpcode() == ISD::BITCAST) {
5956     SDNode *BVN = N->getOperand(0).getNode();
5957     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5958            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5959     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5960     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5961                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5962   }
5963   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5964   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5965   EVT VT = N->getValueType(0);
5966   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5967   unsigned NumElts = VT.getVectorNumElements();
5968   MVT TruncVT = MVT::getIntegerVT(EltSize);
5969   SmallVector<SDValue, 8> Ops;
5970   for (unsigned i = 0; i != NumElts; ++i) {
5971     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5972     const APInt &CInt = C->getAPIntValue();
5973     // Element types smaller than 32 bits are not legal, so use i32 elements.
5974     // The values are implicitly truncated so sext vs. zext doesn't matter.
5975     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5976   }
5977   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5978                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5979 }
5980
5981 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5982   unsigned Opcode = N->getOpcode();
5983   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5984     SDNode *N0 = N->getOperand(0).getNode();
5985     SDNode *N1 = N->getOperand(1).getNode();
5986     return N0->hasOneUse() && N1->hasOneUse() &&
5987       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5988   }
5989   return false;
5990 }
5991
5992 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5993   unsigned Opcode = N->getOpcode();
5994   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5995     SDNode *N0 = N->getOperand(0).getNode();
5996     SDNode *N1 = N->getOperand(1).getNode();
5997     return N0->hasOneUse() && N1->hasOneUse() &&
5998       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5999   }
6000   return false;
6001 }
6002
6003 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6004   // Multiplications are only custom-lowered for 128-bit vectors so that
6005   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6006   EVT VT = Op.getValueType();
6007   assert(VT.is128BitVector() && VT.isInteger() &&
6008          "unexpected type for custom-lowering ISD::MUL");
6009   SDNode *N0 = Op.getOperand(0).getNode();
6010   SDNode *N1 = Op.getOperand(1).getNode();
6011   unsigned NewOpc = 0;
6012   bool isMLA = false;
6013   bool isN0SExt = isSignExtended(N0, DAG);
6014   bool isN1SExt = isSignExtended(N1, DAG);
6015   if (isN0SExt && isN1SExt)
6016     NewOpc = ARMISD::VMULLs;
6017   else {
6018     bool isN0ZExt = isZeroExtended(N0, DAG);
6019     bool isN1ZExt = isZeroExtended(N1, DAG);
6020     if (isN0ZExt && isN1ZExt)
6021       NewOpc = ARMISD::VMULLu;
6022     else if (isN1SExt || isN1ZExt) {
6023       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6024       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6025       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6026         NewOpc = ARMISD::VMULLs;
6027         isMLA = true;
6028       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6029         NewOpc = ARMISD::VMULLu;
6030         isMLA = true;
6031       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6032         std::swap(N0, N1);
6033         NewOpc = ARMISD::VMULLu;
6034         isMLA = true;
6035       }
6036     }
6037
6038     if (!NewOpc) {
6039       if (VT == MVT::v2i64)
6040         // Fall through to expand this.  It is not legal.
6041         return SDValue();
6042       else
6043         // Other vector multiplications are legal.
6044         return Op;
6045     }
6046   }
6047
6048   // Legalize to a VMULL instruction.
6049   SDLoc DL(Op);
6050   SDValue Op0;
6051   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6052   if (!isMLA) {
6053     Op0 = SkipExtensionForVMULL(N0, DAG);
6054     assert(Op0.getValueType().is64BitVector() &&
6055            Op1.getValueType().is64BitVector() &&
6056            "unexpected types for extended operands to VMULL");
6057     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6058   }
6059
6060   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6061   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6062   //   vmull q0, d4, d6
6063   //   vmlal q0, d5, d6
6064   // is faster than
6065   //   vaddl q0, d4, d5
6066   //   vmovl q1, d6
6067   //   vmul  q0, q0, q1
6068   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6069   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6070   EVT Op1VT = Op1.getValueType();
6071   return DAG.getNode(N0->getOpcode(), DL, VT,
6072                      DAG.getNode(NewOpc, DL, VT,
6073                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6074                      DAG.getNode(NewOpc, DL, VT,
6075                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6076 }
6077
6078 static SDValue
6079 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6080   // Convert to float
6081   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6082   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6083   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6084   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6085   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6086   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6087   // Get reciprocal estimate.
6088   // float4 recip = vrecpeq_f32(yf);
6089   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6090                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
6091   // Because char has a smaller range than uchar, we can actually get away
6092   // without any newton steps.  This requires that we use a weird bias
6093   // of 0xb000, however (again, this has been exhaustively tested).
6094   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6095   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6096   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6097   Y = DAG.getConstant(0xb000, MVT::i32);
6098   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6099   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6100   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6101   // Convert back to short.
6102   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6103   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6104   return X;
6105 }
6106
6107 static SDValue
6108 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6109   SDValue N2;
6110   // Convert to float.
6111   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6112   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6113   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6114   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6115   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6116   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6117
6118   // Use reciprocal estimate and one refinement step.
6119   // float4 recip = vrecpeq_f32(yf);
6120   // recip *= vrecpsq_f32(yf, recip);
6121   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6122                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6123   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6124                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6125                    N1, N2);
6126   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6127   // Because short has a smaller range than ushort, we can actually get away
6128   // with only a single newton step.  This requires that we use a weird bias
6129   // of 89, however (again, this has been exhaustively tested).
6130   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6131   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6132   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6133   N1 = DAG.getConstant(0x89, MVT::i32);
6134   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6135   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6136   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6137   // Convert back to integer and return.
6138   // return vmovn_s32(vcvt_s32_f32(result));
6139   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6140   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6141   return N0;
6142 }
6143
6144 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6145   EVT VT = Op.getValueType();
6146   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6147          "unexpected type for custom-lowering ISD::SDIV");
6148
6149   SDLoc dl(Op);
6150   SDValue N0 = Op.getOperand(0);
6151   SDValue N1 = Op.getOperand(1);
6152   SDValue N2, N3;
6153
6154   if (VT == MVT::v8i8) {
6155     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6156     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6157
6158     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6159                      DAG.getIntPtrConstant(4));
6160     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6161                      DAG.getIntPtrConstant(4));
6162     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6163                      DAG.getIntPtrConstant(0));
6164     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6165                      DAG.getIntPtrConstant(0));
6166
6167     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6168     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6169
6170     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6171     N0 = LowerCONCAT_VECTORS(N0, DAG);
6172
6173     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6174     return N0;
6175   }
6176   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6177 }
6178
6179 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6180   EVT VT = Op.getValueType();
6181   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6182          "unexpected type for custom-lowering ISD::UDIV");
6183
6184   SDLoc dl(Op);
6185   SDValue N0 = Op.getOperand(0);
6186   SDValue N1 = Op.getOperand(1);
6187   SDValue N2, N3;
6188
6189   if (VT == MVT::v8i8) {
6190     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6191     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6192
6193     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6194                      DAG.getIntPtrConstant(4));
6195     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6196                      DAG.getIntPtrConstant(4));
6197     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6198                      DAG.getIntPtrConstant(0));
6199     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6200                      DAG.getIntPtrConstant(0));
6201
6202     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6203     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6204
6205     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6206     N0 = LowerCONCAT_VECTORS(N0, DAG);
6207
6208     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6209                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6210                      N0);
6211     return N0;
6212   }
6213
6214   // v4i16 sdiv ... Convert to float.
6215   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6216   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6217   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6218   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6219   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6220   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6221
6222   // Use reciprocal estimate and two refinement steps.
6223   // float4 recip = vrecpeq_f32(yf);
6224   // recip *= vrecpsq_f32(yf, recip);
6225   // recip *= vrecpsq_f32(yf, recip);
6226   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6227                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6228   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6229                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6230                    BN1, N2);
6231   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6232   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6233                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6234                    BN1, N2);
6235   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6236   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6237   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6238   // and that it will never cause us to return an answer too large).
6239   // float4 result = as_float4(as_int4(xf*recip) + 2);
6240   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6241   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6242   N1 = DAG.getConstant(2, MVT::i32);
6243   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6244   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6245   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6246   // Convert back to integer and return.
6247   // return vmovn_u32(vcvt_s32_f32(result));
6248   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6249   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6250   return N0;
6251 }
6252
6253 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6254   EVT VT = Op.getNode()->getValueType(0);
6255   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6256
6257   unsigned Opc;
6258   bool ExtraOp = false;
6259   switch (Op.getOpcode()) {
6260   default: llvm_unreachable("Invalid code");
6261   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6262   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6263   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6264   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6265   }
6266
6267   if (!ExtraOp)
6268     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6269                        Op.getOperand(1));
6270   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6271                      Op.getOperand(1), Op.getOperand(2));
6272 }
6273
6274 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6275   assert(Subtarget->isTargetDarwin());
6276
6277   // For iOS, we want to call an alternative entry point: __sincos_stret,
6278   // return values are passed via sret.
6279   SDLoc dl(Op);
6280   SDValue Arg = Op.getOperand(0);
6281   EVT ArgVT = Arg.getValueType();
6282   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6283
6284   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6285   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6286
6287   // Pair of floats / doubles used to pass the result.
6288   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6289
6290   // Create stack object for sret.
6291   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6292   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6293   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6294   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6295
6296   ArgListTy Args;
6297   ArgListEntry Entry;
6298
6299   Entry.Node = SRet;
6300   Entry.Ty = RetTy->getPointerTo();
6301   Entry.isSExt = false;
6302   Entry.isZExt = false;
6303   Entry.isSRet = true;
6304   Args.push_back(Entry);
6305
6306   Entry.Node = Arg;
6307   Entry.Ty = ArgTy;
6308   Entry.isSExt = false;
6309   Entry.isZExt = false;
6310   Args.push_back(Entry);
6311
6312   const char *LibcallName  = (ArgVT == MVT::f64)
6313   ? "__sincos_stret" : "__sincosf_stret";
6314   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6315
6316   TargetLowering::CallLoweringInfo CLI(DAG);
6317   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6318     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6319                std::move(Args), 0)
6320     .setDiscardResult();
6321
6322   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6323
6324   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6325                                 MachinePointerInfo(), false, false, false, 0);
6326
6327   // Address of cos field.
6328   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6329                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6330   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6331                                 MachinePointerInfo(), false, false, false, 0);
6332
6333   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6334   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6335                      LoadSin.getValue(0), LoadCos.getValue(0));
6336 }
6337
6338 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6339   // Monotonic load/store is legal for all targets
6340   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6341     return Op;
6342
6343   // Acquire/Release load/store is not legal for targets without a
6344   // dmb or equivalent available.
6345   return SDValue();
6346 }
6347
6348 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6349                                     SmallVectorImpl<SDValue> &Results,
6350                                     SelectionDAG &DAG,
6351                                     const ARMSubtarget *Subtarget) {
6352   SDLoc DL(N);
6353   SDValue Cycles32, OutChain;
6354
6355   if (Subtarget->hasPerfMon()) {
6356     // Under Power Management extensions, the cycle-count is:
6357     //    mrc p15, #0, <Rt>, c9, c13, #0
6358     SDValue Ops[] = { N->getOperand(0), // Chain
6359                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6360                       DAG.getConstant(15, MVT::i32),
6361                       DAG.getConstant(0, MVT::i32),
6362                       DAG.getConstant(9, MVT::i32),
6363                       DAG.getConstant(13, MVT::i32),
6364                       DAG.getConstant(0, MVT::i32)
6365     };
6366
6367     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6368                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6369     OutChain = Cycles32.getValue(1);
6370   } else {
6371     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6372     // there are older ARM CPUs that have implementation-specific ways of
6373     // obtaining this information (FIXME!).
6374     Cycles32 = DAG.getConstant(0, MVT::i32);
6375     OutChain = DAG.getEntryNode();
6376   }
6377
6378
6379   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6380                                  Cycles32, DAG.getConstant(0, MVT::i32));
6381   Results.push_back(Cycles64);
6382   Results.push_back(OutChain);
6383 }
6384
6385 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6386   switch (Op.getOpcode()) {
6387   default: llvm_unreachable("Don't know how to custom lower this!");
6388   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6389   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6390   case ISD::GlobalAddress:
6391     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6392     default: llvm_unreachable("unknown object format");
6393     case Triple::COFF:
6394       return LowerGlobalAddressWindows(Op, DAG);
6395     case Triple::ELF:
6396       return LowerGlobalAddressELF(Op, DAG);
6397     case Triple::MachO:
6398       return LowerGlobalAddressDarwin(Op, DAG);
6399     }
6400   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6401   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6402   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6403   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6404   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6405   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6406   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6407   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6408   case ISD::SINT_TO_FP:
6409   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6410   case ISD::FP_TO_SINT:
6411   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6412   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6413   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6414   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6415   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6416   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6417   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6418   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6419                                                                Subtarget);
6420   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6421   case ISD::SHL:
6422   case ISD::SRL:
6423   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6424   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6425   case ISD::SRL_PARTS:
6426   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6427   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6428   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6429   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6430   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6431   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6432   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6433   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6434   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6435   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6436   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6437   case ISD::MUL:           return LowerMUL(Op, DAG);
6438   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6439   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6440   case ISD::ADDC:
6441   case ISD::ADDE:
6442   case ISD::SUBC:
6443   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6444   case ISD::SADDO:
6445   case ISD::UADDO:
6446   case ISD::SSUBO:
6447   case ISD::USUBO:
6448     return LowerXALUO(Op, DAG);
6449   case ISD::ATOMIC_LOAD:
6450   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6451   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6452   case ISD::SDIVREM:
6453   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6454   case ISD::DYNAMIC_STACKALLOC:
6455     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6456       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6457     llvm_unreachable("Don't know how to custom lower this!");
6458   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6459   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6460   }
6461 }
6462
6463 /// ReplaceNodeResults - Replace the results of node with an illegal result
6464 /// type with new values built out of custom code.
6465 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6466                                            SmallVectorImpl<SDValue>&Results,
6467                                            SelectionDAG &DAG) const {
6468   SDValue Res;
6469   switch (N->getOpcode()) {
6470   default:
6471     llvm_unreachable("Don't know how to custom expand this!");
6472   case ISD::BITCAST:
6473     Res = ExpandBITCAST(N, DAG);
6474     break;
6475   case ISD::SRL:
6476   case ISD::SRA:
6477     Res = Expand64BitShift(N, DAG, Subtarget);
6478     break;
6479   case ISD::READCYCLECOUNTER:
6480     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6481     return;
6482   }
6483   if (Res.getNode())
6484     Results.push_back(Res);
6485 }
6486
6487 //===----------------------------------------------------------------------===//
6488 //                           ARM Scheduler Hooks
6489 //===----------------------------------------------------------------------===//
6490
6491 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6492 /// registers the function context.
6493 void ARMTargetLowering::
6494 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6495                        MachineBasicBlock *DispatchBB, int FI) const {
6496   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6497   DebugLoc dl = MI->getDebugLoc();
6498   MachineFunction *MF = MBB->getParent();
6499   MachineRegisterInfo *MRI = &MF->getRegInfo();
6500   MachineConstantPool *MCP = MF->getConstantPool();
6501   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6502   const Function *F = MF->getFunction();
6503
6504   bool isThumb = Subtarget->isThumb();
6505   bool isThumb2 = Subtarget->isThumb2();
6506
6507   unsigned PCLabelId = AFI->createPICLabelUId();
6508   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6509   ARMConstantPoolValue *CPV =
6510     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6511   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6512
6513   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6514                                            : &ARM::GPRRegClass;
6515
6516   // Grab constant pool and fixed stack memory operands.
6517   MachineMemOperand *CPMMO =
6518     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6519                              MachineMemOperand::MOLoad, 4, 4);
6520
6521   MachineMemOperand *FIMMOSt =
6522     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6523                              MachineMemOperand::MOStore, 4, 4);
6524
6525   // Load the address of the dispatch MBB into the jump buffer.
6526   if (isThumb2) {
6527     // Incoming value: jbuf
6528     //   ldr.n  r5, LCPI1_1
6529     //   orr    r5, r5, #1
6530     //   add    r5, pc
6531     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6532     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6533     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6534                    .addConstantPoolIndex(CPI)
6535                    .addMemOperand(CPMMO));
6536     // Set the low bit because of thumb mode.
6537     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6538     AddDefaultCC(
6539       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6540                      .addReg(NewVReg1, RegState::Kill)
6541                      .addImm(0x01)));
6542     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6543     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6544       .addReg(NewVReg2, RegState::Kill)
6545       .addImm(PCLabelId);
6546     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6547                    .addReg(NewVReg3, RegState::Kill)
6548                    .addFrameIndex(FI)
6549                    .addImm(36)  // &jbuf[1] :: pc
6550                    .addMemOperand(FIMMOSt));
6551   } else if (isThumb) {
6552     // Incoming value: jbuf
6553     //   ldr.n  r1, LCPI1_4
6554     //   add    r1, pc
6555     //   mov    r2, #1
6556     //   orrs   r1, r2
6557     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6558     //   str    r1, [r2]
6559     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6560     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6561                    .addConstantPoolIndex(CPI)
6562                    .addMemOperand(CPMMO));
6563     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6564     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6565       .addReg(NewVReg1, RegState::Kill)
6566       .addImm(PCLabelId);
6567     // Set the low bit because of thumb mode.
6568     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6569     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6570                    .addReg(ARM::CPSR, RegState::Define)
6571                    .addImm(1));
6572     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6573     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6574                    .addReg(ARM::CPSR, RegState::Define)
6575                    .addReg(NewVReg2, RegState::Kill)
6576                    .addReg(NewVReg3, RegState::Kill));
6577     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6578     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6579             .addFrameIndex(FI)
6580             .addImm(36); // &jbuf[1] :: pc
6581     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6582                    .addReg(NewVReg4, RegState::Kill)
6583                    .addReg(NewVReg5, RegState::Kill)
6584                    .addImm(0)
6585                    .addMemOperand(FIMMOSt));
6586   } else {
6587     // Incoming value: jbuf
6588     //   ldr  r1, LCPI1_1
6589     //   add  r1, pc, r1
6590     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6591     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6592     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6593                    .addConstantPoolIndex(CPI)
6594                    .addImm(0)
6595                    .addMemOperand(CPMMO));
6596     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6597     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6598                    .addReg(NewVReg1, RegState::Kill)
6599                    .addImm(PCLabelId));
6600     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6601                    .addReg(NewVReg2, RegState::Kill)
6602                    .addFrameIndex(FI)
6603                    .addImm(36)  // &jbuf[1] :: pc
6604                    .addMemOperand(FIMMOSt));
6605   }
6606 }
6607
6608 MachineBasicBlock *ARMTargetLowering::
6609 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6610   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6611   DebugLoc dl = MI->getDebugLoc();
6612   MachineFunction *MF = MBB->getParent();
6613   MachineRegisterInfo *MRI = &MF->getRegInfo();
6614   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6615   MachineFrameInfo *MFI = MF->getFrameInfo();
6616   int FI = MFI->getFunctionContextIndex();
6617
6618   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6619                                                         : &ARM::GPRnopcRegClass;
6620
6621   // Get a mapping of the call site numbers to all of the landing pads they're
6622   // associated with.
6623   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6624   unsigned MaxCSNum = 0;
6625   MachineModuleInfo &MMI = MF->getMMI();
6626   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6627        ++BB) {
6628     if (!BB->isLandingPad()) continue;
6629
6630     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6631     // pad.
6632     for (MachineBasicBlock::iterator
6633            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6634       if (!II->isEHLabel()) continue;
6635
6636       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6637       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6638
6639       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6640       for (SmallVectorImpl<unsigned>::iterator
6641              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6642            CSI != CSE; ++CSI) {
6643         CallSiteNumToLPad[*CSI].push_back(BB);
6644         MaxCSNum = std::max(MaxCSNum, *CSI);
6645       }
6646       break;
6647     }
6648   }
6649
6650   // Get an ordered list of the machine basic blocks for the jump table.
6651   std::vector<MachineBasicBlock*> LPadList;
6652   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6653   LPadList.reserve(CallSiteNumToLPad.size());
6654   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6655     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6656     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6657            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6658       LPadList.push_back(*II);
6659       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6660     }
6661   }
6662
6663   assert(!LPadList.empty() &&
6664          "No landing pad destinations for the dispatch jump table!");
6665
6666   // Create the jump table and associated information.
6667   MachineJumpTableInfo *JTI =
6668     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6669   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6670   unsigned UId = AFI->createJumpTableUId();
6671   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6672
6673   // Create the MBBs for the dispatch code.
6674
6675   // Shove the dispatch's address into the return slot in the function context.
6676   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6677   DispatchBB->setIsLandingPad();
6678
6679   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6680   unsigned trap_opcode;
6681   if (Subtarget->isThumb())
6682     trap_opcode = ARM::tTRAP;
6683   else
6684     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6685
6686   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6687   DispatchBB->addSuccessor(TrapBB);
6688
6689   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6690   DispatchBB->addSuccessor(DispContBB);
6691
6692   // Insert and MBBs.
6693   MF->insert(MF->end(), DispatchBB);
6694   MF->insert(MF->end(), DispContBB);
6695   MF->insert(MF->end(), TrapBB);
6696
6697   // Insert code into the entry block that creates and registers the function
6698   // context.
6699   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6700
6701   MachineMemOperand *FIMMOLd =
6702     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6703                              MachineMemOperand::MOLoad |
6704                              MachineMemOperand::MOVolatile, 4, 4);
6705
6706   MachineInstrBuilder MIB;
6707   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6708
6709   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6710   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6711
6712   // Add a register mask with no preserved registers.  This results in all
6713   // registers being marked as clobbered.
6714   MIB.addRegMask(RI.getNoPreservedMask());
6715
6716   unsigned NumLPads = LPadList.size();
6717   if (Subtarget->isThumb2()) {
6718     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6719     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6720                    .addFrameIndex(FI)
6721                    .addImm(4)
6722                    .addMemOperand(FIMMOLd));
6723
6724     if (NumLPads < 256) {
6725       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6726                      .addReg(NewVReg1)
6727                      .addImm(LPadList.size()));
6728     } else {
6729       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6730       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6731                      .addImm(NumLPads & 0xFFFF));
6732
6733       unsigned VReg2 = VReg1;
6734       if ((NumLPads & 0xFFFF0000) != 0) {
6735         VReg2 = MRI->createVirtualRegister(TRC);
6736         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6737                        .addReg(VReg1)
6738                        .addImm(NumLPads >> 16));
6739       }
6740
6741       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6742                      .addReg(NewVReg1)
6743                      .addReg(VReg2));
6744     }
6745
6746     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6747       .addMBB(TrapBB)
6748       .addImm(ARMCC::HI)
6749       .addReg(ARM::CPSR);
6750
6751     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6752     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6753                    .addJumpTableIndex(MJTI)
6754                    .addImm(UId));
6755
6756     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6757     AddDefaultCC(
6758       AddDefaultPred(
6759         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6760         .addReg(NewVReg3, RegState::Kill)
6761         .addReg(NewVReg1)
6762         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6763
6764     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6765       .addReg(NewVReg4, RegState::Kill)
6766       .addReg(NewVReg1)
6767       .addJumpTableIndex(MJTI)
6768       .addImm(UId);
6769   } else if (Subtarget->isThumb()) {
6770     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6771     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6772                    .addFrameIndex(FI)
6773                    .addImm(1)
6774                    .addMemOperand(FIMMOLd));
6775
6776     if (NumLPads < 256) {
6777       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6778                      .addReg(NewVReg1)
6779                      .addImm(NumLPads));
6780     } else {
6781       MachineConstantPool *ConstantPool = MF->getConstantPool();
6782       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6783       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6784
6785       // MachineConstantPool wants an explicit alignment.
6786       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6787       if (Align == 0)
6788         Align = getDataLayout()->getTypeAllocSize(C->getType());
6789       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6790
6791       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6792       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6793                      .addReg(VReg1, RegState::Define)
6794                      .addConstantPoolIndex(Idx));
6795       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6796                      .addReg(NewVReg1)
6797                      .addReg(VReg1));
6798     }
6799
6800     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6801       .addMBB(TrapBB)
6802       .addImm(ARMCC::HI)
6803       .addReg(ARM::CPSR);
6804
6805     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6806     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6807                    .addReg(ARM::CPSR, RegState::Define)
6808                    .addReg(NewVReg1)
6809                    .addImm(2));
6810
6811     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6812     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6813                    .addJumpTableIndex(MJTI)
6814                    .addImm(UId));
6815
6816     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6817     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6818                    .addReg(ARM::CPSR, RegState::Define)
6819                    .addReg(NewVReg2, RegState::Kill)
6820                    .addReg(NewVReg3));
6821
6822     MachineMemOperand *JTMMOLd =
6823       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6824                                MachineMemOperand::MOLoad, 4, 4);
6825
6826     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6827     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6828                    .addReg(NewVReg4, RegState::Kill)
6829                    .addImm(0)
6830                    .addMemOperand(JTMMOLd));
6831
6832     unsigned NewVReg6 = NewVReg5;
6833     if (RelocM == Reloc::PIC_) {
6834       NewVReg6 = MRI->createVirtualRegister(TRC);
6835       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6836                      .addReg(ARM::CPSR, RegState::Define)
6837                      .addReg(NewVReg5, RegState::Kill)
6838                      .addReg(NewVReg3));
6839     }
6840
6841     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6842       .addReg(NewVReg6, RegState::Kill)
6843       .addJumpTableIndex(MJTI)
6844       .addImm(UId);
6845   } else {
6846     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6847     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6848                    .addFrameIndex(FI)
6849                    .addImm(4)
6850                    .addMemOperand(FIMMOLd));
6851
6852     if (NumLPads < 256) {
6853       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6854                      .addReg(NewVReg1)
6855                      .addImm(NumLPads));
6856     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6857       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6858       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6859                      .addImm(NumLPads & 0xFFFF));
6860
6861       unsigned VReg2 = VReg1;
6862       if ((NumLPads & 0xFFFF0000) != 0) {
6863         VReg2 = MRI->createVirtualRegister(TRC);
6864         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6865                        .addReg(VReg1)
6866                        .addImm(NumLPads >> 16));
6867       }
6868
6869       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6870                      .addReg(NewVReg1)
6871                      .addReg(VReg2));
6872     } else {
6873       MachineConstantPool *ConstantPool = MF->getConstantPool();
6874       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6875       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6876
6877       // MachineConstantPool wants an explicit alignment.
6878       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6879       if (Align == 0)
6880         Align = getDataLayout()->getTypeAllocSize(C->getType());
6881       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6882
6883       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6884       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6885                      .addReg(VReg1, RegState::Define)
6886                      .addConstantPoolIndex(Idx)
6887                      .addImm(0));
6888       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6889                      .addReg(NewVReg1)
6890                      .addReg(VReg1, RegState::Kill));
6891     }
6892
6893     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6894       .addMBB(TrapBB)
6895       .addImm(ARMCC::HI)
6896       .addReg(ARM::CPSR);
6897
6898     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6899     AddDefaultCC(
6900       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6901                      .addReg(NewVReg1)
6902                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6903     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6904     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6905                    .addJumpTableIndex(MJTI)
6906                    .addImm(UId));
6907
6908     MachineMemOperand *JTMMOLd =
6909       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6910                                MachineMemOperand::MOLoad, 4, 4);
6911     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6912     AddDefaultPred(
6913       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6914       .addReg(NewVReg3, RegState::Kill)
6915       .addReg(NewVReg4)
6916       .addImm(0)
6917       .addMemOperand(JTMMOLd));
6918
6919     if (RelocM == Reloc::PIC_) {
6920       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6921         .addReg(NewVReg5, RegState::Kill)
6922         .addReg(NewVReg4)
6923         .addJumpTableIndex(MJTI)
6924         .addImm(UId);
6925     } else {
6926       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6927         .addReg(NewVReg5, RegState::Kill)
6928         .addJumpTableIndex(MJTI)
6929         .addImm(UId);
6930     }
6931   }
6932
6933   // Add the jump table entries as successors to the MBB.
6934   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6935   for (std::vector<MachineBasicBlock*>::iterator
6936          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6937     MachineBasicBlock *CurMBB = *I;
6938     if (SeenMBBs.insert(CurMBB).second)
6939       DispContBB->addSuccessor(CurMBB);
6940   }
6941
6942   // N.B. the order the invoke BBs are processed in doesn't matter here.
6943   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6944   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6945   for (MachineBasicBlock *BB : InvokeBBs) {
6946
6947     // Remove the landing pad successor from the invoke block and replace it
6948     // with the new dispatch block.
6949     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6950                                                   BB->succ_end());
6951     while (!Successors.empty()) {
6952       MachineBasicBlock *SMBB = Successors.pop_back_val();
6953       if (SMBB->isLandingPad()) {
6954         BB->removeSuccessor(SMBB);
6955         MBBLPads.push_back(SMBB);
6956       }
6957     }
6958
6959     BB->addSuccessor(DispatchBB);
6960
6961     // Find the invoke call and mark all of the callee-saved registers as
6962     // 'implicit defined' so that they're spilled. This prevents code from
6963     // moving instructions to before the EH block, where they will never be
6964     // executed.
6965     for (MachineBasicBlock::reverse_iterator
6966            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6967       if (!II->isCall()) continue;
6968
6969       DenseMap<unsigned, bool> DefRegs;
6970       for (MachineInstr::mop_iterator
6971              OI = II->operands_begin(), OE = II->operands_end();
6972            OI != OE; ++OI) {
6973         if (!OI->isReg()) continue;
6974         DefRegs[OI->getReg()] = true;
6975       }
6976
6977       MachineInstrBuilder MIB(*MF, &*II);
6978
6979       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6980         unsigned Reg = SavedRegs[i];
6981         if (Subtarget->isThumb2() &&
6982             !ARM::tGPRRegClass.contains(Reg) &&
6983             !ARM::hGPRRegClass.contains(Reg))
6984           continue;
6985         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6986           continue;
6987         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6988           continue;
6989         if (!DefRegs[Reg])
6990           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6991       }
6992
6993       break;
6994     }
6995   }
6996
6997   // Mark all former landing pads as non-landing pads. The dispatch is the only
6998   // landing pad now.
6999   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7000          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7001     (*I)->setIsLandingPad(false);
7002
7003   // The instruction is gone now.
7004   MI->eraseFromParent();
7005
7006   return MBB;
7007 }
7008
7009 static
7010 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7011   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7012        E = MBB->succ_end(); I != E; ++I)
7013     if (*I != Succ)
7014       return *I;
7015   llvm_unreachable("Expecting a BB with two successors!");
7016 }
7017
7018 /// Return the load opcode for a given load size. If load size >= 8,
7019 /// neon opcode will be returned.
7020 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7021   if (LdSize >= 8)
7022     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7023                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7024   if (IsThumb1)
7025     return LdSize == 4 ? ARM::tLDRi
7026                        : LdSize == 2 ? ARM::tLDRHi
7027                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7028   if (IsThumb2)
7029     return LdSize == 4 ? ARM::t2LDR_POST
7030                        : LdSize == 2 ? ARM::t2LDRH_POST
7031                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7032   return LdSize == 4 ? ARM::LDR_POST_IMM
7033                      : LdSize == 2 ? ARM::LDRH_POST
7034                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7035 }
7036
7037 /// Return the store opcode for a given store size. If store size >= 8,
7038 /// neon opcode will be returned.
7039 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7040   if (StSize >= 8)
7041     return StSize == 16 ? ARM::VST1q32wb_fixed
7042                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7043   if (IsThumb1)
7044     return StSize == 4 ? ARM::tSTRi
7045                        : StSize == 2 ? ARM::tSTRHi
7046                                      : StSize == 1 ? ARM::tSTRBi : 0;
7047   if (IsThumb2)
7048     return StSize == 4 ? ARM::t2STR_POST
7049                        : StSize == 2 ? ARM::t2STRH_POST
7050                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7051   return StSize == 4 ? ARM::STR_POST_IMM
7052                      : StSize == 2 ? ARM::STRH_POST
7053                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7054 }
7055
7056 /// Emit a post-increment load operation with given size. The instructions
7057 /// will be added to BB at Pos.
7058 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7059                        const TargetInstrInfo *TII, DebugLoc dl,
7060                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7061                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7062   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7063   assert(LdOpc != 0 && "Should have a load opcode");
7064   if (LdSize >= 8) {
7065     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7066                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7067                        .addImm(0));
7068   } else if (IsThumb1) {
7069     // load + update AddrIn
7070     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7071                        .addReg(AddrIn).addImm(0));
7072     MachineInstrBuilder MIB =
7073         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7074     MIB = AddDefaultT1CC(MIB);
7075     MIB.addReg(AddrIn).addImm(LdSize);
7076     AddDefaultPred(MIB);
7077   } else if (IsThumb2) {
7078     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7079                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7080                        .addImm(LdSize));
7081   } else { // arm
7082     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7083                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7084                        .addReg(0).addImm(LdSize));
7085   }
7086 }
7087
7088 /// Emit a post-increment store operation with given size. The instructions
7089 /// will be added to BB at Pos.
7090 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7091                        const TargetInstrInfo *TII, DebugLoc dl,
7092                        unsigned StSize, unsigned Data, unsigned AddrIn,
7093                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7094   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7095   assert(StOpc != 0 && "Should have a store opcode");
7096   if (StSize >= 8) {
7097     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7098                        .addReg(AddrIn).addImm(0).addReg(Data));
7099   } else if (IsThumb1) {
7100     // store + update AddrIn
7101     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7102                        .addReg(AddrIn).addImm(0));
7103     MachineInstrBuilder MIB =
7104         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7105     MIB = AddDefaultT1CC(MIB);
7106     MIB.addReg(AddrIn).addImm(StSize);
7107     AddDefaultPred(MIB);
7108   } else if (IsThumb2) {
7109     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7110                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7111   } else { // arm
7112     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7113                        .addReg(Data).addReg(AddrIn).addReg(0)
7114                        .addImm(StSize));
7115   }
7116 }
7117
7118 MachineBasicBlock *
7119 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7120                                    MachineBasicBlock *BB) const {
7121   // This pseudo instruction has 3 operands: dst, src, size
7122   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7123   // Otherwise, we will generate unrolled scalar copies.
7124   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7125   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7126   MachineFunction::iterator It = BB;
7127   ++It;
7128
7129   unsigned dest = MI->getOperand(0).getReg();
7130   unsigned src = MI->getOperand(1).getReg();
7131   unsigned SizeVal = MI->getOperand(2).getImm();
7132   unsigned Align = MI->getOperand(3).getImm();
7133   DebugLoc dl = MI->getDebugLoc();
7134
7135   MachineFunction *MF = BB->getParent();
7136   MachineRegisterInfo &MRI = MF->getRegInfo();
7137   unsigned UnitSize = 0;
7138   const TargetRegisterClass *TRC = nullptr;
7139   const TargetRegisterClass *VecTRC = nullptr;
7140
7141   bool IsThumb1 = Subtarget->isThumb1Only();
7142   bool IsThumb2 = Subtarget->isThumb2();
7143
7144   if (Align & 1) {
7145     UnitSize = 1;
7146   } else if (Align & 2) {
7147     UnitSize = 2;
7148   } else {
7149     // Check whether we can use NEON instructions.
7150     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7151         Subtarget->hasNEON()) {
7152       if ((Align % 16 == 0) && SizeVal >= 16)
7153         UnitSize = 16;
7154       else if ((Align % 8 == 0) && SizeVal >= 8)
7155         UnitSize = 8;
7156     }
7157     // Can't use NEON instructions.
7158     if (UnitSize == 0)
7159       UnitSize = 4;
7160   }
7161
7162   // Select the correct opcode and register class for unit size load/store
7163   bool IsNeon = UnitSize >= 8;
7164   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7165   if (IsNeon)
7166     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7167                             : UnitSize == 8 ? &ARM::DPRRegClass
7168                                             : nullptr;
7169
7170   unsigned BytesLeft = SizeVal % UnitSize;
7171   unsigned LoopSize = SizeVal - BytesLeft;
7172
7173   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7174     // Use LDR and STR to copy.
7175     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7176     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7177     unsigned srcIn = src;
7178     unsigned destIn = dest;
7179     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7180       unsigned srcOut = MRI.createVirtualRegister(TRC);
7181       unsigned destOut = MRI.createVirtualRegister(TRC);
7182       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7183       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7184                  IsThumb1, IsThumb2);
7185       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7186                  IsThumb1, IsThumb2);
7187       srcIn = srcOut;
7188       destIn = destOut;
7189     }
7190
7191     // Handle the leftover bytes with LDRB and STRB.
7192     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7193     // [destOut] = STRB_POST(scratch, destIn, 1)
7194     for (unsigned i = 0; i < BytesLeft; i++) {
7195       unsigned srcOut = MRI.createVirtualRegister(TRC);
7196       unsigned destOut = MRI.createVirtualRegister(TRC);
7197       unsigned scratch = MRI.createVirtualRegister(TRC);
7198       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7199                  IsThumb1, IsThumb2);
7200       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7201                  IsThumb1, IsThumb2);
7202       srcIn = srcOut;
7203       destIn = destOut;
7204     }
7205     MI->eraseFromParent();   // The instruction is gone now.
7206     return BB;
7207   }
7208
7209   // Expand the pseudo op to a loop.
7210   // thisMBB:
7211   //   ...
7212   //   movw varEnd, # --> with thumb2
7213   //   movt varEnd, #
7214   //   ldrcp varEnd, idx --> without thumb2
7215   //   fallthrough --> loopMBB
7216   // loopMBB:
7217   //   PHI varPhi, varEnd, varLoop
7218   //   PHI srcPhi, src, srcLoop
7219   //   PHI destPhi, dst, destLoop
7220   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7221   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7222   //   subs varLoop, varPhi, #UnitSize
7223   //   bne loopMBB
7224   //   fallthrough --> exitMBB
7225   // exitMBB:
7226   //   epilogue to handle left-over bytes
7227   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7228   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7229   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7230   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7231   MF->insert(It, loopMBB);
7232   MF->insert(It, exitMBB);
7233
7234   // Transfer the remainder of BB and its successor edges to exitMBB.
7235   exitMBB->splice(exitMBB->begin(), BB,
7236                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7237   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7238
7239   // Load an immediate to varEnd.
7240   unsigned varEnd = MRI.createVirtualRegister(TRC);
7241   if (IsThumb2) {
7242     unsigned Vtmp = varEnd;
7243     if ((LoopSize & 0xFFFF0000) != 0)
7244       Vtmp = MRI.createVirtualRegister(TRC);
7245     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7246                        .addImm(LoopSize & 0xFFFF));
7247
7248     if ((LoopSize & 0xFFFF0000) != 0)
7249       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7250                          .addReg(Vtmp).addImm(LoopSize >> 16));
7251   } else {
7252     MachineConstantPool *ConstantPool = MF->getConstantPool();
7253     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7254     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7255
7256     // MachineConstantPool wants an explicit alignment.
7257     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7258     if (Align == 0)
7259       Align = getDataLayout()->getTypeAllocSize(C->getType());
7260     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7261
7262     if (IsThumb1)
7263       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7264           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7265     else
7266       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7267           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7268   }
7269   BB->addSuccessor(loopMBB);
7270
7271   // Generate the loop body:
7272   //   varPhi = PHI(varLoop, varEnd)
7273   //   srcPhi = PHI(srcLoop, src)
7274   //   destPhi = PHI(destLoop, dst)
7275   MachineBasicBlock *entryBB = BB;
7276   BB = loopMBB;
7277   unsigned varLoop = MRI.createVirtualRegister(TRC);
7278   unsigned varPhi = MRI.createVirtualRegister(TRC);
7279   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7280   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7281   unsigned destLoop = MRI.createVirtualRegister(TRC);
7282   unsigned destPhi = MRI.createVirtualRegister(TRC);
7283
7284   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7285     .addReg(varLoop).addMBB(loopMBB)
7286     .addReg(varEnd).addMBB(entryBB);
7287   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7288     .addReg(srcLoop).addMBB(loopMBB)
7289     .addReg(src).addMBB(entryBB);
7290   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7291     .addReg(destLoop).addMBB(loopMBB)
7292     .addReg(dest).addMBB(entryBB);
7293
7294   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7295   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7296   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7297   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7298              IsThumb1, IsThumb2);
7299   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7300              IsThumb1, IsThumb2);
7301
7302   // Decrement loop variable by UnitSize.
7303   if (IsThumb1) {
7304     MachineInstrBuilder MIB =
7305         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7306     MIB = AddDefaultT1CC(MIB);
7307     MIB.addReg(varPhi).addImm(UnitSize);
7308     AddDefaultPred(MIB);
7309   } else {
7310     MachineInstrBuilder MIB =
7311         BuildMI(*BB, BB->end(), dl,
7312                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7313     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7314     MIB->getOperand(5).setReg(ARM::CPSR);
7315     MIB->getOperand(5).setIsDef(true);
7316   }
7317   BuildMI(*BB, BB->end(), dl,
7318           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7319       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7320
7321   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7322   BB->addSuccessor(loopMBB);
7323   BB->addSuccessor(exitMBB);
7324
7325   // Add epilogue to handle BytesLeft.
7326   BB = exitMBB;
7327   MachineInstr *StartOfExit = exitMBB->begin();
7328
7329   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7330   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7331   unsigned srcIn = srcLoop;
7332   unsigned destIn = destLoop;
7333   for (unsigned i = 0; i < BytesLeft; i++) {
7334     unsigned srcOut = MRI.createVirtualRegister(TRC);
7335     unsigned destOut = MRI.createVirtualRegister(TRC);
7336     unsigned scratch = MRI.createVirtualRegister(TRC);
7337     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7338                IsThumb1, IsThumb2);
7339     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7340                IsThumb1, IsThumb2);
7341     srcIn = srcOut;
7342     destIn = destOut;
7343   }
7344
7345   MI->eraseFromParent();   // The instruction is gone now.
7346   return BB;
7347 }
7348
7349 MachineBasicBlock *
7350 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7351                                        MachineBasicBlock *MBB) const {
7352   const TargetMachine &TM = getTargetMachine();
7353   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7354   DebugLoc DL = MI->getDebugLoc();
7355
7356   assert(Subtarget->isTargetWindows() &&
7357          "__chkstk is only supported on Windows");
7358   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7359
7360   // __chkstk takes the number of words to allocate on the stack in R4, and
7361   // returns the stack adjustment in number of bytes in R4.  This will not
7362   // clober any other registers (other than the obvious lr).
7363   //
7364   // Although, technically, IP should be considered a register which may be
7365   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7366   // thumb-2 environment, so there is no interworking required.  As a result, we
7367   // do not expect a veneer to be emitted by the linker, clobbering IP.
7368   //
7369   // Each module receives its own copy of __chkstk, so no import thunk is
7370   // required, again, ensuring that IP is not clobbered.
7371   //
7372   // Finally, although some linkers may theoretically provide a trampoline for
7373   // out of range calls (which is quite common due to a 32M range limitation of
7374   // branches for Thumb), we can generate the long-call version via
7375   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7376   // IP.
7377
7378   switch (TM.getCodeModel()) {
7379   case CodeModel::Small:
7380   case CodeModel::Medium:
7381   case CodeModel::Default:
7382   case CodeModel::Kernel:
7383     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7384       .addImm((unsigned)ARMCC::AL).addReg(0)
7385       .addExternalSymbol("__chkstk")
7386       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7387       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7388       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7389     break;
7390   case CodeModel::Large:
7391   case CodeModel::JITDefault: {
7392     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7393     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7394
7395     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7396       .addExternalSymbol("__chkstk");
7397     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7398       .addImm((unsigned)ARMCC::AL).addReg(0)
7399       .addReg(Reg, RegState::Kill)
7400       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7401       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7402       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7403     break;
7404   }
7405   }
7406
7407   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7408                                       ARM::SP)
7409                               .addReg(ARM::SP).addReg(ARM::R4)));
7410
7411   MI->eraseFromParent();
7412   return MBB;
7413 }
7414
7415 MachineBasicBlock *
7416 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7417                                                MachineBasicBlock *BB) const {
7418   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7419   DebugLoc dl = MI->getDebugLoc();
7420   bool isThumb2 = Subtarget->isThumb2();
7421   switch (MI->getOpcode()) {
7422   default: {
7423     MI->dump();
7424     llvm_unreachable("Unexpected instr type to insert");
7425   }
7426   // The Thumb2 pre-indexed stores have the same MI operands, they just
7427   // define them differently in the .td files from the isel patterns, so
7428   // they need pseudos.
7429   case ARM::t2STR_preidx:
7430     MI->setDesc(TII->get(ARM::t2STR_PRE));
7431     return BB;
7432   case ARM::t2STRB_preidx:
7433     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7434     return BB;
7435   case ARM::t2STRH_preidx:
7436     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7437     return BB;
7438
7439   case ARM::STRi_preidx:
7440   case ARM::STRBi_preidx: {
7441     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7442       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7443     // Decode the offset.
7444     unsigned Offset = MI->getOperand(4).getImm();
7445     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7446     Offset = ARM_AM::getAM2Offset(Offset);
7447     if (isSub)
7448       Offset = -Offset;
7449
7450     MachineMemOperand *MMO = *MI->memoperands_begin();
7451     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7452       .addOperand(MI->getOperand(0))  // Rn_wb
7453       .addOperand(MI->getOperand(1))  // Rt
7454       .addOperand(MI->getOperand(2))  // Rn
7455       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7456       .addOperand(MI->getOperand(5))  // pred
7457       .addOperand(MI->getOperand(6))
7458       .addMemOperand(MMO);
7459     MI->eraseFromParent();
7460     return BB;
7461   }
7462   case ARM::STRr_preidx:
7463   case ARM::STRBr_preidx:
7464   case ARM::STRH_preidx: {
7465     unsigned NewOpc;
7466     switch (MI->getOpcode()) {
7467     default: llvm_unreachable("unexpected opcode!");
7468     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7469     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7470     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7471     }
7472     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7473     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7474       MIB.addOperand(MI->getOperand(i));
7475     MI->eraseFromParent();
7476     return BB;
7477   }
7478
7479   case ARM::tMOVCCr_pseudo: {
7480     // To "insert" a SELECT_CC instruction, we actually have to insert the
7481     // diamond control-flow pattern.  The incoming instruction knows the
7482     // destination vreg to set, the condition code register to branch on, the
7483     // true/false values to select between, and a branch opcode to use.
7484     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7485     MachineFunction::iterator It = BB;
7486     ++It;
7487
7488     //  thisMBB:
7489     //  ...
7490     //   TrueVal = ...
7491     //   cmpTY ccX, r1, r2
7492     //   bCC copy1MBB
7493     //   fallthrough --> copy0MBB
7494     MachineBasicBlock *thisMBB  = BB;
7495     MachineFunction *F = BB->getParent();
7496     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7497     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7498     F->insert(It, copy0MBB);
7499     F->insert(It, sinkMBB);
7500
7501     // Transfer the remainder of BB and its successor edges to sinkMBB.
7502     sinkMBB->splice(sinkMBB->begin(), BB,
7503                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7504     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7505
7506     BB->addSuccessor(copy0MBB);
7507     BB->addSuccessor(sinkMBB);
7508
7509     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7510       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7511
7512     //  copy0MBB:
7513     //   %FalseValue = ...
7514     //   # fallthrough to sinkMBB
7515     BB = copy0MBB;
7516
7517     // Update machine-CFG edges
7518     BB->addSuccessor(sinkMBB);
7519
7520     //  sinkMBB:
7521     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7522     //  ...
7523     BB = sinkMBB;
7524     BuildMI(*BB, BB->begin(), dl,
7525             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7526       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7527       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7528
7529     MI->eraseFromParent();   // The pseudo instruction is gone now.
7530     return BB;
7531   }
7532
7533   case ARM::BCCi64:
7534   case ARM::BCCZi64: {
7535     // If there is an unconditional branch to the other successor, remove it.
7536     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7537
7538     // Compare both parts that make up the double comparison separately for
7539     // equality.
7540     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7541
7542     unsigned LHS1 = MI->getOperand(1).getReg();
7543     unsigned LHS2 = MI->getOperand(2).getReg();
7544     if (RHSisZero) {
7545       AddDefaultPred(BuildMI(BB, dl,
7546                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7547                      .addReg(LHS1).addImm(0));
7548       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7549         .addReg(LHS2).addImm(0)
7550         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7551     } else {
7552       unsigned RHS1 = MI->getOperand(3).getReg();
7553       unsigned RHS2 = MI->getOperand(4).getReg();
7554       AddDefaultPred(BuildMI(BB, dl,
7555                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7556                      .addReg(LHS1).addReg(RHS1));
7557       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7558         .addReg(LHS2).addReg(RHS2)
7559         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7560     }
7561
7562     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7563     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7564     if (MI->getOperand(0).getImm() == ARMCC::NE)
7565       std::swap(destMBB, exitMBB);
7566
7567     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7568       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7569     if (isThumb2)
7570       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7571     else
7572       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7573
7574     MI->eraseFromParent();   // The pseudo instruction is gone now.
7575     return BB;
7576   }
7577
7578   case ARM::Int_eh_sjlj_setjmp:
7579   case ARM::Int_eh_sjlj_setjmp_nofp:
7580   case ARM::tInt_eh_sjlj_setjmp:
7581   case ARM::t2Int_eh_sjlj_setjmp:
7582   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7583     EmitSjLjDispatchBlock(MI, BB);
7584     return BB;
7585
7586   case ARM::ABS:
7587   case ARM::t2ABS: {
7588     // To insert an ABS instruction, we have to insert the
7589     // diamond control-flow pattern.  The incoming instruction knows the
7590     // source vreg to test against 0, the destination vreg to set,
7591     // the condition code register to branch on, the
7592     // true/false values to select between, and a branch opcode to use.
7593     // It transforms
7594     //     V1 = ABS V0
7595     // into
7596     //     V2 = MOVS V0
7597     //     BCC                      (branch to SinkBB if V0 >= 0)
7598     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7599     //     SinkBB: V1 = PHI(V2, V3)
7600     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7601     MachineFunction::iterator BBI = BB;
7602     ++BBI;
7603     MachineFunction *Fn = BB->getParent();
7604     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7605     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7606     Fn->insert(BBI, RSBBB);
7607     Fn->insert(BBI, SinkBB);
7608
7609     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7610     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7611     bool isThumb2 = Subtarget->isThumb2();
7612     MachineRegisterInfo &MRI = Fn->getRegInfo();
7613     // In Thumb mode S must not be specified if source register is the SP or
7614     // PC and if destination register is the SP, so restrict register class
7615     unsigned NewRsbDstReg =
7616       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7617
7618     // Transfer the remainder of BB and its successor edges to sinkMBB.
7619     SinkBB->splice(SinkBB->begin(), BB,
7620                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7621     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7622
7623     BB->addSuccessor(RSBBB);
7624     BB->addSuccessor(SinkBB);
7625
7626     // fall through to SinkMBB
7627     RSBBB->addSuccessor(SinkBB);
7628
7629     // insert a cmp at the end of BB
7630     AddDefaultPred(BuildMI(BB, dl,
7631                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7632                    .addReg(ABSSrcReg).addImm(0));
7633
7634     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7635     BuildMI(BB, dl,
7636       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7637       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7638
7639     // insert rsbri in RSBBB
7640     // Note: BCC and rsbri will be converted into predicated rsbmi
7641     // by if-conversion pass
7642     BuildMI(*RSBBB, RSBBB->begin(), dl,
7643       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7644       .addReg(ABSSrcReg, RegState::Kill)
7645       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7646
7647     // insert PHI in SinkBB,
7648     // reuse ABSDstReg to not change uses of ABS instruction
7649     BuildMI(*SinkBB, SinkBB->begin(), dl,
7650       TII->get(ARM::PHI), ABSDstReg)
7651       .addReg(NewRsbDstReg).addMBB(RSBBB)
7652       .addReg(ABSSrcReg).addMBB(BB);
7653
7654     // remove ABS instruction
7655     MI->eraseFromParent();
7656
7657     // return last added BB
7658     return SinkBB;
7659   }
7660   case ARM::COPY_STRUCT_BYVAL_I32:
7661     ++NumLoopByVals;
7662     return EmitStructByval(MI, BB);
7663   case ARM::WIN__CHKSTK:
7664     return EmitLowered__chkstk(MI, BB);
7665   }
7666 }
7667
7668 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7669                                                       SDNode *Node) const {
7670   const MCInstrDesc *MCID = &MI->getDesc();
7671   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7672   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7673   // operand is still set to noreg. If needed, set the optional operand's
7674   // register to CPSR, and remove the redundant implicit def.
7675   //
7676   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7677
7678   // Rename pseudo opcodes.
7679   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7680   if (NewOpc) {
7681     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7682     MCID = &TII->get(NewOpc);
7683
7684     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7685            "converted opcode should be the same except for cc_out");
7686
7687     MI->setDesc(*MCID);
7688
7689     // Add the optional cc_out operand
7690     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7691   }
7692   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7693
7694   // Any ARM instruction that sets the 's' bit should specify an optional
7695   // "cc_out" operand in the last operand position.
7696   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7697     assert(!NewOpc && "Optional cc_out operand required");
7698     return;
7699   }
7700   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7701   // since we already have an optional CPSR def.
7702   bool definesCPSR = false;
7703   bool deadCPSR = false;
7704   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7705        i != e; ++i) {
7706     const MachineOperand &MO = MI->getOperand(i);
7707     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7708       definesCPSR = true;
7709       if (MO.isDead())
7710         deadCPSR = true;
7711       MI->RemoveOperand(i);
7712       break;
7713     }
7714   }
7715   if (!definesCPSR) {
7716     assert(!NewOpc && "Optional cc_out operand required");
7717     return;
7718   }
7719   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7720   if (deadCPSR) {
7721     assert(!MI->getOperand(ccOutIdx).getReg() &&
7722            "expect uninitialized optional cc_out operand");
7723     return;
7724   }
7725
7726   // If this instruction was defined with an optional CPSR def and its dag node
7727   // had a live implicit CPSR def, then activate the optional CPSR def.
7728   MachineOperand &MO = MI->getOperand(ccOutIdx);
7729   MO.setReg(ARM::CPSR);
7730   MO.setIsDef(true);
7731 }
7732
7733 //===----------------------------------------------------------------------===//
7734 //                           ARM Optimization Hooks
7735 //===----------------------------------------------------------------------===//
7736
7737 // Helper function that checks if N is a null or all ones constant.
7738 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7739   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7740   if (!C)
7741     return false;
7742   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7743 }
7744
7745 // Return true if N is conditionally 0 or all ones.
7746 // Detects these expressions where cc is an i1 value:
7747 //
7748 //   (select cc 0, y)   [AllOnes=0]
7749 //   (select cc y, 0)   [AllOnes=0]
7750 //   (zext cc)          [AllOnes=0]
7751 //   (sext cc)          [AllOnes=0/1]
7752 //   (select cc -1, y)  [AllOnes=1]
7753 //   (select cc y, -1)  [AllOnes=1]
7754 //
7755 // Invert is set when N is the null/all ones constant when CC is false.
7756 // OtherOp is set to the alternative value of N.
7757 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7758                                        SDValue &CC, bool &Invert,
7759                                        SDValue &OtherOp,
7760                                        SelectionDAG &DAG) {
7761   switch (N->getOpcode()) {
7762   default: return false;
7763   case ISD::SELECT: {
7764     CC = N->getOperand(0);
7765     SDValue N1 = N->getOperand(1);
7766     SDValue N2 = N->getOperand(2);
7767     if (isZeroOrAllOnes(N1, AllOnes)) {
7768       Invert = false;
7769       OtherOp = N2;
7770       return true;
7771     }
7772     if (isZeroOrAllOnes(N2, AllOnes)) {
7773       Invert = true;
7774       OtherOp = N1;
7775       return true;
7776     }
7777     return false;
7778   }
7779   case ISD::ZERO_EXTEND:
7780     // (zext cc) can never be the all ones value.
7781     if (AllOnes)
7782       return false;
7783     // Fall through.
7784   case ISD::SIGN_EXTEND: {
7785     EVT VT = N->getValueType(0);
7786     CC = N->getOperand(0);
7787     if (CC.getValueType() != MVT::i1)
7788       return false;
7789     Invert = !AllOnes;
7790     if (AllOnes)
7791       // When looking for an AllOnes constant, N is an sext, and the 'other'
7792       // value is 0.
7793       OtherOp = DAG.getConstant(0, VT);
7794     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7795       // When looking for a 0 constant, N can be zext or sext.
7796       OtherOp = DAG.getConstant(1, VT);
7797     else
7798       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7799     return true;
7800   }
7801   }
7802 }
7803
7804 // Combine a constant select operand into its use:
7805 //
7806 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7807 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7808 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7809 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7810 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7811 //
7812 // The transform is rejected if the select doesn't have a constant operand that
7813 // is null, or all ones when AllOnes is set.
7814 //
7815 // Also recognize sext/zext from i1:
7816 //
7817 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7818 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7819 //
7820 // These transformations eventually create predicated instructions.
7821 //
7822 // @param N       The node to transform.
7823 // @param Slct    The N operand that is a select.
7824 // @param OtherOp The other N operand (x above).
7825 // @param DCI     Context.
7826 // @param AllOnes Require the select constant to be all ones instead of null.
7827 // @returns The new node, or SDValue() on failure.
7828 static
7829 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7830                             TargetLowering::DAGCombinerInfo &DCI,
7831                             bool AllOnes = false) {
7832   SelectionDAG &DAG = DCI.DAG;
7833   EVT VT = N->getValueType(0);
7834   SDValue NonConstantVal;
7835   SDValue CCOp;
7836   bool SwapSelectOps;
7837   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7838                                   NonConstantVal, DAG))
7839     return SDValue();
7840
7841   // Slct is now know to be the desired identity constant when CC is true.
7842   SDValue TrueVal = OtherOp;
7843   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7844                                  OtherOp, NonConstantVal);
7845   // Unless SwapSelectOps says CC should be false.
7846   if (SwapSelectOps)
7847     std::swap(TrueVal, FalseVal);
7848
7849   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7850                      CCOp, TrueVal, FalseVal);
7851 }
7852
7853 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7854 static
7855 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7856                                        TargetLowering::DAGCombinerInfo &DCI) {
7857   SDValue N0 = N->getOperand(0);
7858   SDValue N1 = N->getOperand(1);
7859   if (N0.getNode()->hasOneUse()) {
7860     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7861     if (Result.getNode())
7862       return Result;
7863   }
7864   if (N1.getNode()->hasOneUse()) {
7865     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7866     if (Result.getNode())
7867       return Result;
7868   }
7869   return SDValue();
7870 }
7871
7872 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7873 // (only after legalization).
7874 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7875                                  TargetLowering::DAGCombinerInfo &DCI,
7876                                  const ARMSubtarget *Subtarget) {
7877
7878   // Only perform optimization if after legalize, and if NEON is available. We
7879   // also expected both operands to be BUILD_VECTORs.
7880   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7881       || N0.getOpcode() != ISD::BUILD_VECTOR
7882       || N1.getOpcode() != ISD::BUILD_VECTOR)
7883     return SDValue();
7884
7885   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7886   EVT VT = N->getValueType(0);
7887   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7888     return SDValue();
7889
7890   // Check that the vector operands are of the right form.
7891   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7892   // operands, where N is the size of the formed vector.
7893   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7894   // index such that we have a pair wise add pattern.
7895
7896   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7897   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7898     return SDValue();
7899   SDValue Vec = N0->getOperand(0)->getOperand(0);
7900   SDNode *V = Vec.getNode();
7901   unsigned nextIndex = 0;
7902
7903   // For each operands to the ADD which are BUILD_VECTORs,
7904   // check to see if each of their operands are an EXTRACT_VECTOR with
7905   // the same vector and appropriate index.
7906   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7907     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7908         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7909
7910       SDValue ExtVec0 = N0->getOperand(i);
7911       SDValue ExtVec1 = N1->getOperand(i);
7912
7913       // First operand is the vector, verify its the same.
7914       if (V != ExtVec0->getOperand(0).getNode() ||
7915           V != ExtVec1->getOperand(0).getNode())
7916         return SDValue();
7917
7918       // Second is the constant, verify its correct.
7919       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7920       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7921
7922       // For the constant, we want to see all the even or all the odd.
7923       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7924           || C1->getZExtValue() != nextIndex+1)
7925         return SDValue();
7926
7927       // Increment index.
7928       nextIndex+=2;
7929     } else
7930       return SDValue();
7931   }
7932
7933   // Create VPADDL node.
7934   SelectionDAG &DAG = DCI.DAG;
7935   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7936
7937   // Build operand list.
7938   SmallVector<SDValue, 8> Ops;
7939   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7940                                 TLI.getPointerTy()));
7941
7942   // Input is the vector.
7943   Ops.push_back(Vec);
7944
7945   // Get widened type and narrowed type.
7946   MVT widenType;
7947   unsigned numElem = VT.getVectorNumElements();
7948   
7949   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7950   switch (inputLaneType.getSimpleVT().SimpleTy) {
7951     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7952     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7953     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7954     default:
7955       llvm_unreachable("Invalid vector element type for padd optimization.");
7956   }
7957
7958   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7959   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7960   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7961 }
7962
7963 static SDValue findMUL_LOHI(SDValue V) {
7964   if (V->getOpcode() == ISD::UMUL_LOHI ||
7965       V->getOpcode() == ISD::SMUL_LOHI)
7966     return V;
7967   return SDValue();
7968 }
7969
7970 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7971                                      TargetLowering::DAGCombinerInfo &DCI,
7972                                      const ARMSubtarget *Subtarget) {
7973
7974   if (Subtarget->isThumb1Only()) return SDValue();
7975
7976   // Only perform the checks after legalize when the pattern is available.
7977   if (DCI.isBeforeLegalize()) return SDValue();
7978
7979   // Look for multiply add opportunities.
7980   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7981   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7982   // a glue link from the first add to the second add.
7983   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7984   // a S/UMLAL instruction.
7985   //          loAdd   UMUL_LOHI
7986   //            \    / :lo    \ :hi
7987   //             \  /          \          [no multiline comment]
7988   //              ADDC         |  hiAdd
7989   //                 \ :glue  /  /
7990   //                  \      /  /
7991   //                    ADDE
7992   //
7993   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7994   SDValue AddcOp0 = AddcNode->getOperand(0);
7995   SDValue AddcOp1 = AddcNode->getOperand(1);
7996
7997   // Check if the two operands are from the same mul_lohi node.
7998   if (AddcOp0.getNode() == AddcOp1.getNode())
7999     return SDValue();
8000
8001   assert(AddcNode->getNumValues() == 2 &&
8002          AddcNode->getValueType(0) == MVT::i32 &&
8003          "Expect ADDC with two result values. First: i32");
8004
8005   // Check that we have a glued ADDC node.
8006   if (AddcNode->getValueType(1) != MVT::Glue)
8007     return SDValue();
8008
8009   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8010   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8011       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8012       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8013       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8014     return SDValue();
8015
8016   // Look for the glued ADDE.
8017   SDNode* AddeNode = AddcNode->getGluedUser();
8018   if (!AddeNode)
8019     return SDValue();
8020
8021   // Make sure it is really an ADDE.
8022   if (AddeNode->getOpcode() != ISD::ADDE)
8023     return SDValue();
8024
8025   assert(AddeNode->getNumOperands() == 3 &&
8026          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8027          "ADDE node has the wrong inputs");
8028
8029   // Check for the triangle shape.
8030   SDValue AddeOp0 = AddeNode->getOperand(0);
8031   SDValue AddeOp1 = AddeNode->getOperand(1);
8032
8033   // Make sure that the ADDE operands are not coming from the same node.
8034   if (AddeOp0.getNode() == AddeOp1.getNode())
8035     return SDValue();
8036
8037   // Find the MUL_LOHI node walking up ADDE's operands.
8038   bool IsLeftOperandMUL = false;
8039   SDValue MULOp = findMUL_LOHI(AddeOp0);
8040   if (MULOp == SDValue())
8041    MULOp = findMUL_LOHI(AddeOp1);
8042   else
8043     IsLeftOperandMUL = true;
8044   if (MULOp == SDValue())
8045     return SDValue();
8046
8047   // Figure out the right opcode.
8048   unsigned Opc = MULOp->getOpcode();
8049   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8050
8051   // Figure out the high and low input values to the MLAL node.
8052   SDValue* HiAdd = nullptr;
8053   SDValue* LoMul = nullptr;
8054   SDValue* LowAdd = nullptr;
8055
8056   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8057   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8058     return SDValue();
8059
8060   if (IsLeftOperandMUL)
8061     HiAdd = &AddeOp1;
8062   else
8063     HiAdd = &AddeOp0;
8064
8065
8066   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8067   // whose low result is fed to the ADDC we are checking.
8068
8069   if (AddcOp0 == MULOp.getValue(0)) {
8070     LoMul = &AddcOp0;
8071     LowAdd = &AddcOp1;
8072   }
8073   if (AddcOp1 == MULOp.getValue(0)) {
8074     LoMul = &AddcOp1;
8075     LowAdd = &AddcOp0;
8076   }
8077
8078   if (!LoMul)
8079     return SDValue();
8080
8081   // Create the merged node.
8082   SelectionDAG &DAG = DCI.DAG;
8083
8084   // Build operand list.
8085   SmallVector<SDValue, 8> Ops;
8086   Ops.push_back(LoMul->getOperand(0));
8087   Ops.push_back(LoMul->getOperand(1));
8088   Ops.push_back(*LowAdd);
8089   Ops.push_back(*HiAdd);
8090
8091   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8092                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8093
8094   // Replace the ADDs' nodes uses by the MLA node's values.
8095   SDValue HiMLALResult(MLALNode.getNode(), 1);
8096   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8097
8098   SDValue LoMLALResult(MLALNode.getNode(), 0);
8099   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8100
8101   // Return original node to notify the driver to stop replacing.
8102   SDValue resNode(AddcNode, 0);
8103   return resNode;
8104 }
8105
8106 /// PerformADDCCombine - Target-specific dag combine transform from
8107 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8108 static SDValue PerformADDCCombine(SDNode *N,
8109                                  TargetLowering::DAGCombinerInfo &DCI,
8110                                  const ARMSubtarget *Subtarget) {
8111
8112   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8113
8114 }
8115
8116 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8117 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8118 /// called with the default operands, and if that fails, with commuted
8119 /// operands.
8120 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8121                                           TargetLowering::DAGCombinerInfo &DCI,
8122                                           const ARMSubtarget *Subtarget){
8123
8124   // Attempt to create vpaddl for this add.
8125   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8126   if (Result.getNode())
8127     return Result;
8128
8129   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8130   if (N0.getNode()->hasOneUse()) {
8131     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8132     if (Result.getNode()) return Result;
8133   }
8134   return SDValue();
8135 }
8136
8137 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8138 ///
8139 static SDValue PerformADDCombine(SDNode *N,
8140                                  TargetLowering::DAGCombinerInfo &DCI,
8141                                  const ARMSubtarget *Subtarget) {
8142   SDValue N0 = N->getOperand(0);
8143   SDValue N1 = N->getOperand(1);
8144
8145   // First try with the default operand order.
8146   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8147   if (Result.getNode())
8148     return Result;
8149
8150   // If that didn't work, try again with the operands commuted.
8151   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8152 }
8153
8154 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8155 ///
8156 static SDValue PerformSUBCombine(SDNode *N,
8157                                  TargetLowering::DAGCombinerInfo &DCI) {
8158   SDValue N0 = N->getOperand(0);
8159   SDValue N1 = N->getOperand(1);
8160
8161   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8162   if (N1.getNode()->hasOneUse()) {
8163     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8164     if (Result.getNode()) return Result;
8165   }
8166
8167   return SDValue();
8168 }
8169
8170 /// PerformVMULCombine
8171 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8172 /// special multiplier accumulator forwarding.
8173 ///   vmul d3, d0, d2
8174 ///   vmla d3, d1, d2
8175 /// is faster than
8176 ///   vadd d3, d0, d1
8177 ///   vmul d3, d3, d2
8178 //  However, for (A + B) * (A + B),
8179 //    vadd d2, d0, d1
8180 //    vmul d3, d0, d2
8181 //    vmla d3, d1, d2
8182 //  is slower than
8183 //    vadd d2, d0, d1
8184 //    vmul d3, d2, d2
8185 static SDValue PerformVMULCombine(SDNode *N,
8186                                   TargetLowering::DAGCombinerInfo &DCI,
8187                                   const ARMSubtarget *Subtarget) {
8188   if (!Subtarget->hasVMLxForwarding())
8189     return SDValue();
8190
8191   SelectionDAG &DAG = DCI.DAG;
8192   SDValue N0 = N->getOperand(0);
8193   SDValue N1 = N->getOperand(1);
8194   unsigned Opcode = N0.getOpcode();
8195   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8196       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8197     Opcode = N1.getOpcode();
8198     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8199         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8200       return SDValue();
8201     std::swap(N0, N1);
8202   }
8203
8204   if (N0 == N1)
8205     return SDValue();
8206
8207   EVT VT = N->getValueType(0);
8208   SDLoc DL(N);
8209   SDValue N00 = N0->getOperand(0);
8210   SDValue N01 = N0->getOperand(1);
8211   return DAG.getNode(Opcode, DL, VT,
8212                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8213                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8214 }
8215
8216 static SDValue PerformMULCombine(SDNode *N,
8217                                  TargetLowering::DAGCombinerInfo &DCI,
8218                                  const ARMSubtarget *Subtarget) {
8219   SelectionDAG &DAG = DCI.DAG;
8220
8221   if (Subtarget->isThumb1Only())
8222     return SDValue();
8223
8224   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8225     return SDValue();
8226
8227   EVT VT = N->getValueType(0);
8228   if (VT.is64BitVector() || VT.is128BitVector())
8229     return PerformVMULCombine(N, DCI, Subtarget);
8230   if (VT != MVT::i32)
8231     return SDValue();
8232
8233   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8234   if (!C)
8235     return SDValue();
8236
8237   int64_t MulAmt = C->getSExtValue();
8238   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8239
8240   ShiftAmt = ShiftAmt & (32 - 1);
8241   SDValue V = N->getOperand(0);
8242   SDLoc DL(N);
8243
8244   SDValue Res;
8245   MulAmt >>= ShiftAmt;
8246
8247   if (MulAmt >= 0) {
8248     if (isPowerOf2_32(MulAmt - 1)) {
8249       // (mul x, 2^N + 1) => (add (shl x, N), x)
8250       Res = DAG.getNode(ISD::ADD, DL, VT,
8251                         V,
8252                         DAG.getNode(ISD::SHL, DL, VT,
8253                                     V,
8254                                     DAG.getConstant(Log2_32(MulAmt - 1),
8255                                                     MVT::i32)));
8256     } else if (isPowerOf2_32(MulAmt + 1)) {
8257       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8258       Res = DAG.getNode(ISD::SUB, DL, VT,
8259                         DAG.getNode(ISD::SHL, DL, VT,
8260                                     V,
8261                                     DAG.getConstant(Log2_32(MulAmt + 1),
8262                                                     MVT::i32)),
8263                         V);
8264     } else
8265       return SDValue();
8266   } else {
8267     uint64_t MulAmtAbs = -MulAmt;
8268     if (isPowerOf2_32(MulAmtAbs + 1)) {
8269       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8270       Res = DAG.getNode(ISD::SUB, DL, VT,
8271                         V,
8272                         DAG.getNode(ISD::SHL, DL, VT,
8273                                     V,
8274                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8275                                                     MVT::i32)));
8276     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8277       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8278       Res = DAG.getNode(ISD::ADD, DL, VT,
8279                         V,
8280                         DAG.getNode(ISD::SHL, DL, VT,
8281                                     V,
8282                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8283                                                     MVT::i32)));
8284       Res = DAG.getNode(ISD::SUB, DL, VT,
8285                         DAG.getConstant(0, MVT::i32),Res);
8286
8287     } else
8288       return SDValue();
8289   }
8290
8291   if (ShiftAmt != 0)
8292     Res = DAG.getNode(ISD::SHL, DL, VT,
8293                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8294
8295   // Do not add new nodes to DAG combiner worklist.
8296   DCI.CombineTo(N, Res, false);
8297   return SDValue();
8298 }
8299
8300 static SDValue PerformANDCombine(SDNode *N,
8301                                  TargetLowering::DAGCombinerInfo &DCI,
8302                                  const ARMSubtarget *Subtarget) {
8303
8304   // Attempt to use immediate-form VBIC
8305   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8306   SDLoc dl(N);
8307   EVT VT = N->getValueType(0);
8308   SelectionDAG &DAG = DCI.DAG;
8309
8310   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8311     return SDValue();
8312
8313   APInt SplatBits, SplatUndef;
8314   unsigned SplatBitSize;
8315   bool HasAnyUndefs;
8316   if (BVN &&
8317       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8318     if (SplatBitSize <= 64) {
8319       EVT VbicVT;
8320       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8321                                       SplatUndef.getZExtValue(), SplatBitSize,
8322                                       DAG, VbicVT, VT.is128BitVector(),
8323                                       OtherModImm);
8324       if (Val.getNode()) {
8325         SDValue Input =
8326           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8327         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8328         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8329       }
8330     }
8331   }
8332
8333   if (!Subtarget->isThumb1Only()) {
8334     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8335     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8336     if (Result.getNode())
8337       return Result;
8338   }
8339
8340   return SDValue();
8341 }
8342
8343 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8344 static SDValue PerformORCombine(SDNode *N,
8345                                 TargetLowering::DAGCombinerInfo &DCI,
8346                                 const ARMSubtarget *Subtarget) {
8347   // Attempt to use immediate-form VORR
8348   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8349   SDLoc dl(N);
8350   EVT VT = N->getValueType(0);
8351   SelectionDAG &DAG = DCI.DAG;
8352
8353   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8354     return SDValue();
8355
8356   APInt SplatBits, SplatUndef;
8357   unsigned SplatBitSize;
8358   bool HasAnyUndefs;
8359   if (BVN && Subtarget->hasNEON() &&
8360       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8361     if (SplatBitSize <= 64) {
8362       EVT VorrVT;
8363       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8364                                       SplatUndef.getZExtValue(), SplatBitSize,
8365                                       DAG, VorrVT, VT.is128BitVector(),
8366                                       OtherModImm);
8367       if (Val.getNode()) {
8368         SDValue Input =
8369           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8370         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8371         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8372       }
8373     }
8374   }
8375
8376   if (!Subtarget->isThumb1Only()) {
8377     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8378     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8379     if (Result.getNode())
8380       return Result;
8381   }
8382
8383   // The code below optimizes (or (and X, Y), Z).
8384   // The AND operand needs to have a single user to make these optimizations
8385   // profitable.
8386   SDValue N0 = N->getOperand(0);
8387   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8388     return SDValue();
8389   SDValue N1 = N->getOperand(1);
8390
8391   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8392   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8393       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8394     APInt SplatUndef;
8395     unsigned SplatBitSize;
8396     bool HasAnyUndefs;
8397
8398     APInt SplatBits0, SplatBits1;
8399     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8400     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8401     // Ensure that the second operand of both ands are constants
8402     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8403                                       HasAnyUndefs) && !HasAnyUndefs) {
8404         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8405                                           HasAnyUndefs) && !HasAnyUndefs) {
8406             // Ensure that the bit width of the constants are the same and that
8407             // the splat arguments are logical inverses as per the pattern we
8408             // are trying to simplify.
8409             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8410                 SplatBits0 == ~SplatBits1) {
8411                 // Canonicalize the vector type to make instruction selection
8412                 // simpler.
8413                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8414                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8415                                              N0->getOperand(1),
8416                                              N0->getOperand(0),
8417                                              N1->getOperand(0));
8418                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8419             }
8420         }
8421     }
8422   }
8423
8424   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8425   // reasonable.
8426
8427   // BFI is only available on V6T2+
8428   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8429     return SDValue();
8430
8431   SDLoc DL(N);
8432   // 1) or (and A, mask), val => ARMbfi A, val, mask
8433   //      iff (val & mask) == val
8434   //
8435   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8436   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8437   //          && mask == ~mask2
8438   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8439   //          && ~mask == mask2
8440   //  (i.e., copy a bitfield value into another bitfield of the same width)
8441
8442   if (VT != MVT::i32)
8443     return SDValue();
8444
8445   SDValue N00 = N0.getOperand(0);
8446
8447   // The value and the mask need to be constants so we can verify this is
8448   // actually a bitfield set. If the mask is 0xffff, we can do better
8449   // via a movt instruction, so don't use BFI in that case.
8450   SDValue MaskOp = N0.getOperand(1);
8451   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8452   if (!MaskC)
8453     return SDValue();
8454   unsigned Mask = MaskC->getZExtValue();
8455   if (Mask == 0xffff)
8456     return SDValue();
8457   SDValue Res;
8458   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8459   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8460   if (N1C) {
8461     unsigned Val = N1C->getZExtValue();
8462     if ((Val & ~Mask) != Val)
8463       return SDValue();
8464
8465     if (ARM::isBitFieldInvertedMask(Mask)) {
8466       Val >>= countTrailingZeros(~Mask);
8467
8468       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8469                         DAG.getConstant(Val, MVT::i32),
8470                         DAG.getConstant(Mask, MVT::i32));
8471
8472       // Do not add new nodes to DAG combiner worklist.
8473       DCI.CombineTo(N, Res, false);
8474       return SDValue();
8475     }
8476   } else if (N1.getOpcode() == ISD::AND) {
8477     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8478     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8479     if (!N11C)
8480       return SDValue();
8481     unsigned Mask2 = N11C->getZExtValue();
8482
8483     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8484     // as is to match.
8485     if (ARM::isBitFieldInvertedMask(Mask) &&
8486         (Mask == ~Mask2)) {
8487       // The pack halfword instruction works better for masks that fit it,
8488       // so use that when it's available.
8489       if (Subtarget->hasT2ExtractPack() &&
8490           (Mask == 0xffff || Mask == 0xffff0000))
8491         return SDValue();
8492       // 2a
8493       unsigned amt = countTrailingZeros(Mask2);
8494       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8495                         DAG.getConstant(amt, MVT::i32));
8496       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8497                         DAG.getConstant(Mask, MVT::i32));
8498       // Do not add new nodes to DAG combiner worklist.
8499       DCI.CombineTo(N, Res, false);
8500       return SDValue();
8501     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8502                (~Mask == Mask2)) {
8503       // The pack halfword instruction works better for masks that fit it,
8504       // so use that when it's available.
8505       if (Subtarget->hasT2ExtractPack() &&
8506           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8507         return SDValue();
8508       // 2b
8509       unsigned lsb = countTrailingZeros(Mask);
8510       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8511                         DAG.getConstant(lsb, MVT::i32));
8512       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8513                         DAG.getConstant(Mask2, MVT::i32));
8514       // Do not add new nodes to DAG combiner worklist.
8515       DCI.CombineTo(N, Res, false);
8516       return SDValue();
8517     }
8518   }
8519
8520   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8521       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8522       ARM::isBitFieldInvertedMask(~Mask)) {
8523     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8524     // where lsb(mask) == #shamt and masked bits of B are known zero.
8525     SDValue ShAmt = N00.getOperand(1);
8526     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8527     unsigned LSB = countTrailingZeros(Mask);
8528     if (ShAmtC != LSB)
8529       return SDValue();
8530
8531     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8532                       DAG.getConstant(~Mask, MVT::i32));
8533
8534     // Do not add new nodes to DAG combiner worklist.
8535     DCI.CombineTo(N, Res, false);
8536   }
8537
8538   return SDValue();
8539 }
8540
8541 static SDValue PerformXORCombine(SDNode *N,
8542                                  TargetLowering::DAGCombinerInfo &DCI,
8543                                  const ARMSubtarget *Subtarget) {
8544   EVT VT = N->getValueType(0);
8545   SelectionDAG &DAG = DCI.DAG;
8546
8547   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8548     return SDValue();
8549
8550   if (!Subtarget->isThumb1Only()) {
8551     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8552     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8553     if (Result.getNode())
8554       return Result;
8555   }
8556
8557   return SDValue();
8558 }
8559
8560 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8561 /// the bits being cleared by the AND are not demanded by the BFI.
8562 static SDValue PerformBFICombine(SDNode *N,
8563                                  TargetLowering::DAGCombinerInfo &DCI) {
8564   SDValue N1 = N->getOperand(1);
8565   if (N1.getOpcode() == ISD::AND) {
8566     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8567     if (!N11C)
8568       return SDValue();
8569     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8570     unsigned LSB = countTrailingZeros(~InvMask);
8571     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8572     assert(Width <
8573                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8574            "undefined behavior");
8575     unsigned Mask = (1u << Width) - 1;
8576     unsigned Mask2 = N11C->getZExtValue();
8577     if ((Mask & (~Mask2)) == 0)
8578       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8579                              N->getOperand(0), N1.getOperand(0),
8580                              N->getOperand(2));
8581   }
8582   return SDValue();
8583 }
8584
8585 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8586 /// ARMISD::VMOVRRD.
8587 static SDValue PerformVMOVRRDCombine(SDNode *N,
8588                                      TargetLowering::DAGCombinerInfo &DCI,
8589                                      const ARMSubtarget *Subtarget) {
8590   // vmovrrd(vmovdrr x, y) -> x,y
8591   SDValue InDouble = N->getOperand(0);
8592   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8593     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8594
8595   // vmovrrd(load f64) -> (load i32), (load i32)
8596   SDNode *InNode = InDouble.getNode();
8597   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8598       InNode->getValueType(0) == MVT::f64 &&
8599       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8600       !cast<LoadSDNode>(InNode)->isVolatile()) {
8601     // TODO: Should this be done for non-FrameIndex operands?
8602     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8603
8604     SelectionDAG &DAG = DCI.DAG;
8605     SDLoc DL(LD);
8606     SDValue BasePtr = LD->getBasePtr();
8607     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8608                                  LD->getPointerInfo(), LD->isVolatile(),
8609                                  LD->isNonTemporal(), LD->isInvariant(),
8610                                  LD->getAlignment());
8611
8612     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8613                                     DAG.getConstant(4, MVT::i32));
8614     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8615                                  LD->getPointerInfo(), LD->isVolatile(),
8616                                  LD->isNonTemporal(), LD->isInvariant(),
8617                                  std::min(4U, LD->getAlignment() / 2));
8618
8619     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8620     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8621       std::swap (NewLD1, NewLD2);
8622     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8623     return Result;
8624   }
8625
8626   return SDValue();
8627 }
8628
8629 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8630 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8631 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8632   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8633   SDValue Op0 = N->getOperand(0);
8634   SDValue Op1 = N->getOperand(1);
8635   if (Op0.getOpcode() == ISD::BITCAST)
8636     Op0 = Op0.getOperand(0);
8637   if (Op1.getOpcode() == ISD::BITCAST)
8638     Op1 = Op1.getOperand(0);
8639   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8640       Op0.getNode() == Op1.getNode() &&
8641       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8642     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8643                        N->getValueType(0), Op0.getOperand(0));
8644   return SDValue();
8645 }
8646
8647 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8648 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8649 /// i64 vector to have f64 elements, since the value can then be loaded
8650 /// directly into a VFP register.
8651 static bool hasNormalLoadOperand(SDNode *N) {
8652   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8653   for (unsigned i = 0; i < NumElts; ++i) {
8654     SDNode *Elt = N->getOperand(i).getNode();
8655     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8656       return true;
8657   }
8658   return false;
8659 }
8660
8661 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8662 /// ISD::BUILD_VECTOR.
8663 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8664                                           TargetLowering::DAGCombinerInfo &DCI,
8665                                           const ARMSubtarget *Subtarget) {
8666   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8667   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8668   // into a pair of GPRs, which is fine when the value is used as a scalar,
8669   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8670   SelectionDAG &DAG = DCI.DAG;
8671   if (N->getNumOperands() == 2) {
8672     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8673     if (RV.getNode())
8674       return RV;
8675   }
8676
8677   // Load i64 elements as f64 values so that type legalization does not split
8678   // them up into i32 values.
8679   EVT VT = N->getValueType(0);
8680   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8681     return SDValue();
8682   SDLoc dl(N);
8683   SmallVector<SDValue, 8> Ops;
8684   unsigned NumElts = VT.getVectorNumElements();
8685   for (unsigned i = 0; i < NumElts; ++i) {
8686     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8687     Ops.push_back(V);
8688     // Make the DAGCombiner fold the bitcast.
8689     DCI.AddToWorklist(V.getNode());
8690   }
8691   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8692   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8693   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8694 }
8695
8696 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8697 static SDValue
8698 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8699   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8700   // At that time, we may have inserted bitcasts from integer to float.
8701   // If these bitcasts have survived DAGCombine, change the lowering of this
8702   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8703   // force to use floating point types.
8704
8705   // Make sure we can change the type of the vector.
8706   // This is possible iff:
8707   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8708   //    1.1. Vector is used only once.
8709   //    1.2. Use is a bit convert to an integer type.
8710   // 2. The size of its operands are 32-bits (64-bits are not legal).
8711   EVT VT = N->getValueType(0);
8712   EVT EltVT = VT.getVectorElementType();
8713
8714   // Check 1.1. and 2.
8715   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8716     return SDValue();
8717
8718   // By construction, the input type must be float.
8719   assert(EltVT == MVT::f32 && "Unexpected type!");
8720
8721   // Check 1.2.
8722   SDNode *Use = *N->use_begin();
8723   if (Use->getOpcode() != ISD::BITCAST ||
8724       Use->getValueType(0).isFloatingPoint())
8725     return SDValue();
8726
8727   // Check profitability.
8728   // Model is, if more than half of the relevant operands are bitcast from
8729   // i32, turn the build_vector into a sequence of insert_vector_elt.
8730   // Relevant operands are everything that is not statically
8731   // (i.e., at compile time) bitcasted.
8732   unsigned NumOfBitCastedElts = 0;
8733   unsigned NumElts = VT.getVectorNumElements();
8734   unsigned NumOfRelevantElts = NumElts;
8735   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8736     SDValue Elt = N->getOperand(Idx);
8737     if (Elt->getOpcode() == ISD::BITCAST) {
8738       // Assume only bit cast to i32 will go away.
8739       if (Elt->getOperand(0).getValueType() == MVT::i32)
8740         ++NumOfBitCastedElts;
8741     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8742       // Constants are statically casted, thus do not count them as
8743       // relevant operands.
8744       --NumOfRelevantElts;
8745   }
8746
8747   // Check if more than half of the elements require a non-free bitcast.
8748   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8749     return SDValue();
8750
8751   SelectionDAG &DAG = DCI.DAG;
8752   // Create the new vector type.
8753   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8754   // Check if the type is legal.
8755   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8756   if (!TLI.isTypeLegal(VecVT))
8757     return SDValue();
8758
8759   // Combine:
8760   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8761   // => BITCAST INSERT_VECTOR_ELT
8762   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8763   //                      (BITCAST EN), N.
8764   SDValue Vec = DAG.getUNDEF(VecVT);
8765   SDLoc dl(N);
8766   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8767     SDValue V = N->getOperand(Idx);
8768     if (V.getOpcode() == ISD::UNDEF)
8769       continue;
8770     if (V.getOpcode() == ISD::BITCAST &&
8771         V->getOperand(0).getValueType() == MVT::i32)
8772       // Fold obvious case.
8773       V = V.getOperand(0);
8774     else {
8775       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8776       // Make the DAGCombiner fold the bitcasts.
8777       DCI.AddToWorklist(V.getNode());
8778     }
8779     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8780     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8781   }
8782   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8783   // Make the DAGCombiner fold the bitcasts.
8784   DCI.AddToWorklist(Vec.getNode());
8785   return Vec;
8786 }
8787
8788 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8789 /// ISD::INSERT_VECTOR_ELT.
8790 static SDValue PerformInsertEltCombine(SDNode *N,
8791                                        TargetLowering::DAGCombinerInfo &DCI) {
8792   // Bitcast an i64 load inserted into a vector to f64.
8793   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8794   EVT VT = N->getValueType(0);
8795   SDNode *Elt = N->getOperand(1).getNode();
8796   if (VT.getVectorElementType() != MVT::i64 ||
8797       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8798     return SDValue();
8799
8800   SelectionDAG &DAG = DCI.DAG;
8801   SDLoc dl(N);
8802   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8803                                  VT.getVectorNumElements());
8804   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8805   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8806   // Make the DAGCombiner fold the bitcasts.
8807   DCI.AddToWorklist(Vec.getNode());
8808   DCI.AddToWorklist(V.getNode());
8809   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8810                                Vec, V, N->getOperand(2));
8811   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8812 }
8813
8814 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8815 /// ISD::VECTOR_SHUFFLE.
8816 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8817   // The LLVM shufflevector instruction does not require the shuffle mask
8818   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8819   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8820   // operands do not match the mask length, they are extended by concatenating
8821   // them with undef vectors.  That is probably the right thing for other
8822   // targets, but for NEON it is better to concatenate two double-register
8823   // size vector operands into a single quad-register size vector.  Do that
8824   // transformation here:
8825   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8826   //   shuffle(concat(v1, v2), undef)
8827   SDValue Op0 = N->getOperand(0);
8828   SDValue Op1 = N->getOperand(1);
8829   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8830       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8831       Op0.getNumOperands() != 2 ||
8832       Op1.getNumOperands() != 2)
8833     return SDValue();
8834   SDValue Concat0Op1 = Op0.getOperand(1);
8835   SDValue Concat1Op1 = Op1.getOperand(1);
8836   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8837       Concat1Op1.getOpcode() != ISD::UNDEF)
8838     return SDValue();
8839   // Skip the transformation if any of the types are illegal.
8840   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8841   EVT VT = N->getValueType(0);
8842   if (!TLI.isTypeLegal(VT) ||
8843       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8844       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8845     return SDValue();
8846
8847   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8848                                   Op0.getOperand(0), Op1.getOperand(0));
8849   // Translate the shuffle mask.
8850   SmallVector<int, 16> NewMask;
8851   unsigned NumElts = VT.getVectorNumElements();
8852   unsigned HalfElts = NumElts/2;
8853   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8854   for (unsigned n = 0; n < NumElts; ++n) {
8855     int MaskElt = SVN->getMaskElt(n);
8856     int NewElt = -1;
8857     if (MaskElt < (int)HalfElts)
8858       NewElt = MaskElt;
8859     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8860       NewElt = HalfElts + MaskElt - NumElts;
8861     NewMask.push_back(NewElt);
8862   }
8863   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8864                               DAG.getUNDEF(VT), NewMask.data());
8865 }
8866
8867 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8868 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8869 /// base address updates.
8870 /// For generic load/stores, the memory type is assumed to be a vector.
8871 /// The caller is assumed to have checked legality.
8872 static SDValue CombineBaseUpdate(SDNode *N,
8873                                  TargetLowering::DAGCombinerInfo &DCI) {
8874   SelectionDAG &DAG = DCI.DAG;
8875   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8876                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8877   const bool isStore = N->getOpcode() == ISD::STORE;
8878   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8879   SDValue Addr = N->getOperand(AddrOpIdx);
8880   MemSDNode *MemN = cast<MemSDNode>(N);
8881
8882   // Search for a use of the address operand that is an increment.
8883   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8884          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8885     SDNode *User = *UI;
8886     if (User->getOpcode() != ISD::ADD ||
8887         UI.getUse().getResNo() != Addr.getResNo())
8888       continue;
8889
8890     // Check that the add is independent of the load/store.  Otherwise, folding
8891     // it would create a cycle.
8892     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8893       continue;
8894
8895     // Find the new opcode for the updating load/store.
8896     bool isLoadOp = true;
8897     bool isLaneOp = false;
8898     unsigned NewOpc = 0;
8899     unsigned NumVecs = 0;
8900     if (isIntrinsic) {
8901       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8902       switch (IntNo) {
8903       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8904       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8905         NumVecs = 1; break;
8906       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8907         NumVecs = 2; break;
8908       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8909         NumVecs = 3; break;
8910       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8911         NumVecs = 4; break;
8912       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8913         NumVecs = 2; isLaneOp = true; break;
8914       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8915         NumVecs = 3; isLaneOp = true; break;
8916       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8917         NumVecs = 4; isLaneOp = true; break;
8918       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8919         NumVecs = 1; isLoadOp = false; break;
8920       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8921         NumVecs = 2; isLoadOp = false; break;
8922       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8923         NumVecs = 3; isLoadOp = false; break;
8924       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8925         NumVecs = 4; isLoadOp = false; break;
8926       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8927         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8928       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8929         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8930       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8931         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8932       }
8933     } else {
8934       isLaneOp = true;
8935       switch (N->getOpcode()) {
8936       default: llvm_unreachable("unexpected opcode for Neon base update");
8937       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8938       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8939       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8940       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
8941         NumVecs = 1; isLaneOp = false; break;
8942       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
8943         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8944       }
8945     }
8946
8947     // Find the size of memory referenced by the load/store.
8948     EVT VecTy;
8949     if (isLoadOp) {
8950       VecTy = N->getValueType(0);
8951     } else if (isIntrinsic) {
8952       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8953     } else {
8954       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8955       VecTy = N->getOperand(1).getValueType();
8956     }
8957
8958     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8959     if (isLaneOp)
8960       NumBytes /= VecTy.getVectorNumElements();
8961
8962     // If the increment is a constant, it must match the memory ref size.
8963     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8964     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8965       uint64_t IncVal = CInc->getZExtValue();
8966       if (IncVal != NumBytes)
8967         continue;
8968     } else if (NumBytes >= 3 * 16) {
8969       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8970       // separate instructions that make it harder to use a non-constant update.
8971       continue;
8972     }
8973
8974     // OK, we found an ADD we can fold into the base update.
8975     // Now, create a _UPD node, taking care of not breaking alignment.
8976
8977     EVT AlignedVecTy = VecTy;
8978     unsigned Alignment = MemN->getAlignment();
8979
8980     // If this is a less-than-standard-aligned load/store, change the type to
8981     // match the standard alignment.
8982     // The alignment is overlooked when selecting _UPD variants; and it's
8983     // easier to introduce bitcasts here than fix that.
8984     // There are 3 ways to get to this base-update combine:
8985     // - intrinsics: they are assumed to be properly aligned (to the standard
8986     //   alignment of the memory type), so we don't need to do anything.
8987     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
8988     //   intrinsics, so, likewise, there's nothing to do.
8989     // - generic load/store instructions: the alignment is specified as an
8990     //   explicit operand, rather than implicitly as the standard alignment
8991     //   of the memory type (like the intrisics).  We need to change the
8992     //   memory type to match the explicit alignment.  That way, we don't
8993     //   generate non-standard-aligned ARMISD::VLDx nodes.
8994     if (isa<LSBaseSDNode>(N)) {
8995       if (Alignment == 0)
8996         Alignment = 1;
8997       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
8998         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
8999         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9000         assert(!isLaneOp && "Unexpected generic load/store lane.");
9001         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9002         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9003       }
9004       // Don't set an explicit alignment on regular load/stores that we want
9005       // to transform to VLD/VST 1_UPD nodes.
9006       // This matches the behavior of regular load/stores, which only get an
9007       // explicit alignment if the MMO alignment is larger than the standard
9008       // alignment of the memory type.
9009       // Intrinsics, however, always get an explicit alignment, set to the
9010       // alignment of the MMO.
9011       Alignment = 1;
9012     }
9013
9014     // Create the new updating load/store node.
9015     // First, create an SDVTList for the new updating node's results.
9016     EVT Tys[6];
9017     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9018     unsigned n;
9019     for (n = 0; n < NumResultVecs; ++n)
9020       Tys[n] = AlignedVecTy;
9021     Tys[n++] = MVT::i32;
9022     Tys[n] = MVT::Other;
9023     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9024
9025     // Then, gather the new node's operands.
9026     SmallVector<SDValue, 8> Ops;
9027     Ops.push_back(N->getOperand(0)); // incoming chain
9028     Ops.push_back(N->getOperand(AddrOpIdx));
9029     Ops.push_back(Inc);
9030
9031     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9032       // Try to match the intrinsic's signature
9033       Ops.push_back(StN->getValue());
9034     } else {
9035       // Loads (and of course intrinsics) match the intrinsics' signature,
9036       // so just add all but the alignment operand.
9037       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9038         Ops.push_back(N->getOperand(i));
9039     }
9040
9041     // For all node types, the alignment operand is always the last one.
9042     Ops.push_back(DAG.getConstant(Alignment, MVT::i32));
9043
9044     // If this is a non-standard-aligned STORE, the penultimate operand is the
9045     // stored value.  Bitcast it to the aligned type.
9046     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9047       SDValue &StVal = Ops[Ops.size()-2];
9048       StVal = DAG.getNode(ISD::BITCAST, SDLoc(N), AlignedVecTy, StVal);
9049     }
9050
9051     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9052                                            Ops, AlignedVecTy,
9053                                            MemN->getMemOperand());
9054
9055     // Update the uses.
9056     SmallVector<SDValue, 5> NewResults;
9057     for (unsigned i = 0; i < NumResultVecs; ++i)
9058       NewResults.push_back(SDValue(UpdN.getNode(), i));
9059
9060     // If this is an non-standard-aligned LOAD, the first result is the loaded
9061     // value.  Bitcast it to the expected result type.
9062     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9063       SDValue &LdVal = NewResults[0];
9064       LdVal = DAG.getNode(ISD::BITCAST, SDLoc(N), VecTy, LdVal);
9065     }
9066
9067     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9068     DCI.CombineTo(N, NewResults);
9069     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9070
9071     break;
9072   }
9073   return SDValue();
9074 }
9075
9076 static SDValue PerformVLDCombine(SDNode *N,
9077                                  TargetLowering::DAGCombinerInfo &DCI) {
9078   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9079     return SDValue();
9080
9081   return CombineBaseUpdate(N, DCI);
9082 }
9083
9084 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9085 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9086 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9087 /// return true.
9088 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9089   SelectionDAG &DAG = DCI.DAG;
9090   EVT VT = N->getValueType(0);
9091   // vldN-dup instructions only support 64-bit vectors for N > 1.
9092   if (!VT.is64BitVector())
9093     return false;
9094
9095   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9096   SDNode *VLD = N->getOperand(0).getNode();
9097   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9098     return false;
9099   unsigned NumVecs = 0;
9100   unsigned NewOpc = 0;
9101   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9102   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9103     NumVecs = 2;
9104     NewOpc = ARMISD::VLD2DUP;
9105   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9106     NumVecs = 3;
9107     NewOpc = ARMISD::VLD3DUP;
9108   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9109     NumVecs = 4;
9110     NewOpc = ARMISD::VLD4DUP;
9111   } else {
9112     return false;
9113   }
9114
9115   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9116   // numbers match the load.
9117   unsigned VLDLaneNo =
9118     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9119   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9120        UI != UE; ++UI) {
9121     // Ignore uses of the chain result.
9122     if (UI.getUse().getResNo() == NumVecs)
9123       continue;
9124     SDNode *User = *UI;
9125     if (User->getOpcode() != ARMISD::VDUPLANE ||
9126         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9127       return false;
9128   }
9129
9130   // Create the vldN-dup node.
9131   EVT Tys[5];
9132   unsigned n;
9133   for (n = 0; n < NumVecs; ++n)
9134     Tys[n] = VT;
9135   Tys[n] = MVT::Other;
9136   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9137   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9138   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9139   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9140                                            Ops, VLDMemInt->getMemoryVT(),
9141                                            VLDMemInt->getMemOperand());
9142
9143   // Update the uses.
9144   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9145        UI != UE; ++UI) {
9146     unsigned ResNo = UI.getUse().getResNo();
9147     // Ignore uses of the chain result.
9148     if (ResNo == NumVecs)
9149       continue;
9150     SDNode *User = *UI;
9151     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9152   }
9153
9154   // Now the vldN-lane intrinsic is dead except for its chain result.
9155   // Update uses of the chain.
9156   std::vector<SDValue> VLDDupResults;
9157   for (unsigned n = 0; n < NumVecs; ++n)
9158     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9159   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9160   DCI.CombineTo(VLD, VLDDupResults);
9161
9162   return true;
9163 }
9164
9165 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9166 /// ARMISD::VDUPLANE.
9167 static SDValue PerformVDUPLANECombine(SDNode *N,
9168                                       TargetLowering::DAGCombinerInfo &DCI) {
9169   SDValue Op = N->getOperand(0);
9170
9171   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9172   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9173   if (CombineVLDDUP(N, DCI))
9174     return SDValue(N, 0);
9175
9176   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9177   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9178   while (Op.getOpcode() == ISD::BITCAST)
9179     Op = Op.getOperand(0);
9180   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9181     return SDValue();
9182
9183   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9184   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9185   // The canonical VMOV for a zero vector uses a 32-bit element size.
9186   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9187   unsigned EltBits;
9188   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9189     EltSize = 8;
9190   EVT VT = N->getValueType(0);
9191   if (EltSize > VT.getVectorElementType().getSizeInBits())
9192     return SDValue();
9193
9194   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9195 }
9196
9197 static SDValue PerformLOADCombine(SDNode *N,
9198                                   TargetLowering::DAGCombinerInfo &DCI) {
9199   EVT VT = N->getValueType(0);
9200
9201   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9202   if (ISD::isNormalLoad(N) && VT.isVector() &&
9203       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9204     return CombineBaseUpdate(N, DCI);
9205
9206   return SDValue();
9207 }
9208
9209 /// PerformSTORECombine - Target-specific dag combine xforms for
9210 /// ISD::STORE.
9211 static SDValue PerformSTORECombine(SDNode *N,
9212                                    TargetLowering::DAGCombinerInfo &DCI) {
9213   StoreSDNode *St = cast<StoreSDNode>(N);
9214   if (St->isVolatile())
9215     return SDValue();
9216
9217   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9218   // pack all of the elements in one place.  Next, store to memory in fewer
9219   // chunks.
9220   SDValue StVal = St->getValue();
9221   EVT VT = StVal.getValueType();
9222   if (St->isTruncatingStore() && VT.isVector()) {
9223     SelectionDAG &DAG = DCI.DAG;
9224     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9225     EVT StVT = St->getMemoryVT();
9226     unsigned NumElems = VT.getVectorNumElements();
9227     assert(StVT != VT && "Cannot truncate to the same type");
9228     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9229     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9230
9231     // From, To sizes and ElemCount must be pow of two
9232     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9233
9234     // We are going to use the original vector elt for storing.
9235     // Accumulated smaller vector elements must be a multiple of the store size.
9236     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9237
9238     unsigned SizeRatio  = FromEltSz / ToEltSz;
9239     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9240
9241     // Create a type on which we perform the shuffle.
9242     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9243                                      NumElems*SizeRatio);
9244     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9245
9246     SDLoc DL(St);
9247     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9248     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9249     for (unsigned i = 0; i < NumElems; ++i)
9250       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9251
9252     // Can't shuffle using an illegal type.
9253     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9254
9255     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9256                                 DAG.getUNDEF(WideVec.getValueType()),
9257                                 ShuffleVec.data());
9258     // At this point all of the data is stored at the bottom of the
9259     // register. We now need to save it to mem.
9260
9261     // Find the largest store unit
9262     MVT StoreType = MVT::i8;
9263     for (MVT Tp : MVT::integer_valuetypes()) {
9264       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9265         StoreType = Tp;
9266     }
9267     // Didn't find a legal store type.
9268     if (!TLI.isTypeLegal(StoreType))
9269       return SDValue();
9270
9271     // Bitcast the original vector into a vector of store-size units
9272     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9273             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9274     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9275     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9276     SmallVector<SDValue, 8> Chains;
9277     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9278                                         TLI.getPointerTy());
9279     SDValue BasePtr = St->getBasePtr();
9280
9281     // Perform one or more big stores into memory.
9282     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9283     for (unsigned I = 0; I < E; I++) {
9284       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9285                                    StoreType, ShuffWide,
9286                                    DAG.getIntPtrConstant(I));
9287       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9288                                 St->getPointerInfo(), St->isVolatile(),
9289                                 St->isNonTemporal(), St->getAlignment());
9290       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9291                             Increment);
9292       Chains.push_back(Ch);
9293     }
9294     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9295   }
9296
9297   if (!ISD::isNormalStore(St))
9298     return SDValue();
9299
9300   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9301   // ARM stores of arguments in the same cache line.
9302   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9303       StVal.getNode()->hasOneUse()) {
9304     SelectionDAG  &DAG = DCI.DAG;
9305     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9306     SDLoc DL(St);
9307     SDValue BasePtr = St->getBasePtr();
9308     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9309                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9310                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9311                                   St->isNonTemporal(), St->getAlignment());
9312
9313     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9314                                     DAG.getConstant(4, MVT::i32));
9315     return DAG.getStore(NewST1.getValue(0), DL,
9316                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9317                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9318                         St->isNonTemporal(),
9319                         std::min(4U, St->getAlignment() / 2));
9320   }
9321
9322   if (StVal.getValueType() == MVT::i64 &&
9323       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9324
9325     // Bitcast an i64 store extracted from a vector to f64.
9326     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9327     SelectionDAG &DAG = DCI.DAG;
9328     SDLoc dl(StVal);
9329     SDValue IntVec = StVal.getOperand(0);
9330     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9331                                    IntVec.getValueType().getVectorNumElements());
9332     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9333     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9334                                  Vec, StVal.getOperand(1));
9335     dl = SDLoc(N);
9336     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9337     // Make the DAGCombiner fold the bitcasts.
9338     DCI.AddToWorklist(Vec.getNode());
9339     DCI.AddToWorklist(ExtElt.getNode());
9340     DCI.AddToWorklist(V.getNode());
9341     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9342                         St->getPointerInfo(), St->isVolatile(),
9343                         St->isNonTemporal(), St->getAlignment(),
9344                         St->getAAInfo());
9345   }
9346
9347   // If this is a legal vector store, try to combine it into a VST1_UPD.
9348   if (ISD::isNormalStore(N) && VT.isVector() &&
9349       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9350     return CombineBaseUpdate(N, DCI);
9351
9352   return SDValue();
9353 }
9354
9355 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9356 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9357 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9358 {
9359   integerPart cN;
9360   integerPart c0 = 0;
9361   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9362        I != E; I++) {
9363     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9364     if (!C)
9365       return false;
9366
9367     bool isExact;
9368     APFloat APF = C->getValueAPF();
9369     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9370         != APFloat::opOK || !isExact)
9371       return false;
9372
9373     c0 = (I == 0) ? cN : c0;
9374     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9375       return false;
9376   }
9377   C = c0;
9378   return true;
9379 }
9380
9381 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9382 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9383 /// when the VMUL has a constant operand that is a power of 2.
9384 ///
9385 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9386 ///  vmul.f32        d16, d17, d16
9387 ///  vcvt.s32.f32    d16, d16
9388 /// becomes:
9389 ///  vcvt.s32.f32    d16, d16, #3
9390 static SDValue PerformVCVTCombine(SDNode *N,
9391                                   TargetLowering::DAGCombinerInfo &DCI,
9392                                   const ARMSubtarget *Subtarget) {
9393   SelectionDAG &DAG = DCI.DAG;
9394   SDValue Op = N->getOperand(0);
9395
9396   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9397       Op.getOpcode() != ISD::FMUL)
9398     return SDValue();
9399
9400   uint64_t C;
9401   SDValue N0 = Op->getOperand(0);
9402   SDValue ConstVec = Op->getOperand(1);
9403   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9404
9405   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9406       !isConstVecPow2(ConstVec, isSigned, C))
9407     return SDValue();
9408
9409   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9410   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9411   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9412   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9413       NumLanes > 4) {
9414     // These instructions only exist converting from f32 to i32. We can handle
9415     // smaller integers by generating an extra truncate, but larger ones would
9416     // be lossy. We also can't handle more then 4 lanes, since these intructions
9417     // only support v2i32/v4i32 types.
9418     return SDValue();
9419   }
9420
9421   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9422     Intrinsic::arm_neon_vcvtfp2fxu;
9423   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9424                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9425                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9426                                  DAG.getConstant(Log2_64(C), MVT::i32));
9427
9428   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9429     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9430
9431   return FixConv;
9432 }
9433
9434 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9435 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9436 /// when the VDIV has a constant operand that is a power of 2.
9437 ///
9438 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9439 ///  vcvt.f32.s32    d16, d16
9440 ///  vdiv.f32        d16, d17, d16
9441 /// becomes:
9442 ///  vcvt.f32.s32    d16, d16, #3
9443 static SDValue PerformVDIVCombine(SDNode *N,
9444                                   TargetLowering::DAGCombinerInfo &DCI,
9445                                   const ARMSubtarget *Subtarget) {
9446   SelectionDAG &DAG = DCI.DAG;
9447   SDValue Op = N->getOperand(0);
9448   unsigned OpOpcode = Op.getNode()->getOpcode();
9449
9450   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9451       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9452     return SDValue();
9453
9454   uint64_t C;
9455   SDValue ConstVec = N->getOperand(1);
9456   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9457
9458   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9459       !isConstVecPow2(ConstVec, isSigned, C))
9460     return SDValue();
9461
9462   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9463   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9464   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9465     // These instructions only exist converting from i32 to f32. We can handle
9466     // smaller integers by generating an extra extend, but larger ones would
9467     // be lossy.
9468     return SDValue();
9469   }
9470
9471   SDValue ConvInput = Op.getOperand(0);
9472   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9473   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9474     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9475                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9476                             ConvInput);
9477
9478   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9479     Intrinsic::arm_neon_vcvtfxu2fp;
9480   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9481                      Op.getValueType(),
9482                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9483                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9484 }
9485
9486 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9487 /// operand of a vector shift operation, where all the elements of the
9488 /// build_vector must have the same constant integer value.
9489 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9490   // Ignore bit_converts.
9491   while (Op.getOpcode() == ISD::BITCAST)
9492     Op = Op.getOperand(0);
9493   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9494   APInt SplatBits, SplatUndef;
9495   unsigned SplatBitSize;
9496   bool HasAnyUndefs;
9497   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9498                                       HasAnyUndefs, ElementBits) ||
9499       SplatBitSize > ElementBits)
9500     return false;
9501   Cnt = SplatBits.getSExtValue();
9502   return true;
9503 }
9504
9505 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9506 /// operand of a vector shift left operation.  That value must be in the range:
9507 ///   0 <= Value < ElementBits for a left shift; or
9508 ///   0 <= Value <= ElementBits for a long left shift.
9509 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9510   assert(VT.isVector() && "vector shift count is not a vector type");
9511   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9512   if (! getVShiftImm(Op, ElementBits, Cnt))
9513     return false;
9514   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9515 }
9516
9517 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9518 /// operand of a vector shift right operation.  For a shift opcode, the value
9519 /// is positive, but for an intrinsic the value count must be negative. The
9520 /// absolute value must be in the range:
9521 ///   1 <= |Value| <= ElementBits for a right shift; or
9522 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9523 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9524                          int64_t &Cnt) {
9525   assert(VT.isVector() && "vector shift count is not a vector type");
9526   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9527   if (! getVShiftImm(Op, ElementBits, Cnt))
9528     return false;
9529   if (isIntrinsic)
9530     Cnt = -Cnt;
9531   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9532 }
9533
9534 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9535 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9536   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9537   switch (IntNo) {
9538   default:
9539     // Don't do anything for most intrinsics.
9540     break;
9541
9542   // Vector shifts: check for immediate versions and lower them.
9543   // Note: This is done during DAG combining instead of DAG legalizing because
9544   // the build_vectors for 64-bit vector element shift counts are generally
9545   // not legal, and it is hard to see their values after they get legalized to
9546   // loads from a constant pool.
9547   case Intrinsic::arm_neon_vshifts:
9548   case Intrinsic::arm_neon_vshiftu:
9549   case Intrinsic::arm_neon_vrshifts:
9550   case Intrinsic::arm_neon_vrshiftu:
9551   case Intrinsic::arm_neon_vrshiftn:
9552   case Intrinsic::arm_neon_vqshifts:
9553   case Intrinsic::arm_neon_vqshiftu:
9554   case Intrinsic::arm_neon_vqshiftsu:
9555   case Intrinsic::arm_neon_vqshiftns:
9556   case Intrinsic::arm_neon_vqshiftnu:
9557   case Intrinsic::arm_neon_vqshiftnsu:
9558   case Intrinsic::arm_neon_vqrshiftns:
9559   case Intrinsic::arm_neon_vqrshiftnu:
9560   case Intrinsic::arm_neon_vqrshiftnsu: {
9561     EVT VT = N->getOperand(1).getValueType();
9562     int64_t Cnt;
9563     unsigned VShiftOpc = 0;
9564
9565     switch (IntNo) {
9566     case Intrinsic::arm_neon_vshifts:
9567     case Intrinsic::arm_neon_vshiftu:
9568       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9569         VShiftOpc = ARMISD::VSHL;
9570         break;
9571       }
9572       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9573         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9574                      ARMISD::VSHRs : ARMISD::VSHRu);
9575         break;
9576       }
9577       return SDValue();
9578
9579     case Intrinsic::arm_neon_vrshifts:
9580     case Intrinsic::arm_neon_vrshiftu:
9581       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9582         break;
9583       return SDValue();
9584
9585     case Intrinsic::arm_neon_vqshifts:
9586     case Intrinsic::arm_neon_vqshiftu:
9587       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9588         break;
9589       return SDValue();
9590
9591     case Intrinsic::arm_neon_vqshiftsu:
9592       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9593         break;
9594       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9595
9596     case Intrinsic::arm_neon_vrshiftn:
9597     case Intrinsic::arm_neon_vqshiftns:
9598     case Intrinsic::arm_neon_vqshiftnu:
9599     case Intrinsic::arm_neon_vqshiftnsu:
9600     case Intrinsic::arm_neon_vqrshiftns:
9601     case Intrinsic::arm_neon_vqrshiftnu:
9602     case Intrinsic::arm_neon_vqrshiftnsu:
9603       // Narrowing shifts require an immediate right shift.
9604       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9605         break;
9606       llvm_unreachable("invalid shift count for narrowing vector shift "
9607                        "intrinsic");
9608
9609     default:
9610       llvm_unreachable("unhandled vector shift");
9611     }
9612
9613     switch (IntNo) {
9614     case Intrinsic::arm_neon_vshifts:
9615     case Intrinsic::arm_neon_vshiftu:
9616       // Opcode already set above.
9617       break;
9618     case Intrinsic::arm_neon_vrshifts:
9619       VShiftOpc = ARMISD::VRSHRs; break;
9620     case Intrinsic::arm_neon_vrshiftu:
9621       VShiftOpc = ARMISD::VRSHRu; break;
9622     case Intrinsic::arm_neon_vrshiftn:
9623       VShiftOpc = ARMISD::VRSHRN; break;
9624     case Intrinsic::arm_neon_vqshifts:
9625       VShiftOpc = ARMISD::VQSHLs; break;
9626     case Intrinsic::arm_neon_vqshiftu:
9627       VShiftOpc = ARMISD::VQSHLu; break;
9628     case Intrinsic::arm_neon_vqshiftsu:
9629       VShiftOpc = ARMISD::VQSHLsu; break;
9630     case Intrinsic::arm_neon_vqshiftns:
9631       VShiftOpc = ARMISD::VQSHRNs; break;
9632     case Intrinsic::arm_neon_vqshiftnu:
9633       VShiftOpc = ARMISD::VQSHRNu; break;
9634     case Intrinsic::arm_neon_vqshiftnsu:
9635       VShiftOpc = ARMISD::VQSHRNsu; break;
9636     case Intrinsic::arm_neon_vqrshiftns:
9637       VShiftOpc = ARMISD::VQRSHRNs; break;
9638     case Intrinsic::arm_neon_vqrshiftnu:
9639       VShiftOpc = ARMISD::VQRSHRNu; break;
9640     case Intrinsic::arm_neon_vqrshiftnsu:
9641       VShiftOpc = ARMISD::VQRSHRNsu; break;
9642     }
9643
9644     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9645                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9646   }
9647
9648   case Intrinsic::arm_neon_vshiftins: {
9649     EVT VT = N->getOperand(1).getValueType();
9650     int64_t Cnt;
9651     unsigned VShiftOpc = 0;
9652
9653     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9654       VShiftOpc = ARMISD::VSLI;
9655     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9656       VShiftOpc = ARMISD::VSRI;
9657     else {
9658       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9659     }
9660
9661     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9662                        N->getOperand(1), N->getOperand(2),
9663                        DAG.getConstant(Cnt, MVT::i32));
9664   }
9665
9666   case Intrinsic::arm_neon_vqrshifts:
9667   case Intrinsic::arm_neon_vqrshiftu:
9668     // No immediate versions of these to check for.
9669     break;
9670   }
9671
9672   return SDValue();
9673 }
9674
9675 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9676 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9677 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9678 /// vector element shift counts are generally not legal, and it is hard to see
9679 /// their values after they get legalized to loads from a constant pool.
9680 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9681                                    const ARMSubtarget *ST) {
9682   EVT VT = N->getValueType(0);
9683   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9684     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9685     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9686     SDValue N1 = N->getOperand(1);
9687     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9688       SDValue N0 = N->getOperand(0);
9689       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9690           DAG.MaskedValueIsZero(N0.getOperand(0),
9691                                 APInt::getHighBitsSet(32, 16)))
9692         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9693     }
9694   }
9695
9696   // Nothing to be done for scalar shifts.
9697   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9698   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9699     return SDValue();
9700
9701   assert(ST->hasNEON() && "unexpected vector shift");
9702   int64_t Cnt;
9703
9704   switch (N->getOpcode()) {
9705   default: llvm_unreachable("unexpected shift opcode");
9706
9707   case ISD::SHL:
9708     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9709       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9710                          DAG.getConstant(Cnt, MVT::i32));
9711     break;
9712
9713   case ISD::SRA:
9714   case ISD::SRL:
9715     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9716       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9717                             ARMISD::VSHRs : ARMISD::VSHRu);
9718       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9719                          DAG.getConstant(Cnt, MVT::i32));
9720     }
9721   }
9722   return SDValue();
9723 }
9724
9725 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9726 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9727 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9728                                     const ARMSubtarget *ST) {
9729   SDValue N0 = N->getOperand(0);
9730
9731   // Check for sign- and zero-extensions of vector extract operations of 8-
9732   // and 16-bit vector elements.  NEON supports these directly.  They are
9733   // handled during DAG combining because type legalization will promote them
9734   // to 32-bit types and it is messy to recognize the operations after that.
9735   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9736     SDValue Vec = N0.getOperand(0);
9737     SDValue Lane = N0.getOperand(1);
9738     EVT VT = N->getValueType(0);
9739     EVT EltVT = N0.getValueType();
9740     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9741
9742     if (VT == MVT::i32 &&
9743         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9744         TLI.isTypeLegal(Vec.getValueType()) &&
9745         isa<ConstantSDNode>(Lane)) {
9746
9747       unsigned Opc = 0;
9748       switch (N->getOpcode()) {
9749       default: llvm_unreachable("unexpected opcode");
9750       case ISD::SIGN_EXTEND:
9751         Opc = ARMISD::VGETLANEs;
9752         break;
9753       case ISD::ZERO_EXTEND:
9754       case ISD::ANY_EXTEND:
9755         Opc = ARMISD::VGETLANEu;
9756         break;
9757       }
9758       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9759     }
9760   }
9761
9762   return SDValue();
9763 }
9764
9765 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9766 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9767 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9768                                        const ARMSubtarget *ST) {
9769   // If the target supports NEON, try to use vmax/vmin instructions for f32
9770   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9771   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9772   // a NaN; only do the transformation when it matches that behavior.
9773
9774   // For now only do this when using NEON for FP operations; if using VFP, it
9775   // is not obvious that the benefit outweighs the cost of switching to the
9776   // NEON pipeline.
9777   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9778       N->getValueType(0) != MVT::f32)
9779     return SDValue();
9780
9781   SDValue CondLHS = N->getOperand(0);
9782   SDValue CondRHS = N->getOperand(1);
9783   SDValue LHS = N->getOperand(2);
9784   SDValue RHS = N->getOperand(3);
9785   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9786
9787   unsigned Opcode = 0;
9788   bool IsReversed;
9789   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9790     IsReversed = false; // x CC y ? x : y
9791   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9792     IsReversed = true ; // x CC y ? y : x
9793   } else {
9794     return SDValue();
9795   }
9796
9797   bool IsUnordered;
9798   switch (CC) {
9799   default: break;
9800   case ISD::SETOLT:
9801   case ISD::SETOLE:
9802   case ISD::SETLT:
9803   case ISD::SETLE:
9804   case ISD::SETULT:
9805   case ISD::SETULE:
9806     // If LHS is NaN, an ordered comparison will be false and the result will
9807     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9808     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9809     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9810     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9811       break;
9812     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9813     // will return -0, so vmin can only be used for unsafe math or if one of
9814     // the operands is known to be nonzero.
9815     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9816         !DAG.getTarget().Options.UnsafeFPMath &&
9817         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9818       break;
9819     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9820     break;
9821
9822   case ISD::SETOGT:
9823   case ISD::SETOGE:
9824   case ISD::SETGT:
9825   case ISD::SETGE:
9826   case ISD::SETUGT:
9827   case ISD::SETUGE:
9828     // If LHS is NaN, an ordered comparison will be false and the result will
9829     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9830     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9831     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9832     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9833       break;
9834     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9835     // will return +0, so vmax can only be used for unsafe math or if one of
9836     // the operands is known to be nonzero.
9837     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9838         !DAG.getTarget().Options.UnsafeFPMath &&
9839         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9840       break;
9841     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9842     break;
9843   }
9844
9845   if (!Opcode)
9846     return SDValue();
9847   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9848 }
9849
9850 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9851 SDValue
9852 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9853   SDValue Cmp = N->getOperand(4);
9854   if (Cmp.getOpcode() != ARMISD::CMPZ)
9855     // Only looking at EQ and NE cases.
9856     return SDValue();
9857
9858   EVT VT = N->getValueType(0);
9859   SDLoc dl(N);
9860   SDValue LHS = Cmp.getOperand(0);
9861   SDValue RHS = Cmp.getOperand(1);
9862   SDValue FalseVal = N->getOperand(0);
9863   SDValue TrueVal = N->getOperand(1);
9864   SDValue ARMcc = N->getOperand(2);
9865   ARMCC::CondCodes CC =
9866     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9867
9868   // Simplify
9869   //   mov     r1, r0
9870   //   cmp     r1, x
9871   //   mov     r0, y
9872   //   moveq   r0, x
9873   // to
9874   //   cmp     r0, x
9875   //   movne   r0, y
9876   //
9877   //   mov     r1, r0
9878   //   cmp     r1, x
9879   //   mov     r0, x
9880   //   movne   r0, y
9881   // to
9882   //   cmp     r0, x
9883   //   movne   r0, y
9884   /// FIXME: Turn this into a target neutral optimization?
9885   SDValue Res;
9886   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9887     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9888                       N->getOperand(3), Cmp);
9889   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9890     SDValue ARMcc;
9891     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9892     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9893                       N->getOperand(3), NewCmp);
9894   }
9895
9896   if (Res.getNode()) {
9897     APInt KnownZero, KnownOne;
9898     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9899     // Capture demanded bits information that would be otherwise lost.
9900     if (KnownZero == 0xfffffffe)
9901       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9902                         DAG.getValueType(MVT::i1));
9903     else if (KnownZero == 0xffffff00)
9904       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9905                         DAG.getValueType(MVT::i8));
9906     else if (KnownZero == 0xffff0000)
9907       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9908                         DAG.getValueType(MVT::i16));
9909   }
9910
9911   return Res;
9912 }
9913
9914 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9915                                              DAGCombinerInfo &DCI) const {
9916   switch (N->getOpcode()) {
9917   default: break;
9918   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9919   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9920   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9921   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9922   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9923   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9924   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9925   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9926   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9927   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9928   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9929   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9930   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9931   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9932   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9933   case ISD::FP_TO_SINT:
9934   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9935   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9936   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9937   case ISD::SHL:
9938   case ISD::SRA:
9939   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9940   case ISD::SIGN_EXTEND:
9941   case ISD::ZERO_EXTEND:
9942   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9943   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9944   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9945   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
9946   case ARMISD::VLD2DUP:
9947   case ARMISD::VLD3DUP:
9948   case ARMISD::VLD4DUP:
9949     return PerformVLDCombine(N, DCI);
9950   case ARMISD::BUILD_VECTOR:
9951     return PerformARMBUILD_VECTORCombine(N, DCI);
9952   case ISD::INTRINSIC_VOID:
9953   case ISD::INTRINSIC_W_CHAIN:
9954     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9955     case Intrinsic::arm_neon_vld1:
9956     case Intrinsic::arm_neon_vld2:
9957     case Intrinsic::arm_neon_vld3:
9958     case Intrinsic::arm_neon_vld4:
9959     case Intrinsic::arm_neon_vld2lane:
9960     case Intrinsic::arm_neon_vld3lane:
9961     case Intrinsic::arm_neon_vld4lane:
9962     case Intrinsic::arm_neon_vst1:
9963     case Intrinsic::arm_neon_vst2:
9964     case Intrinsic::arm_neon_vst3:
9965     case Intrinsic::arm_neon_vst4:
9966     case Intrinsic::arm_neon_vst2lane:
9967     case Intrinsic::arm_neon_vst3lane:
9968     case Intrinsic::arm_neon_vst4lane:
9969       return PerformVLDCombine(N, DCI);
9970     default: break;
9971     }
9972     break;
9973   }
9974   return SDValue();
9975 }
9976
9977 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9978                                                           EVT VT) const {
9979   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9980 }
9981
9982 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9983                                                        unsigned,
9984                                                        unsigned,
9985                                                        bool *Fast) const {
9986   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9987   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9988
9989   switch (VT.getSimpleVT().SimpleTy) {
9990   default:
9991     return false;
9992   case MVT::i8:
9993   case MVT::i16:
9994   case MVT::i32: {
9995     // Unaligned access can use (for example) LRDB, LRDH, LDR
9996     if (AllowsUnaligned) {
9997       if (Fast)
9998         *Fast = Subtarget->hasV7Ops();
9999       return true;
10000     }
10001     return false;
10002   }
10003   case MVT::f64:
10004   case MVT::v2f64: {
10005     // For any little-endian targets with neon, we can support unaligned ld/st
10006     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10007     // A big-endian target may also explicitly support unaligned accesses
10008     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10009       if (Fast)
10010         *Fast = true;
10011       return true;
10012     }
10013     return false;
10014   }
10015   }
10016 }
10017
10018 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10019                        unsigned AlignCheck) {
10020   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10021           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10022 }
10023
10024 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10025                                            unsigned DstAlign, unsigned SrcAlign,
10026                                            bool IsMemset, bool ZeroMemset,
10027                                            bool MemcpyStrSrc,
10028                                            MachineFunction &MF) const {
10029   const Function *F = MF.getFunction();
10030
10031   // See if we can use NEON instructions for this...
10032   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10033       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10034     bool Fast;
10035     if (Size >= 16 &&
10036         (memOpAlign(SrcAlign, DstAlign, 16) ||
10037          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10038       return MVT::v2f64;
10039     } else if (Size >= 8 &&
10040                (memOpAlign(SrcAlign, DstAlign, 8) ||
10041                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10042                  Fast))) {
10043       return MVT::f64;
10044     }
10045   }
10046
10047   // Lowering to i32/i16 if the size permits.
10048   if (Size >= 4)
10049     return MVT::i32;
10050   else if (Size >= 2)
10051     return MVT::i16;
10052
10053   // Let the target-independent logic figure it out.
10054   return MVT::Other;
10055 }
10056
10057 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10058   if (Val.getOpcode() != ISD::LOAD)
10059     return false;
10060
10061   EVT VT1 = Val.getValueType();
10062   if (!VT1.isSimple() || !VT1.isInteger() ||
10063       !VT2.isSimple() || !VT2.isInteger())
10064     return false;
10065
10066   switch (VT1.getSimpleVT().SimpleTy) {
10067   default: break;
10068   case MVT::i1:
10069   case MVT::i8:
10070   case MVT::i16:
10071     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10072     return true;
10073   }
10074
10075   return false;
10076 }
10077
10078 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10079   EVT VT = ExtVal.getValueType();
10080
10081   if (!isTypeLegal(VT))
10082     return false;
10083
10084   // Don't create a loadext if we can fold the extension into a wide/long
10085   // instruction.
10086   // If there's more than one user instruction, the loadext is desirable no
10087   // matter what.  There can be two uses by the same instruction.
10088   if (ExtVal->use_empty() ||
10089       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10090     return true;
10091
10092   SDNode *U = *ExtVal->use_begin();
10093   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10094        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10095     return false;
10096
10097   return true;
10098 }
10099
10100 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10101   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10102     return false;
10103
10104   if (!isTypeLegal(EVT::getEVT(Ty1)))
10105     return false;
10106
10107   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10108
10109   // Assuming the caller doesn't have a zeroext or signext return parameter,
10110   // truncation all the way down to i1 is valid.
10111   return true;
10112 }
10113
10114
10115 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10116   if (V < 0)
10117     return false;
10118
10119   unsigned Scale = 1;
10120   switch (VT.getSimpleVT().SimpleTy) {
10121   default: return false;
10122   case MVT::i1:
10123   case MVT::i8:
10124     // Scale == 1;
10125     break;
10126   case MVT::i16:
10127     // Scale == 2;
10128     Scale = 2;
10129     break;
10130   case MVT::i32:
10131     // Scale == 4;
10132     Scale = 4;
10133     break;
10134   }
10135
10136   if ((V & (Scale - 1)) != 0)
10137     return false;
10138   V /= Scale;
10139   return V == (V & ((1LL << 5) - 1));
10140 }
10141
10142 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10143                                       const ARMSubtarget *Subtarget) {
10144   bool isNeg = false;
10145   if (V < 0) {
10146     isNeg = true;
10147     V = - V;
10148   }
10149
10150   switch (VT.getSimpleVT().SimpleTy) {
10151   default: return false;
10152   case MVT::i1:
10153   case MVT::i8:
10154   case MVT::i16:
10155   case MVT::i32:
10156     // + imm12 or - imm8
10157     if (isNeg)
10158       return V == (V & ((1LL << 8) - 1));
10159     return V == (V & ((1LL << 12) - 1));
10160   case MVT::f32:
10161   case MVT::f64:
10162     // Same as ARM mode. FIXME: NEON?
10163     if (!Subtarget->hasVFP2())
10164       return false;
10165     if ((V & 3) != 0)
10166       return false;
10167     V >>= 2;
10168     return V == (V & ((1LL << 8) - 1));
10169   }
10170 }
10171
10172 /// isLegalAddressImmediate - Return true if the integer value can be used
10173 /// as the offset of the target addressing mode for load / store of the
10174 /// given type.
10175 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10176                                     const ARMSubtarget *Subtarget) {
10177   if (V == 0)
10178     return true;
10179
10180   if (!VT.isSimple())
10181     return false;
10182
10183   if (Subtarget->isThumb1Only())
10184     return isLegalT1AddressImmediate(V, VT);
10185   else if (Subtarget->isThumb2())
10186     return isLegalT2AddressImmediate(V, VT, Subtarget);
10187
10188   // ARM mode.
10189   if (V < 0)
10190     V = - V;
10191   switch (VT.getSimpleVT().SimpleTy) {
10192   default: return false;
10193   case MVT::i1:
10194   case MVT::i8:
10195   case MVT::i32:
10196     // +- imm12
10197     return V == (V & ((1LL << 12) - 1));
10198   case MVT::i16:
10199     // +- imm8
10200     return V == (V & ((1LL << 8) - 1));
10201   case MVT::f32:
10202   case MVT::f64:
10203     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10204       return false;
10205     if ((V & 3) != 0)
10206       return false;
10207     V >>= 2;
10208     return V == (V & ((1LL << 8) - 1));
10209   }
10210 }
10211
10212 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10213                                                       EVT VT) const {
10214   int Scale = AM.Scale;
10215   if (Scale < 0)
10216     return false;
10217
10218   switch (VT.getSimpleVT().SimpleTy) {
10219   default: return false;
10220   case MVT::i1:
10221   case MVT::i8:
10222   case MVT::i16:
10223   case MVT::i32:
10224     if (Scale == 1)
10225       return true;
10226     // r + r << imm
10227     Scale = Scale & ~1;
10228     return Scale == 2 || Scale == 4 || Scale == 8;
10229   case MVT::i64:
10230     // r + r
10231     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10232       return true;
10233     return false;
10234   case MVT::isVoid:
10235     // Note, we allow "void" uses (basically, uses that aren't loads or
10236     // stores), because arm allows folding a scale into many arithmetic
10237     // operations.  This should be made more precise and revisited later.
10238
10239     // Allow r << imm, but the imm has to be a multiple of two.
10240     if (Scale & 1) return false;
10241     return isPowerOf2_32(Scale);
10242   }
10243 }
10244
10245 /// isLegalAddressingMode - Return true if the addressing mode represented
10246 /// by AM is legal for this target, for a load/store of the specified type.
10247 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10248                                               Type *Ty) const {
10249   EVT VT = getValueType(Ty, true);
10250   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10251     return false;
10252
10253   // Can never fold addr of global into load/store.
10254   if (AM.BaseGV)
10255     return false;
10256
10257   switch (AM.Scale) {
10258   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10259     break;
10260   case 1:
10261     if (Subtarget->isThumb1Only())
10262       return false;
10263     // FALL THROUGH.
10264   default:
10265     // ARM doesn't support any R+R*scale+imm addr modes.
10266     if (AM.BaseOffs)
10267       return false;
10268
10269     if (!VT.isSimple())
10270       return false;
10271
10272     if (Subtarget->isThumb2())
10273       return isLegalT2ScaledAddressingMode(AM, VT);
10274
10275     int Scale = AM.Scale;
10276     switch (VT.getSimpleVT().SimpleTy) {
10277     default: return false;
10278     case MVT::i1:
10279     case MVT::i8:
10280     case MVT::i32:
10281       if (Scale < 0) Scale = -Scale;
10282       if (Scale == 1)
10283         return true;
10284       // r + r << imm
10285       return isPowerOf2_32(Scale & ~1);
10286     case MVT::i16:
10287     case MVT::i64:
10288       // r + r
10289       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10290         return true;
10291       return false;
10292
10293     case MVT::isVoid:
10294       // Note, we allow "void" uses (basically, uses that aren't loads or
10295       // stores), because arm allows folding a scale into many arithmetic
10296       // operations.  This should be made more precise and revisited later.
10297
10298       // Allow r << imm, but the imm has to be a multiple of two.
10299       if (Scale & 1) return false;
10300       return isPowerOf2_32(Scale);
10301     }
10302   }
10303   return true;
10304 }
10305
10306 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10307 /// icmp immediate, that is the target has icmp instructions which can compare
10308 /// a register against the immediate without having to materialize the
10309 /// immediate into a register.
10310 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10311   // Thumb2 and ARM modes can use cmn for negative immediates.
10312   if (!Subtarget->isThumb())
10313     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10314   if (Subtarget->isThumb2())
10315     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10316   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10317   return Imm >= 0 && Imm <= 255;
10318 }
10319
10320 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10321 /// *or sub* immediate, that is the target has add or sub instructions which can
10322 /// add a register with the immediate without having to materialize the
10323 /// immediate into a register.
10324 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10325   // Same encoding for add/sub, just flip the sign.
10326   int64_t AbsImm = llvm::abs64(Imm);
10327   if (!Subtarget->isThumb())
10328     return ARM_AM::getSOImmVal(AbsImm) != -1;
10329   if (Subtarget->isThumb2())
10330     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10331   // Thumb1 only has 8-bit unsigned immediate.
10332   return AbsImm >= 0 && AbsImm <= 255;
10333 }
10334
10335 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10336                                       bool isSEXTLoad, SDValue &Base,
10337                                       SDValue &Offset, bool &isInc,
10338                                       SelectionDAG &DAG) {
10339   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10340     return false;
10341
10342   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10343     // AddressingMode 3
10344     Base = Ptr->getOperand(0);
10345     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10346       int RHSC = (int)RHS->getZExtValue();
10347       if (RHSC < 0 && RHSC > -256) {
10348         assert(Ptr->getOpcode() == ISD::ADD);
10349         isInc = false;
10350         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10351         return true;
10352       }
10353     }
10354     isInc = (Ptr->getOpcode() == ISD::ADD);
10355     Offset = Ptr->getOperand(1);
10356     return true;
10357   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10358     // AddressingMode 2
10359     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10360       int RHSC = (int)RHS->getZExtValue();
10361       if (RHSC < 0 && RHSC > -0x1000) {
10362         assert(Ptr->getOpcode() == ISD::ADD);
10363         isInc = false;
10364         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10365         Base = Ptr->getOperand(0);
10366         return true;
10367       }
10368     }
10369
10370     if (Ptr->getOpcode() == ISD::ADD) {
10371       isInc = true;
10372       ARM_AM::ShiftOpc ShOpcVal=
10373         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10374       if (ShOpcVal != ARM_AM::no_shift) {
10375         Base = Ptr->getOperand(1);
10376         Offset = Ptr->getOperand(0);
10377       } else {
10378         Base = Ptr->getOperand(0);
10379         Offset = Ptr->getOperand(1);
10380       }
10381       return true;
10382     }
10383
10384     isInc = (Ptr->getOpcode() == ISD::ADD);
10385     Base = Ptr->getOperand(0);
10386     Offset = Ptr->getOperand(1);
10387     return true;
10388   }
10389
10390   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10391   return false;
10392 }
10393
10394 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10395                                      bool isSEXTLoad, SDValue &Base,
10396                                      SDValue &Offset, bool &isInc,
10397                                      SelectionDAG &DAG) {
10398   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10399     return false;
10400
10401   Base = Ptr->getOperand(0);
10402   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10403     int RHSC = (int)RHS->getZExtValue();
10404     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10405       assert(Ptr->getOpcode() == ISD::ADD);
10406       isInc = false;
10407       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10408       return true;
10409     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10410       isInc = Ptr->getOpcode() == ISD::ADD;
10411       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10412       return true;
10413     }
10414   }
10415
10416   return false;
10417 }
10418
10419 /// getPreIndexedAddressParts - returns true by value, base pointer and
10420 /// offset pointer and addressing mode by reference if the node's address
10421 /// can be legally represented as pre-indexed load / store address.
10422 bool
10423 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10424                                              SDValue &Offset,
10425                                              ISD::MemIndexedMode &AM,
10426                                              SelectionDAG &DAG) const {
10427   if (Subtarget->isThumb1Only())
10428     return false;
10429
10430   EVT VT;
10431   SDValue Ptr;
10432   bool isSEXTLoad = false;
10433   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10434     Ptr = LD->getBasePtr();
10435     VT  = LD->getMemoryVT();
10436     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10437   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10438     Ptr = ST->getBasePtr();
10439     VT  = ST->getMemoryVT();
10440   } else
10441     return false;
10442
10443   bool isInc;
10444   bool isLegal = false;
10445   if (Subtarget->isThumb2())
10446     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10447                                        Offset, isInc, DAG);
10448   else
10449     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10450                                         Offset, isInc, DAG);
10451   if (!isLegal)
10452     return false;
10453
10454   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10455   return true;
10456 }
10457
10458 /// getPostIndexedAddressParts - returns true by value, base pointer and
10459 /// offset pointer and addressing mode by reference if this node can be
10460 /// combined with a load / store to form a post-indexed load / store.
10461 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10462                                                    SDValue &Base,
10463                                                    SDValue &Offset,
10464                                                    ISD::MemIndexedMode &AM,
10465                                                    SelectionDAG &DAG) const {
10466   if (Subtarget->isThumb1Only())
10467     return false;
10468
10469   EVT VT;
10470   SDValue Ptr;
10471   bool isSEXTLoad = false;
10472   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10473     VT  = LD->getMemoryVT();
10474     Ptr = LD->getBasePtr();
10475     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10476   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10477     VT  = ST->getMemoryVT();
10478     Ptr = ST->getBasePtr();
10479   } else
10480     return false;
10481
10482   bool isInc;
10483   bool isLegal = false;
10484   if (Subtarget->isThumb2())
10485     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10486                                        isInc, DAG);
10487   else
10488     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10489                                         isInc, DAG);
10490   if (!isLegal)
10491     return false;
10492
10493   if (Ptr != Base) {
10494     // Swap base ptr and offset to catch more post-index load / store when
10495     // it's legal. In Thumb2 mode, offset must be an immediate.
10496     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10497         !Subtarget->isThumb2())
10498       std::swap(Base, Offset);
10499
10500     // Post-indexed load / store update the base pointer.
10501     if (Ptr != Base)
10502       return false;
10503   }
10504
10505   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10506   return true;
10507 }
10508
10509 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10510                                                       APInt &KnownZero,
10511                                                       APInt &KnownOne,
10512                                                       const SelectionDAG &DAG,
10513                                                       unsigned Depth) const {
10514   unsigned BitWidth = KnownOne.getBitWidth();
10515   KnownZero = KnownOne = APInt(BitWidth, 0);
10516   switch (Op.getOpcode()) {
10517   default: break;
10518   case ARMISD::ADDC:
10519   case ARMISD::ADDE:
10520   case ARMISD::SUBC:
10521   case ARMISD::SUBE:
10522     // These nodes' second result is a boolean
10523     if (Op.getResNo() == 0)
10524       break;
10525     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10526     break;
10527   case ARMISD::CMOV: {
10528     // Bits are known zero/one if known on the LHS and RHS.
10529     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10530     if (KnownZero == 0 && KnownOne == 0) return;
10531
10532     APInt KnownZeroRHS, KnownOneRHS;
10533     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10534     KnownZero &= KnownZeroRHS;
10535     KnownOne  &= KnownOneRHS;
10536     return;
10537   }
10538   case ISD::INTRINSIC_W_CHAIN: {
10539     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10540     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10541     switch (IntID) {
10542     default: return;
10543     case Intrinsic::arm_ldaex:
10544     case Intrinsic::arm_ldrex: {
10545       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10546       unsigned MemBits = VT.getScalarType().getSizeInBits();
10547       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10548       return;
10549     }
10550     }
10551   }
10552   }
10553 }
10554
10555 //===----------------------------------------------------------------------===//
10556 //                           ARM Inline Assembly Support
10557 //===----------------------------------------------------------------------===//
10558
10559 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10560   // Looking for "rev" which is V6+.
10561   if (!Subtarget->hasV6Ops())
10562     return false;
10563
10564   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10565   std::string AsmStr = IA->getAsmString();
10566   SmallVector<StringRef, 4> AsmPieces;
10567   SplitString(AsmStr, AsmPieces, ";\n");
10568
10569   switch (AsmPieces.size()) {
10570   default: return false;
10571   case 1:
10572     AsmStr = AsmPieces[0];
10573     AsmPieces.clear();
10574     SplitString(AsmStr, AsmPieces, " \t,");
10575
10576     // rev $0, $1
10577     if (AsmPieces.size() == 3 &&
10578         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10579         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10580       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10581       if (Ty && Ty->getBitWidth() == 32)
10582         return IntrinsicLowering::LowerToByteSwap(CI);
10583     }
10584     break;
10585   }
10586
10587   return false;
10588 }
10589
10590 /// getConstraintType - Given a constraint letter, return the type of
10591 /// constraint it is for this target.
10592 ARMTargetLowering::ConstraintType
10593 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10594   if (Constraint.size() == 1) {
10595     switch (Constraint[0]) {
10596     default:  break;
10597     case 'l': return C_RegisterClass;
10598     case 'w': return C_RegisterClass;
10599     case 'h': return C_RegisterClass;
10600     case 'x': return C_RegisterClass;
10601     case 't': return C_RegisterClass;
10602     case 'j': return C_Other; // Constant for movw.
10603       // An address with a single base register. Due to the way we
10604       // currently handle addresses it is the same as an 'r' memory constraint.
10605     case 'Q': return C_Memory;
10606     }
10607   } else if (Constraint.size() == 2) {
10608     switch (Constraint[0]) {
10609     default: break;
10610     // All 'U+' constraints are addresses.
10611     case 'U': return C_Memory;
10612     }
10613   }
10614   return TargetLowering::getConstraintType(Constraint);
10615 }
10616
10617 /// Examine constraint type and operand type and determine a weight value.
10618 /// This object must already have been set up with the operand type
10619 /// and the current alternative constraint selected.
10620 TargetLowering::ConstraintWeight
10621 ARMTargetLowering::getSingleConstraintMatchWeight(
10622     AsmOperandInfo &info, const char *constraint) const {
10623   ConstraintWeight weight = CW_Invalid;
10624   Value *CallOperandVal = info.CallOperandVal;
10625     // If we don't have a value, we can't do a match,
10626     // but allow it at the lowest weight.
10627   if (!CallOperandVal)
10628     return CW_Default;
10629   Type *type = CallOperandVal->getType();
10630   // Look at the constraint type.
10631   switch (*constraint) {
10632   default:
10633     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10634     break;
10635   case 'l':
10636     if (type->isIntegerTy()) {
10637       if (Subtarget->isThumb())
10638         weight = CW_SpecificReg;
10639       else
10640         weight = CW_Register;
10641     }
10642     break;
10643   case 'w':
10644     if (type->isFloatingPointTy())
10645       weight = CW_Register;
10646     break;
10647   }
10648   return weight;
10649 }
10650
10651 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10652 RCPair
10653 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10654                                                 const std::string &Constraint,
10655                                                 MVT VT) const {
10656   if (Constraint.size() == 1) {
10657     // GCC ARM Constraint Letters
10658     switch (Constraint[0]) {
10659     case 'l': // Low regs or general regs.
10660       if (Subtarget->isThumb())
10661         return RCPair(0U, &ARM::tGPRRegClass);
10662       return RCPair(0U, &ARM::GPRRegClass);
10663     case 'h': // High regs or no regs.
10664       if (Subtarget->isThumb())
10665         return RCPair(0U, &ARM::hGPRRegClass);
10666       break;
10667     case 'r':
10668       if (Subtarget->isThumb1Only())
10669         return RCPair(0U, &ARM::tGPRRegClass);
10670       return RCPair(0U, &ARM::GPRRegClass);
10671     case 'w':
10672       if (VT == MVT::Other)
10673         break;
10674       if (VT == MVT::f32)
10675         return RCPair(0U, &ARM::SPRRegClass);
10676       if (VT.getSizeInBits() == 64)
10677         return RCPair(0U, &ARM::DPRRegClass);
10678       if (VT.getSizeInBits() == 128)
10679         return RCPair(0U, &ARM::QPRRegClass);
10680       break;
10681     case 'x':
10682       if (VT == MVT::Other)
10683         break;
10684       if (VT == MVT::f32)
10685         return RCPair(0U, &ARM::SPR_8RegClass);
10686       if (VT.getSizeInBits() == 64)
10687         return RCPair(0U, &ARM::DPR_8RegClass);
10688       if (VT.getSizeInBits() == 128)
10689         return RCPair(0U, &ARM::QPR_8RegClass);
10690       break;
10691     case 't':
10692       if (VT == MVT::f32)
10693         return RCPair(0U, &ARM::SPRRegClass);
10694       break;
10695     }
10696   }
10697   if (StringRef("{cc}").equals_lower(Constraint))
10698     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10699
10700   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10701 }
10702
10703 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10704 /// vector.  If it is invalid, don't add anything to Ops.
10705 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10706                                                      std::string &Constraint,
10707                                                      std::vector<SDValue>&Ops,
10708                                                      SelectionDAG &DAG) const {
10709   SDValue Result;
10710
10711   // Currently only support length 1 constraints.
10712   if (Constraint.length() != 1) return;
10713
10714   char ConstraintLetter = Constraint[0];
10715   switch (ConstraintLetter) {
10716   default: break;
10717   case 'j':
10718   case 'I': case 'J': case 'K': case 'L':
10719   case 'M': case 'N': case 'O':
10720     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10721     if (!C)
10722       return;
10723
10724     int64_t CVal64 = C->getSExtValue();
10725     int CVal = (int) CVal64;
10726     // None of these constraints allow values larger than 32 bits.  Check
10727     // that the value fits in an int.
10728     if (CVal != CVal64)
10729       return;
10730
10731     switch (ConstraintLetter) {
10732       case 'j':
10733         // Constant suitable for movw, must be between 0 and
10734         // 65535.
10735         if (Subtarget->hasV6T2Ops())
10736           if (CVal >= 0 && CVal <= 65535)
10737             break;
10738         return;
10739       case 'I':
10740         if (Subtarget->isThumb1Only()) {
10741           // This must be a constant between 0 and 255, for ADD
10742           // immediates.
10743           if (CVal >= 0 && CVal <= 255)
10744             break;
10745         } else if (Subtarget->isThumb2()) {
10746           // A constant that can be used as an immediate value in a
10747           // data-processing instruction.
10748           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10749             break;
10750         } else {
10751           // A constant that can be used as an immediate value in a
10752           // data-processing instruction.
10753           if (ARM_AM::getSOImmVal(CVal) != -1)
10754             break;
10755         }
10756         return;
10757
10758       case 'J':
10759         if (Subtarget->isThumb()) {  // FIXME thumb2
10760           // This must be a constant between -255 and -1, for negated ADD
10761           // immediates. This can be used in GCC with an "n" modifier that
10762           // prints the negated value, for use with SUB instructions. It is
10763           // not useful otherwise but is implemented for compatibility.
10764           if (CVal >= -255 && CVal <= -1)
10765             break;
10766         } else {
10767           // This must be a constant between -4095 and 4095. It is not clear
10768           // what this constraint is intended for. Implemented for
10769           // compatibility with GCC.
10770           if (CVal >= -4095 && CVal <= 4095)
10771             break;
10772         }
10773         return;
10774
10775       case 'K':
10776         if (Subtarget->isThumb1Only()) {
10777           // A 32-bit value where only one byte has a nonzero value. Exclude
10778           // zero to match GCC. This constraint is used by GCC internally for
10779           // constants that can be loaded with a move/shift combination.
10780           // It is not useful otherwise but is implemented for compatibility.
10781           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10782             break;
10783         } else if (Subtarget->isThumb2()) {
10784           // A constant whose bitwise inverse can be used as an immediate
10785           // value in a data-processing instruction. This can be used in GCC
10786           // with a "B" modifier that prints the inverted value, for use with
10787           // BIC and MVN instructions. It is not useful otherwise but is
10788           // implemented for compatibility.
10789           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10790             break;
10791         } else {
10792           // A constant whose bitwise inverse can be used as an immediate
10793           // value in a data-processing instruction. This can be used in GCC
10794           // with a "B" modifier that prints the inverted value, for use with
10795           // BIC and MVN instructions. It is not useful otherwise but is
10796           // implemented for compatibility.
10797           if (ARM_AM::getSOImmVal(~CVal) != -1)
10798             break;
10799         }
10800         return;
10801
10802       case 'L':
10803         if (Subtarget->isThumb1Only()) {
10804           // This must be a constant between -7 and 7,
10805           // for 3-operand ADD/SUB immediate instructions.
10806           if (CVal >= -7 && CVal < 7)
10807             break;
10808         } else if (Subtarget->isThumb2()) {
10809           // A constant whose negation can be used as an immediate value in a
10810           // data-processing instruction. This can be used in GCC with an "n"
10811           // modifier that prints the negated value, for use with SUB
10812           // instructions. It is not useful otherwise but is implemented for
10813           // compatibility.
10814           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10815             break;
10816         } else {
10817           // A constant whose negation can be used as an immediate value in a
10818           // data-processing instruction. This can be used in GCC with an "n"
10819           // modifier that prints the negated value, for use with SUB
10820           // instructions. It is not useful otherwise but is implemented for
10821           // compatibility.
10822           if (ARM_AM::getSOImmVal(-CVal) != -1)
10823             break;
10824         }
10825         return;
10826
10827       case 'M':
10828         if (Subtarget->isThumb()) { // FIXME thumb2
10829           // This must be a multiple of 4 between 0 and 1020, for
10830           // ADD sp + immediate.
10831           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10832             break;
10833         } else {
10834           // A power of two or a constant between 0 and 32.  This is used in
10835           // GCC for the shift amount on shifted register operands, but it is
10836           // useful in general for any shift amounts.
10837           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10838             break;
10839         }
10840         return;
10841
10842       case 'N':
10843         if (Subtarget->isThumb()) {  // FIXME thumb2
10844           // This must be a constant between 0 and 31, for shift amounts.
10845           if (CVal >= 0 && CVal <= 31)
10846             break;
10847         }
10848         return;
10849
10850       case 'O':
10851         if (Subtarget->isThumb()) {  // FIXME thumb2
10852           // This must be a multiple of 4 between -508 and 508, for
10853           // ADD/SUB sp = sp + immediate.
10854           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10855             break;
10856         }
10857         return;
10858     }
10859     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10860     break;
10861   }
10862
10863   if (Result.getNode()) {
10864     Ops.push_back(Result);
10865     return;
10866   }
10867   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10868 }
10869
10870 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10871   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10872   unsigned Opcode = Op->getOpcode();
10873   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10874          "Invalid opcode for Div/Rem lowering");
10875   bool isSigned = (Opcode == ISD::SDIVREM);
10876   EVT VT = Op->getValueType(0);
10877   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10878
10879   RTLIB::Libcall LC;
10880   switch (VT.getSimpleVT().SimpleTy) {
10881   default: llvm_unreachable("Unexpected request for libcall!");
10882   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10883   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10884   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10885   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10886   }
10887
10888   SDValue InChain = DAG.getEntryNode();
10889
10890   TargetLowering::ArgListTy Args;
10891   TargetLowering::ArgListEntry Entry;
10892   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10893     EVT ArgVT = Op->getOperand(i).getValueType();
10894     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10895     Entry.Node = Op->getOperand(i);
10896     Entry.Ty = ArgTy;
10897     Entry.isSExt = isSigned;
10898     Entry.isZExt = !isSigned;
10899     Args.push_back(Entry);
10900   }
10901
10902   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10903                                          getPointerTy());
10904
10905   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10906
10907   SDLoc dl(Op);
10908   TargetLowering::CallLoweringInfo CLI(DAG);
10909   CLI.setDebugLoc(dl).setChain(InChain)
10910     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10911     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10912
10913   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10914   return CallInfo.first;
10915 }
10916
10917 SDValue
10918 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10919   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10920   SDLoc DL(Op);
10921
10922   // Get the inputs.
10923   SDValue Chain = Op.getOperand(0);
10924   SDValue Size  = Op.getOperand(1);
10925
10926   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10927                               DAG.getConstant(2, MVT::i32));
10928
10929   SDValue Flag;
10930   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10931   Flag = Chain.getValue(1);
10932
10933   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10934   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10935
10936   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10937   Chain = NewSP.getValue(1);
10938
10939   SDValue Ops[2] = { NewSP, Chain };
10940   return DAG.getMergeValues(Ops, DL);
10941 }
10942
10943 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10944   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10945          "Unexpected type for custom-lowering FP_EXTEND");
10946
10947   RTLIB::Libcall LC;
10948   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10949
10950   SDValue SrcVal = Op.getOperand(0);
10951   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10952                      /*isSigned*/ false, SDLoc(Op)).first;
10953 }
10954
10955 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10956   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10957          Subtarget->isFPOnlySP() &&
10958          "Unexpected type for custom-lowering FP_ROUND");
10959
10960   RTLIB::Libcall LC;
10961   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10962
10963   SDValue SrcVal = Op.getOperand(0);
10964   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10965                      /*isSigned*/ false, SDLoc(Op)).first;
10966 }
10967
10968 bool
10969 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10970   // The ARM target isn't yet aware of offsets.
10971   return false;
10972 }
10973
10974 bool ARM::isBitFieldInvertedMask(unsigned v) {
10975   if (v == 0xffffffff)
10976     return false;
10977
10978   // there can be 1's on either or both "outsides", all the "inside"
10979   // bits must be 0's
10980   return isShiftedMask_32(~v);
10981 }
10982
10983 /// isFPImmLegal - Returns true if the target can instruction select the
10984 /// specified FP immediate natively. If false, the legalizer will
10985 /// materialize the FP immediate as a load from a constant pool.
10986 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10987   if (!Subtarget->hasVFP3())
10988     return false;
10989   if (VT == MVT::f32)
10990     return ARM_AM::getFP32Imm(Imm) != -1;
10991   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10992     return ARM_AM::getFP64Imm(Imm) != -1;
10993   return false;
10994 }
10995
10996 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10997 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10998 /// specified in the intrinsic calls.
10999 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11000                                            const CallInst &I,
11001                                            unsigned Intrinsic) const {
11002   switch (Intrinsic) {
11003   case Intrinsic::arm_neon_vld1:
11004   case Intrinsic::arm_neon_vld2:
11005   case Intrinsic::arm_neon_vld3:
11006   case Intrinsic::arm_neon_vld4:
11007   case Intrinsic::arm_neon_vld2lane:
11008   case Intrinsic::arm_neon_vld3lane:
11009   case Intrinsic::arm_neon_vld4lane: {
11010     Info.opc = ISD::INTRINSIC_W_CHAIN;
11011     // Conservatively set memVT to the entire set of vectors loaded.
11012     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11013     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11014     Info.ptrVal = I.getArgOperand(0);
11015     Info.offset = 0;
11016     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11017     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11018     Info.vol = false; // volatile loads with NEON intrinsics not supported
11019     Info.readMem = true;
11020     Info.writeMem = false;
11021     return true;
11022   }
11023   case Intrinsic::arm_neon_vst1:
11024   case Intrinsic::arm_neon_vst2:
11025   case Intrinsic::arm_neon_vst3:
11026   case Intrinsic::arm_neon_vst4:
11027   case Intrinsic::arm_neon_vst2lane:
11028   case Intrinsic::arm_neon_vst3lane:
11029   case Intrinsic::arm_neon_vst4lane: {
11030     Info.opc = ISD::INTRINSIC_VOID;
11031     // Conservatively set memVT to the entire set of vectors stored.
11032     unsigned NumElts = 0;
11033     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11034       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11035       if (!ArgTy->isVectorTy())
11036         break;
11037       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11038     }
11039     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11040     Info.ptrVal = I.getArgOperand(0);
11041     Info.offset = 0;
11042     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11043     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11044     Info.vol = false; // volatile stores with NEON intrinsics not supported
11045     Info.readMem = false;
11046     Info.writeMem = true;
11047     return true;
11048   }
11049   case Intrinsic::arm_ldaex:
11050   case Intrinsic::arm_ldrex: {
11051     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11052     Info.opc = ISD::INTRINSIC_W_CHAIN;
11053     Info.memVT = MVT::getVT(PtrTy->getElementType());
11054     Info.ptrVal = I.getArgOperand(0);
11055     Info.offset = 0;
11056     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11057     Info.vol = true;
11058     Info.readMem = true;
11059     Info.writeMem = false;
11060     return true;
11061   }
11062   case Intrinsic::arm_stlex:
11063   case Intrinsic::arm_strex: {
11064     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11065     Info.opc = ISD::INTRINSIC_W_CHAIN;
11066     Info.memVT = MVT::getVT(PtrTy->getElementType());
11067     Info.ptrVal = I.getArgOperand(1);
11068     Info.offset = 0;
11069     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11070     Info.vol = true;
11071     Info.readMem = false;
11072     Info.writeMem = true;
11073     return true;
11074   }
11075   case Intrinsic::arm_stlexd:
11076   case Intrinsic::arm_strexd: {
11077     Info.opc = ISD::INTRINSIC_W_CHAIN;
11078     Info.memVT = MVT::i64;
11079     Info.ptrVal = I.getArgOperand(2);
11080     Info.offset = 0;
11081     Info.align = 8;
11082     Info.vol = true;
11083     Info.readMem = false;
11084     Info.writeMem = true;
11085     return true;
11086   }
11087   case Intrinsic::arm_ldaexd:
11088   case Intrinsic::arm_ldrexd: {
11089     Info.opc = ISD::INTRINSIC_W_CHAIN;
11090     Info.memVT = MVT::i64;
11091     Info.ptrVal = I.getArgOperand(0);
11092     Info.offset = 0;
11093     Info.align = 8;
11094     Info.vol = true;
11095     Info.readMem = true;
11096     Info.writeMem = false;
11097     return true;
11098   }
11099   default:
11100     break;
11101   }
11102
11103   return false;
11104 }
11105
11106 /// \brief Returns true if it is beneficial to convert a load of a constant
11107 /// to just the constant itself.
11108 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11109                                                           Type *Ty) const {
11110   assert(Ty->isIntegerTy());
11111
11112   unsigned Bits = Ty->getPrimitiveSizeInBits();
11113   if (Bits == 0 || Bits > 32)
11114     return false;
11115   return true;
11116 }
11117
11118 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11119
11120 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11121                                         ARM_MB::MemBOpt Domain) const {
11122   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11123
11124   // First, if the target has no DMB, see what fallback we can use.
11125   if (!Subtarget->hasDataBarrier()) {
11126     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11127     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11128     // here.
11129     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11130       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11131       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11132                         Builder.getInt32(0), Builder.getInt32(7),
11133                         Builder.getInt32(10), Builder.getInt32(5)};
11134       return Builder.CreateCall(MCR, args);
11135     } else {
11136       // Instead of using barriers, atomic accesses on these subtargets use
11137       // libcalls.
11138       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11139     }
11140   } else {
11141     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11142     // Only a full system barrier exists in the M-class architectures.
11143     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11144     Constant *CDomain = Builder.getInt32(Domain);
11145     return Builder.CreateCall(DMB, CDomain);
11146   }
11147 }
11148
11149 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11150 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11151                                          AtomicOrdering Ord, bool IsStore,
11152                                          bool IsLoad) const {
11153   if (!getInsertFencesForAtomic())
11154     return nullptr;
11155
11156   switch (Ord) {
11157   case NotAtomic:
11158   case Unordered:
11159     llvm_unreachable("Invalid fence: unordered/non-atomic");
11160   case Monotonic:
11161   case Acquire:
11162     return nullptr; // Nothing to do
11163   case SequentiallyConsistent:
11164     if (!IsStore)
11165       return nullptr; // Nothing to do
11166     /*FALLTHROUGH*/
11167   case Release:
11168   case AcquireRelease:
11169     if (Subtarget->isSwift())
11170       return makeDMB(Builder, ARM_MB::ISHST);
11171     // FIXME: add a comment with a link to documentation justifying this.
11172     else
11173       return makeDMB(Builder, ARM_MB::ISH);
11174   }
11175   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11176 }
11177
11178 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11179                                           AtomicOrdering Ord, bool IsStore,
11180                                           bool IsLoad) const {
11181   if (!getInsertFencesForAtomic())
11182     return nullptr;
11183
11184   switch (Ord) {
11185   case NotAtomic:
11186   case Unordered:
11187     llvm_unreachable("Invalid fence: unordered/not-atomic");
11188   case Monotonic:
11189   case Release:
11190     return nullptr; // Nothing to do
11191   case Acquire:
11192   case AcquireRelease:
11193   case SequentiallyConsistent:
11194     return makeDMB(Builder, ARM_MB::ISH);
11195   }
11196   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11197 }
11198
11199 // Loads and stores less than 64-bits are already atomic; ones above that
11200 // are doomed anyway, so defer to the default libcall and blame the OS when
11201 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11202 // anything for those.
11203 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11204   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11205   return (Size == 64) && !Subtarget->isMClass();
11206 }
11207
11208 // Loads and stores less than 64-bits are already atomic; ones above that
11209 // are doomed anyway, so defer to the default libcall and blame the OS when
11210 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11211 // anything for those.
11212 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11213 // guarantee, see DDI0406C ARM architecture reference manual,
11214 // sections A8.8.72-74 LDRD)
11215 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11216   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11217   return (Size == 64) && !Subtarget->isMClass();
11218 }
11219
11220 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11221 // and up to 64 bits on the non-M profiles
11222 TargetLoweringBase::AtomicRMWExpansionKind
11223 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11224   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11225   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11226              ? AtomicRMWExpansionKind::LLSC
11227              : AtomicRMWExpansionKind::None;
11228 }
11229
11230 // This has so far only been implemented for MachO.
11231 bool ARMTargetLowering::useLoadStackGuardNode() const {
11232   return Subtarget->isTargetMachO();
11233 }
11234
11235 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11236                                                   unsigned &Cost) const {
11237   // If we do not have NEON, vector types are not natively supported.
11238   if (!Subtarget->hasNEON())
11239     return false;
11240
11241   // Floating point values and vector values map to the same register file.
11242   // Therefore, althought we could do a store extract of a vector type, this is
11243   // better to leave at float as we have more freedom in the addressing mode for
11244   // those.
11245   if (VectorTy->isFPOrFPVectorTy())
11246     return false;
11247
11248   // If the index is unknown at compile time, this is very expensive to lower
11249   // and it is not possible to combine the store with the extract.
11250   if (!isa<ConstantInt>(Idx))
11251     return false;
11252
11253   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11254   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11255   // We can do a store + vector extract on any vector that fits perfectly in a D
11256   // or Q register.
11257   if (BitWidth == 64 || BitWidth == 128) {
11258     Cost = 0;
11259     return true;
11260   }
11261   return false;
11262 }
11263
11264 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11265                                          AtomicOrdering Ord) const {
11266   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11267   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11268   bool IsAcquire = isAtLeastAcquire(Ord);
11269
11270   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11271   // intrinsic must return {i32, i32} and we have to recombine them into a
11272   // single i64 here.
11273   if (ValTy->getPrimitiveSizeInBits() == 64) {
11274     Intrinsic::ID Int =
11275         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11276     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11277
11278     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11279     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11280
11281     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11282     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11283     if (!Subtarget->isLittle())
11284       std::swap (Lo, Hi);
11285     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11286     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11287     return Builder.CreateOr(
11288         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11289   }
11290
11291   Type *Tys[] = { Addr->getType() };
11292   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11293   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11294
11295   return Builder.CreateTruncOrBitCast(
11296       Builder.CreateCall(Ldrex, Addr),
11297       cast<PointerType>(Addr->getType())->getElementType());
11298 }
11299
11300 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11301                                                Value *Addr,
11302                                                AtomicOrdering Ord) const {
11303   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11304   bool IsRelease = isAtLeastRelease(Ord);
11305
11306   // Since the intrinsics must have legal type, the i64 intrinsics take two
11307   // parameters: "i32, i32". We must marshal Val into the appropriate form
11308   // before the call.
11309   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11310     Intrinsic::ID Int =
11311         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11312     Function *Strex = Intrinsic::getDeclaration(M, Int);
11313     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11314
11315     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11316     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11317     if (!Subtarget->isLittle())
11318       std::swap (Lo, Hi);
11319     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11320     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11321   }
11322
11323   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11324   Type *Tys[] = { Addr->getType() };
11325   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11326
11327   return Builder.CreateCall2(
11328       Strex, Builder.CreateZExtOrBitCast(
11329                  Val, Strex->getFunctionType()->getParamType(0)),
11330       Addr);
11331 }
11332
11333 enum HABaseType {
11334   HA_UNKNOWN = 0,
11335   HA_FLOAT,
11336   HA_DOUBLE,
11337   HA_VECT64,
11338   HA_VECT128
11339 };
11340
11341 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11342                                    uint64_t &Members) {
11343   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11344     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11345       uint64_t SubMembers = 0;
11346       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11347         return false;
11348       Members += SubMembers;
11349     }
11350   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11351     uint64_t SubMembers = 0;
11352     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11353       return false;
11354     Members += SubMembers * AT->getNumElements();
11355   } else if (Ty->isFloatTy()) {
11356     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11357       return false;
11358     Members = 1;
11359     Base = HA_FLOAT;
11360   } else if (Ty->isDoubleTy()) {
11361     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11362       return false;
11363     Members = 1;
11364     Base = HA_DOUBLE;
11365   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11366     Members = 1;
11367     switch (Base) {
11368     case HA_FLOAT:
11369     case HA_DOUBLE:
11370       return false;
11371     case HA_VECT64:
11372       return VT->getBitWidth() == 64;
11373     case HA_VECT128:
11374       return VT->getBitWidth() == 128;
11375     case HA_UNKNOWN:
11376       switch (VT->getBitWidth()) {
11377       case 64:
11378         Base = HA_VECT64;
11379         return true;
11380       case 128:
11381         Base = HA_VECT128;
11382         return true;
11383       default:
11384         return false;
11385       }
11386     }
11387   }
11388
11389   return (Members > 0 && Members <= 4);
11390 }
11391
11392 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11393 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11394 /// passing according to AAPCS rules.
11395 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11396     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11397   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11398       CallingConv::ARM_AAPCS_VFP)
11399     return false;
11400
11401   HABaseType Base = HA_UNKNOWN;
11402   uint64_t Members = 0;
11403   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11404   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11405
11406   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11407   return IsHA || IsIntArray;
11408 }