Remove IsLittleEndian from TargetLowering and redirect to DataLayout
[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/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include <utility>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "arm-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
62
63 static cl::opt<bool>
64 ARMInterworking("arm-interworking", cl::Hidden,
65   cl::desc("Enable / disable ARM interworking (for debugging only)"),
66   cl::init(true));
67
68 namespace {
69   class ARMCCState : public CCState {
70   public:
71     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
73                ParmContext PC)
74         : CCState(CC, isVarArg, MF, locs, C) {
75       assert(((PC == Call) || (PC == Prologue)) &&
76              "ARMCCState users must specify whether their context is call"
77              "or prologue generation.");
78       CallOrPrologue = PC;
79     }
80   };
81 }
82
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85   ARM::R0, ARM::R1, ARM::R2, ARM::R3
86 };
87
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89                                        MVT PromotedBitwiseVT) {
90   if (VT != PromotedLdStVT) {
91     setOperationAction(ISD::LOAD, VT, Promote);
92     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
93
94     setOperationAction(ISD::STORE, VT, Promote);
95     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
96   }
97
98   MVT ElemTy = VT.getVectorElementType();
99   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100     setOperationAction(ISD::SETCC, VT, Custom);
101   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103   if (ElemTy == MVT::i32) {
104     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
108   } else {
109     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
113   }
114   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
115   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
116   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
117   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118   setOperationAction(ISD::SELECT,            VT, Expand);
119   setOperationAction(ISD::SELECT_CC,         VT, Expand);
120   setOperationAction(ISD::VSELECT,           VT, Expand);
121   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122   if (VT.isInteger()) {
123     setOperationAction(ISD::SHL, VT, Custom);
124     setOperationAction(ISD::SRA, VT, Custom);
125     setOperationAction(ISD::SRL, VT, Custom);
126   }
127
128   // Promote all bit-wise operations.
129   if (VT.isInteger() && VT != PromotedBitwiseVT) {
130     setOperationAction(ISD::AND, VT, Promote);
131     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132     setOperationAction(ISD::OR,  VT, Promote);
133     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
134     setOperationAction(ISD::XOR, VT, Promote);
135     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
136   }
137
138   // Neon does not support vector divide/remainder operations.
139   setOperationAction(ISD::SDIV, VT, Expand);
140   setOperationAction(ISD::UDIV, VT, Expand);
141   setOperationAction(ISD::FDIV, VT, Expand);
142   setOperationAction(ISD::SREM, VT, Expand);
143   setOperationAction(ISD::UREM, VT, Expand);
144   setOperationAction(ISD::FREM, VT, Expand);
145 }
146
147 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
148   addRegisterClass(VT, &ARM::DPRRegClass);
149   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
150 }
151
152 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPairRegClass);
154   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
155 }
156
157 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
158                                      const ARMSubtarget &STI)
159     : TargetLowering(TM), Subtarget(&STI) {
160   RegInfo = Subtarget->getRegisterInfo();
161   Itins = Subtarget->getInstrItineraryData();
162
163   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
164
165   if (Subtarget->isTargetMachO()) {
166     // Uses VFP for Thumb libfuncs if available.
167     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
168         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
169       // Single-precision floating-point arithmetic.
170       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
171       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
172       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
173       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
174
175       // Double-precision floating-point arithmetic.
176       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
177       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
178       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
179       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
180
181       // Single-precision comparisons.
182       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
183       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
184       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
185       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
186       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
187       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
188       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
189       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
190
191       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
192       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
193       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
194       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
195       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
196       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
197       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
198       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
199
200       // Double-precision comparisons.
201       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
202       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
203       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
204       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
205       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
206       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
207       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
208       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
209
210       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
211       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
212       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
213       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
214       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
215       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
216       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
217       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
218
219       // Floating-point to integer conversions.
220       // i64 conversions are done via library routines even when generating VFP
221       // instructions, so use the same ones.
222       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
223       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
224       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
225       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
226
227       // Conversions between floating types.
228       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
229       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
230
231       // Integer to floating-point conversions.
232       // i64 conversions are done via library routines even when generating VFP
233       // instructions, so use the same ones.
234       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
235       // e.g., __floatunsidf vs. __floatunssidfvfp.
236       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
237       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
238       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
239       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
240     }
241   }
242
243   // These libcalls are not available in 32-bit.
244   setLibcallName(RTLIB::SHL_I128, nullptr);
245   setLibcallName(RTLIB::SRL_I128, nullptr);
246   setLibcallName(RTLIB::SRA_I128, nullptr);
247
248   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
249       !Subtarget->isTargetWindows()) {
250     static const struct {
251       const RTLIB::Libcall Op;
252       const char * const Name;
253       const CallingConv::ID CC;
254       const ISD::CondCode Cond;
255     } LibraryCalls[] = {
256       // Double-precision floating-point arithmetic helper functions
257       // RTABI chapter 4.1.2, Table 2
258       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
259       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
260       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
261       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
262
263       // Double-precision floating-point comparison helper functions
264       // RTABI chapter 4.1.2, Table 3
265       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
266       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
267       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
268       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
269       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
270       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
271       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
272       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
273
274       // Single-precision floating-point arithmetic helper functions
275       // RTABI chapter 4.1.2, Table 4
276       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
277       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
278       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
279       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
280
281       // Single-precision floating-point comparison helper functions
282       // RTABI chapter 4.1.2, Table 5
283       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
284       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
285       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
286       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
287       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
288       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
289       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
290       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
291
292       // Floating-point to integer conversions.
293       // RTABI chapter 4.1.2, Table 6
294       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
295       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
296       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
297       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
298       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302
303       // Conversions between floating types.
304       // RTABI chapter 4.1.2, Table 7
305       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308
309       // Integer to floating-point conversions.
310       // RTABI chapter 4.1.2, Table 8
311       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319
320       // Long long helper functions
321       // RTABI chapter 4.2, Table 9
322       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326
327       // Integer division functions
328       // RTABI chapter 4.3.1
329       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337
338       // Memory operations
339       // RTABI chapter 4.3.4
340       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343     };
344
345     for (const auto &LC : LibraryCalls) {
346       setLibcallName(LC.Op, LC.Name);
347       setLibcallCallingConv(LC.Op, LC.CC);
348       if (LC.Cond != ISD::SETCC_INVALID)
349         setCmpLibcallCC(LC.Op, LC.Cond);
350     }
351   }
352
353   if (Subtarget->isTargetWindows()) {
354     static const struct {
355       const RTLIB::Libcall Op;
356       const char * const Name;
357       const CallingConv::ID CC;
358     } LibraryCalls[] = {
359       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
360       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
361       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
362       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
363       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
364       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
366       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
367     };
368
369     for (const auto &LC : LibraryCalls) {
370       setLibcallName(LC.Op, LC.Name);
371       setLibcallCallingConv(LC.Op, LC.CC);
372     }
373   }
374
375   // Use divmod compiler-rt calls for iOS 5.0 and later.
376   if (Subtarget->getTargetTriple().isiOS() &&
377       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
378     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
379     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
380   }
381
382   // The half <-> float conversion functions are always soft-float, but are
383   // needed for some targets which use a hard-float calling convention by
384   // default.
385   if (Subtarget->isAAPCS_ABI()) {
386     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
387     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
389   } else {
390     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
391     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
392     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
393   }
394
395   if (Subtarget->isThumb1Only())
396     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
397   else
398     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
399   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
400       !Subtarget->isThumb1Only()) {
401     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
402     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
403   }
404
405   for (MVT VT : MVT::vector_valuetypes()) {
406     for (MVT InnerVT : MVT::vector_valuetypes()) {
407       setTruncStoreAction(VT, InnerVT, Expand);
408       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
409       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
410       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
411     }
412
413     setOperationAction(ISD::MULHS, VT, Expand);
414     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
415     setOperationAction(ISD::MULHU, VT, Expand);
416     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
417
418     setOperationAction(ISD::BSWAP, VT, Expand);
419   }
420
421   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
422   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
423
424   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
425   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, 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::SINT_TO_FP, MVT::i32, Custom);
617     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
618     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
619     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
620     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
621     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
622     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
623     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
624   }
625
626   computeRegisterProperties(Subtarget->getRegisterInfo());
627
628   // ARM does not have floating-point extending loads.
629   for (MVT VT : MVT::fp_valuetypes()) {
630     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
631     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
632   }
633
634   // ... or truncating stores
635   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
636   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
637   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
638
639   // ARM does not have i1 sign extending load.
640   for (MVT VT : MVT::integer_valuetypes())
641     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
642
643   // ARM supports all 4 flavors of integer indexed load / store.
644   if (!Subtarget->isThumb1Only()) {
645     for (unsigned im = (unsigned)ISD::PRE_INC;
646          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
647       setIndexedLoadAction(im,  MVT::i1,  Legal);
648       setIndexedLoadAction(im,  MVT::i8,  Legal);
649       setIndexedLoadAction(im,  MVT::i16, Legal);
650       setIndexedLoadAction(im,  MVT::i32, Legal);
651       setIndexedStoreAction(im, MVT::i1,  Legal);
652       setIndexedStoreAction(im, MVT::i8,  Legal);
653       setIndexedStoreAction(im, MVT::i16, Legal);
654       setIndexedStoreAction(im, MVT::i32, Legal);
655     }
656   }
657
658   setOperationAction(ISD::SADDO, MVT::i32, Custom);
659   setOperationAction(ISD::UADDO, MVT::i32, Custom);
660   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
661   setOperationAction(ISD::USUBO, MVT::i32, Custom);
662
663   // i64 operation support.
664   setOperationAction(ISD::MUL,     MVT::i64, Expand);
665   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
666   if (Subtarget->isThumb1Only()) {
667     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
668     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
669   }
670   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
671       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
672     setOperationAction(ISD::MULHS, MVT::i32, Expand);
673
674   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
675   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
676   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
677   setOperationAction(ISD::SRL,       MVT::i64, Custom);
678   setOperationAction(ISD::SRA,       MVT::i64, Custom);
679
680   if (!Subtarget->isThumb1Only()) {
681     // FIXME: We should do this for Thumb1 as well.
682     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
683     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
684     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
685     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
686   }
687
688   // ARM does not have ROTL.
689   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
690   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
691   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
692   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
693     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
694
695   // These just redirect to CTTZ and CTLZ on ARM.
696   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
697   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
698
699   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
700
701   // Only ARMv6 has BSWAP.
702   if (!Subtarget->hasV6Ops())
703     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
704
705   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
706       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
707     // These are expanded into libcalls if the cpu doesn't have HW divider.
708     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
709     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
710   }
711
712   // FIXME: Also set divmod for SREM on EABI
713   setOperationAction(ISD::SREM,  MVT::i32, Expand);
714   setOperationAction(ISD::UREM,  MVT::i32, Expand);
715   // Register based DivRem for AEABI (RTABI 4.2)
716   if (Subtarget->isTargetAEABI()) {
717     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
718     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
719     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
720     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
721     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
722     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
723     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
724     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
725
726     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
727     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
728     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
729     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
730     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
731     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
732     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
733     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
734
735     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
736     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
737   } else {
738     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
739     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
740   }
741
742   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
743   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
744   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
745   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
746   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
747
748   setOperationAction(ISD::TRAP, MVT::Other, Legal);
749
750   // Use the default implementation.
751   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
752   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
753   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
754   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
755   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
756   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
757
758   if (!Subtarget->isTargetMachO()) {
759     // Non-MachO platforms may return values in these registers via the
760     // personality function.
761     setExceptionPointerRegister(ARM::R0);
762     setExceptionSelectorRegister(ARM::R1);
763   }
764
765   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
766     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
767   else
768     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
769
770   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
771   // the default expansion. If we are targeting a single threaded system,
772   // then set them all for expand so we can lower them later into their
773   // non-atomic form.
774   if (TM.Options.ThreadModel == ThreadModel::Single)
775     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
776   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
777     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
778     // to ldrex/strex loops already.
779     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
780
781     // On v8, we have particularly efficient implementations of atomic fences
782     // if they can be combined with nearby atomic loads and stores.
783     if (!Subtarget->hasV8Ops()) {
784       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
785       setInsertFencesForAtomic(true);
786     }
787   } else {
788     // If there's anything we can use as a barrier, go through custom lowering
789     // for ATOMIC_FENCE.
790     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
791                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
792
793     // Set them all for expansion, which will force libcalls.
794     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
795     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
796     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
801     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
802     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
803     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
804     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
805     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
806     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
807     // Unordered/Monotonic case.
808     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
809     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
810   }
811
812   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
813
814   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
815   if (!Subtarget->hasV6Ops()) {
816     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
817     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
818   }
819   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
820
821   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
822       !Subtarget->isThumb1Only()) {
823     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
824     // iff target supports vfp2.
825     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
826     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
827   }
828
829   // We want to custom lower some of our intrinsics.
830   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
831   if (Subtarget->isTargetDarwin()) {
832     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
833     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
834     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
835   }
836
837   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
838   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
839   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
840   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
841   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
842   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
843   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
844   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
845   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
846
847   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
848   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
849   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
850   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
851   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
852
853   // We don't support sin/cos/fmod/copysign/pow
854   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
855   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
856   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
857   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
858   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
859   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
860   setOperationAction(ISD::FREM,      MVT::f64, Expand);
861   setOperationAction(ISD::FREM,      MVT::f32, Expand);
862   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
863       !Subtarget->isThumb1Only()) {
864     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
865     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
866   }
867   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
868   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
869
870   if (!Subtarget->hasVFP4()) {
871     setOperationAction(ISD::FMA, MVT::f64, Expand);
872     setOperationAction(ISD::FMA, MVT::f32, Expand);
873   }
874
875   // Various VFP goodness
876   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
877     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
878     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
879       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
880       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
881     }
882
883     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
884     if (!Subtarget->hasFP16()) {
885       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
886       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
887     }
888   }
889
890   // Combine sin / cos into one node or libcall if possible.
891   if (Subtarget->hasSinCos()) {
892     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
893     setLibcallName(RTLIB::SINCOS_F64, "sincos");
894     if (Subtarget->getTargetTriple().isiOS()) {
895       // For iOS, we don't want to the normal expansion of a libcall to
896       // sincos. We want to issue a libcall to __sincos_stret.
897       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
898       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
899     }
900   }
901
902   // FP-ARMv8 implements a lot of rounding-like FP operations.
903   if (Subtarget->hasFPARMv8()) {
904     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
905     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
906     setOperationAction(ISD::FROUND, MVT::f32, Legal);
907     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
908     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
909     setOperationAction(ISD::FRINT, MVT::f32, Legal);
910     if (!Subtarget->isFPOnlySP()) {
911       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
912       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
913       setOperationAction(ISD::FROUND, MVT::f64, Legal);
914       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
915       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
916       setOperationAction(ISD::FRINT, MVT::f64, Legal);
917     }
918   }
919   // We have target-specific dag combine patterns for the following nodes:
920   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
921   setTargetDAGCombine(ISD::ADD);
922   setTargetDAGCombine(ISD::SUB);
923   setTargetDAGCombine(ISD::MUL);
924   setTargetDAGCombine(ISD::AND);
925   setTargetDAGCombine(ISD::OR);
926   setTargetDAGCombine(ISD::XOR);
927
928   if (Subtarget->hasV6Ops())
929     setTargetDAGCombine(ISD::SRL);
930
931   setStackPointerRegisterToSaveRestore(ARM::SP);
932
933   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
934       !Subtarget->hasVFP2())
935     setSchedulingPreference(Sched::RegPressure);
936   else
937     setSchedulingPreference(Sched::Hybrid);
938
939   //// temporary - rewrite interface to use type
940   MaxStoresPerMemset = 8;
941   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
942   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
943   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
944   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
945   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
946
947   // On ARM arguments smaller than 4 bytes are extended, so all arguments
948   // are at least 4 bytes aligned.
949   setMinStackArgumentAlignment(4);
950
951   // Prefer likely predicted branches to selects on out-of-order cores.
952   PredictableSelectIsExpensive = Subtarget->isLikeA9();
953
954   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
955 }
956
957 bool ARMTargetLowering::useSoftFloat() const {
958   return Subtarget->useSoftFloat();
959 }
960
961 // FIXME: It might make sense to define the representative register class as the
962 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
963 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
964 // SPR's representative would be DPR_VFP2. This should work well if register
965 // pressure tracking were modified such that a register use would increment the
966 // pressure of the register class's representative and all of it's super
967 // classes' representatives transitively. We have not implemented this because
968 // of the difficulty prior to coalescing of modeling operand register classes
969 // due to the common occurrence of cross class copies and subregister insertions
970 // and extractions.
971 std::pair<const TargetRegisterClass *, uint8_t>
972 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
973                                            MVT VT) const {
974   const TargetRegisterClass *RRC = nullptr;
975   uint8_t Cost = 1;
976   switch (VT.SimpleTy) {
977   default:
978     return TargetLowering::findRepresentativeClass(TRI, VT);
979   // Use DPR as representative register class for all floating point
980   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
981   // the cost is 1 for both f32 and f64.
982   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
983   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
984     RRC = &ARM::DPRRegClass;
985     // When NEON is used for SP, only half of the register file is available
986     // because operations that define both SP and DP results will be constrained
987     // to the VFP2 class (D0-D15). We currently model this constraint prior to
988     // coalescing by double-counting the SP regs. See the FIXME above.
989     if (Subtarget->useNEONForSinglePrecisionFP())
990       Cost = 2;
991     break;
992   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
993   case MVT::v4f32: case MVT::v2f64:
994     RRC = &ARM::DPRRegClass;
995     Cost = 2;
996     break;
997   case MVT::v4i64:
998     RRC = &ARM::DPRRegClass;
999     Cost = 4;
1000     break;
1001   case MVT::v8i64:
1002     RRC = &ARM::DPRRegClass;
1003     Cost = 8;
1004     break;
1005   }
1006   return std::make_pair(RRC, Cost);
1007 }
1008
1009 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1010   switch ((ARMISD::NodeType)Opcode) {
1011   case ARMISD::FIRST_NUMBER:  break;
1012   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1013   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1014   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1015   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1016   case ARMISD::CALL:          return "ARMISD::CALL";
1017   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1018   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1019   case ARMISD::tCALL:         return "ARMISD::tCALL";
1020   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1021   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1022   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1023   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1024   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1025   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1026   case ARMISD::CMP:           return "ARMISD::CMP";
1027   case ARMISD::CMN:           return "ARMISD::CMN";
1028   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1029   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1030   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1031   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1032   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1033
1034   case ARMISD::CMOV:          return "ARMISD::CMOV";
1035
1036   case ARMISD::RBIT:          return "ARMISD::RBIT";
1037
1038   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1039   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1040   case ARMISD::RRX:           return "ARMISD::RRX";
1041
1042   case ARMISD::ADDC:          return "ARMISD::ADDC";
1043   case ARMISD::ADDE:          return "ARMISD::ADDE";
1044   case ARMISD::SUBC:          return "ARMISD::SUBC";
1045   case ARMISD::SUBE:          return "ARMISD::SUBE";
1046
1047   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1048   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1049
1050   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1051   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1052
1053   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1054
1055   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1056
1057   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1058
1059   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1060
1061   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1062
1063   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1064
1065   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1066   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1067   case ARMISD::VCGE:          return "ARMISD::VCGE";
1068   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1069   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1070   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1071   case ARMISD::VCGT:          return "ARMISD::VCGT";
1072   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1073   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1074   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1075   case ARMISD::VTST:          return "ARMISD::VTST";
1076
1077   case ARMISD::VSHL:          return "ARMISD::VSHL";
1078   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1079   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1080   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1081   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1082   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1083   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1084   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1085   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1086   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1087   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1088   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1089   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1090   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1091   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1092   case ARMISD::VSLI:          return "ARMISD::VSLI";
1093   case ARMISD::VSRI:          return "ARMISD::VSRI";
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   return nullptr;
1145 }
1146
1147 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1148   if (!VT.isVector()) return getPointerTy();
1149   return VT.changeVectorElementTypeToInteger();
1150 }
1151
1152 /// getRegClassFor - Return the register class that should be used for the
1153 /// specified value type.
1154 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1155   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1156   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1157   // load / store 4 to 8 consecutive D registers.
1158   if (Subtarget->hasNEON()) {
1159     if (VT == MVT::v4i64)
1160       return &ARM::QQPRRegClass;
1161     if (VT == MVT::v8i64)
1162       return &ARM::QQQQPRRegClass;
1163   }
1164   return TargetLowering::getRegClassFor(VT);
1165 }
1166
1167 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1168 // source/dest is aligned and the copy size is large enough. We therefore want
1169 // to align such objects passed to memory intrinsics.
1170 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1171                                                unsigned &PrefAlign) const {
1172   if (!isa<MemIntrinsic>(CI))
1173     return false;
1174   MinSize = 8;
1175   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1176   // cycle faster than 4-byte aligned LDM.
1177   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1178   return true;
1179 }
1180
1181 // Create a fast isel object.
1182 FastISel *
1183 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1184                                   const TargetLibraryInfo *libInfo) const {
1185   return ARM::createFastISel(funcInfo, libInfo);
1186 }
1187
1188 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1189   unsigned NumVals = N->getNumValues();
1190   if (!NumVals)
1191     return Sched::RegPressure;
1192
1193   for (unsigned i = 0; i != NumVals; ++i) {
1194     EVT VT = N->getValueType(i);
1195     if (VT == MVT::Glue || VT == MVT::Other)
1196       continue;
1197     if (VT.isFloatingPoint() || VT.isVector())
1198       return Sched::ILP;
1199   }
1200
1201   if (!N->isMachineOpcode())
1202     return Sched::RegPressure;
1203
1204   // Load are scheduled for latency even if there instruction itinerary
1205   // is not available.
1206   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1207   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1208
1209   if (MCID.getNumDefs() == 0)
1210     return Sched::RegPressure;
1211   if (!Itins->isEmpty() &&
1212       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1213     return Sched::ILP;
1214
1215   return Sched::RegPressure;
1216 }
1217
1218 //===----------------------------------------------------------------------===//
1219 // Lowering Code
1220 //===----------------------------------------------------------------------===//
1221
1222 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1223 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1224   switch (CC) {
1225   default: llvm_unreachable("Unknown condition code!");
1226   case ISD::SETNE:  return ARMCC::NE;
1227   case ISD::SETEQ:  return ARMCC::EQ;
1228   case ISD::SETGT:  return ARMCC::GT;
1229   case ISD::SETGE:  return ARMCC::GE;
1230   case ISD::SETLT:  return ARMCC::LT;
1231   case ISD::SETLE:  return ARMCC::LE;
1232   case ISD::SETUGT: return ARMCC::HI;
1233   case ISD::SETUGE: return ARMCC::HS;
1234   case ISD::SETULT: return ARMCC::LO;
1235   case ISD::SETULE: return ARMCC::LS;
1236   }
1237 }
1238
1239 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1240 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1241                         ARMCC::CondCodes &CondCode2) {
1242   CondCode2 = ARMCC::AL;
1243   switch (CC) {
1244   default: llvm_unreachable("Unknown FP condition!");
1245   case ISD::SETEQ:
1246   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1247   case ISD::SETGT:
1248   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1249   case ISD::SETGE:
1250   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1251   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1252   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1253   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1254   case ISD::SETO:   CondCode = ARMCC::VC; break;
1255   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1256   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1257   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1258   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1259   case ISD::SETLT:
1260   case ISD::SETULT: CondCode = ARMCC::LT; break;
1261   case ISD::SETLE:
1262   case ISD::SETULE: CondCode = ARMCC::LE; break;
1263   case ISD::SETNE:
1264   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1265   }
1266 }
1267
1268 //===----------------------------------------------------------------------===//
1269 //                      Calling Convention Implementation
1270 //===----------------------------------------------------------------------===//
1271
1272 #include "ARMGenCallingConv.inc"
1273
1274 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1275 /// account presence of floating point hardware and calling convention
1276 /// limitations, such as support for variadic functions.
1277 CallingConv::ID
1278 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1279                                            bool isVarArg) const {
1280   switch (CC) {
1281   default:
1282     llvm_unreachable("Unsupported calling convention");
1283   case CallingConv::ARM_AAPCS:
1284   case CallingConv::ARM_APCS:
1285   case CallingConv::GHC:
1286     return CC;
1287   case CallingConv::ARM_AAPCS_VFP:
1288     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1289   case CallingConv::C:
1290     if (!Subtarget->isAAPCS_ABI())
1291       return CallingConv::ARM_APCS;
1292     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1293              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1294              !isVarArg)
1295       return CallingConv::ARM_AAPCS_VFP;
1296     else
1297       return CallingConv::ARM_AAPCS;
1298   case CallingConv::Fast:
1299     if (!Subtarget->isAAPCS_ABI()) {
1300       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1301         return CallingConv::Fast;
1302       return CallingConv::ARM_APCS;
1303     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1304       return CallingConv::ARM_AAPCS_VFP;
1305     else
1306       return CallingConv::ARM_AAPCS;
1307   }
1308 }
1309
1310 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1311 /// CallingConvention.
1312 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1313                                                  bool Return,
1314                                                  bool isVarArg) const {
1315   switch (getEffectiveCallingConv(CC, isVarArg)) {
1316   default:
1317     llvm_unreachable("Unsupported calling convention");
1318   case CallingConv::ARM_APCS:
1319     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1320   case CallingConv::ARM_AAPCS:
1321     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1322   case CallingConv::ARM_AAPCS_VFP:
1323     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1324   case CallingConv::Fast:
1325     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1326   case CallingConv::GHC:
1327     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1328   }
1329 }
1330
1331 /// LowerCallResult - Lower the result values of a call into the
1332 /// appropriate copies out of appropriate physical registers.
1333 SDValue
1334 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1335                                    CallingConv::ID CallConv, bool isVarArg,
1336                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1337                                    SDLoc dl, SelectionDAG &DAG,
1338                                    SmallVectorImpl<SDValue> &InVals,
1339                                    bool isThisReturn, SDValue ThisVal) const {
1340
1341   // Assign locations to each value returned by this call.
1342   SmallVector<CCValAssign, 16> RVLocs;
1343   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1344                     *DAG.getContext(), Call);
1345   CCInfo.AnalyzeCallResult(Ins,
1346                            CCAssignFnForNode(CallConv, /* Return*/ true,
1347                                              isVarArg));
1348
1349   // Copy all of the result registers out of their specified physreg.
1350   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1351     CCValAssign VA = RVLocs[i];
1352
1353     // Pass 'this' value directly from the argument to return value, to avoid
1354     // reg unit interference
1355     if (i == 0 && isThisReturn) {
1356       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1357              "unexpected return calling convention register assignment");
1358       InVals.push_back(ThisVal);
1359       continue;
1360     }
1361
1362     SDValue Val;
1363     if (VA.needsCustom()) {
1364       // Handle f64 or half of a v2f64.
1365       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1366                                       InFlag);
1367       Chain = Lo.getValue(1);
1368       InFlag = Lo.getValue(2);
1369       VA = RVLocs[++i]; // skip ahead to next loc
1370       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1371                                       InFlag);
1372       Chain = Hi.getValue(1);
1373       InFlag = Hi.getValue(2);
1374       if (!Subtarget->isLittle())
1375         std::swap (Lo, Hi);
1376       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1377
1378       if (VA.getLocVT() == MVT::v2f64) {
1379         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1380         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1381                           DAG.getConstant(0, dl, MVT::i32));
1382
1383         VA = RVLocs[++i]; // skip ahead to next loc
1384         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1385         Chain = Lo.getValue(1);
1386         InFlag = Lo.getValue(2);
1387         VA = RVLocs[++i]; // skip ahead to next loc
1388         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1389         Chain = Hi.getValue(1);
1390         InFlag = Hi.getValue(2);
1391         if (!Subtarget->isLittle())
1392           std::swap (Lo, Hi);
1393         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1394         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1395                           DAG.getConstant(1, dl, MVT::i32));
1396       }
1397     } else {
1398       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1399                                InFlag);
1400       Chain = Val.getValue(1);
1401       InFlag = Val.getValue(2);
1402     }
1403
1404     switch (VA.getLocInfo()) {
1405     default: llvm_unreachable("Unknown loc info!");
1406     case CCValAssign::Full: break;
1407     case CCValAssign::BCvt:
1408       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1409       break;
1410     }
1411
1412     InVals.push_back(Val);
1413   }
1414
1415   return Chain;
1416 }
1417
1418 /// LowerMemOpCallTo - Store the argument to the stack.
1419 SDValue
1420 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1421                                     SDValue StackPtr, SDValue Arg,
1422                                     SDLoc dl, SelectionDAG &DAG,
1423                                     const CCValAssign &VA,
1424                                     ISD::ArgFlagsTy Flags) const {
1425   unsigned LocMemOffset = VA.getLocMemOffset();
1426   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1427   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1428   return DAG.getStore(Chain, dl, Arg, PtrOff,
1429                       MachinePointerInfo::getStack(LocMemOffset),
1430                       false, false, 0);
1431 }
1432
1433 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1434                                          SDValue Chain, SDValue &Arg,
1435                                          RegsToPassVector &RegsToPass,
1436                                          CCValAssign &VA, CCValAssign &NextVA,
1437                                          SDValue &StackPtr,
1438                                          SmallVectorImpl<SDValue> &MemOpChains,
1439                                          ISD::ArgFlagsTy Flags) const {
1440
1441   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1442                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1443   unsigned id = Subtarget->isLittle() ? 0 : 1;
1444   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1445
1446   if (NextVA.isRegLoc())
1447     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1448   else {
1449     assert(NextVA.isMemLoc());
1450     if (!StackPtr.getNode())
1451       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1452
1453     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1454                                            dl, DAG, NextVA,
1455                                            Flags));
1456   }
1457 }
1458
1459 /// LowerCall - Lowering a call into a callseq_start <-
1460 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1461 /// nodes.
1462 SDValue
1463 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1464                              SmallVectorImpl<SDValue> &InVals) const {
1465   SelectionDAG &DAG                     = CLI.DAG;
1466   SDLoc &dl                             = CLI.DL;
1467   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1468   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1469   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1470   SDValue Chain                         = CLI.Chain;
1471   SDValue Callee                        = CLI.Callee;
1472   bool &isTailCall                      = CLI.IsTailCall;
1473   CallingConv::ID CallConv              = CLI.CallConv;
1474   bool doesNotRet                       = CLI.DoesNotReturn;
1475   bool isVarArg                         = CLI.IsVarArg;
1476
1477   MachineFunction &MF = DAG.getMachineFunction();
1478   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1479   bool isThisReturn   = false;
1480   bool isSibCall      = false;
1481   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1482
1483   // Disable tail calls if they're not supported.
1484   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1485     isTailCall = false;
1486
1487   if (isTailCall) {
1488     // Check if it's really possible to do a tail call.
1489     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1490                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1491                                                    Outs, OutVals, Ins, DAG);
1492     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1493       report_fatal_error("failed to perform tail call elimination on a call "
1494                          "site marked musttail");
1495     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1496     // detected sibcalls.
1497     if (isTailCall) {
1498       ++NumTailCalls;
1499       isSibCall = true;
1500     }
1501   }
1502
1503   // Analyze operands of the call, assigning locations to each operand.
1504   SmallVector<CCValAssign, 16> ArgLocs;
1505   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1506                     *DAG.getContext(), Call);
1507   CCInfo.AnalyzeCallOperands(Outs,
1508                              CCAssignFnForNode(CallConv, /* Return*/ false,
1509                                                isVarArg));
1510
1511   // Get a count of how many bytes are to be pushed on the stack.
1512   unsigned NumBytes = CCInfo.getNextStackOffset();
1513
1514   // For tail calls, memory operands are available in our caller's stack.
1515   if (isSibCall)
1516     NumBytes = 0;
1517
1518   // Adjust the stack pointer for the new arguments...
1519   // These operations are automatically eliminated by the prolog/epilog pass
1520   if (!isSibCall)
1521     Chain = DAG.getCALLSEQ_START(Chain,
1522                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1523
1524   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1525
1526   RegsToPassVector RegsToPass;
1527   SmallVector<SDValue, 8> MemOpChains;
1528
1529   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1530   // of tail call optimization, arguments are handled later.
1531   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1532        i != e;
1533        ++i, ++realArgIdx) {
1534     CCValAssign &VA = ArgLocs[i];
1535     SDValue Arg = OutVals[realArgIdx];
1536     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1537     bool isByVal = Flags.isByVal();
1538
1539     // Promote the value if needed.
1540     switch (VA.getLocInfo()) {
1541     default: llvm_unreachable("Unknown loc info!");
1542     case CCValAssign::Full: break;
1543     case CCValAssign::SExt:
1544       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1545       break;
1546     case CCValAssign::ZExt:
1547       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1548       break;
1549     case CCValAssign::AExt:
1550       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1551       break;
1552     case CCValAssign::BCvt:
1553       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1554       break;
1555     }
1556
1557     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1558     if (VA.needsCustom()) {
1559       if (VA.getLocVT() == MVT::v2f64) {
1560         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1561                                   DAG.getConstant(0, dl, MVT::i32));
1562         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1563                                   DAG.getConstant(1, dl, MVT::i32));
1564
1565         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1566                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1567
1568         VA = ArgLocs[++i]; // skip ahead to next loc
1569         if (VA.isRegLoc()) {
1570           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1571                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1572         } else {
1573           assert(VA.isMemLoc());
1574
1575           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1576                                                  dl, DAG, VA, Flags));
1577         }
1578       } else {
1579         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1580                          StackPtr, MemOpChains, Flags);
1581       }
1582     } else if (VA.isRegLoc()) {
1583       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1584         assert(VA.getLocVT() == MVT::i32 &&
1585                "unexpected calling convention register assignment");
1586         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1587                "unexpected use of 'returned'");
1588         isThisReturn = true;
1589       }
1590       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1591     } else if (isByVal) {
1592       assert(VA.isMemLoc());
1593       unsigned offset = 0;
1594
1595       // True if this byval aggregate will be split between registers
1596       // and memory.
1597       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1598       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1599
1600       if (CurByValIdx < ByValArgsCount) {
1601
1602         unsigned RegBegin, RegEnd;
1603         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1604
1605         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1606         unsigned int i, j;
1607         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1608           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1609           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1610           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1611                                      MachinePointerInfo(),
1612                                      false, false, false,
1613                                      DAG.InferPtrAlignment(AddArg));
1614           MemOpChains.push_back(Load.getValue(1));
1615           RegsToPass.push_back(std::make_pair(j, Load));
1616         }
1617
1618         // If parameter size outsides register area, "offset" value
1619         // helps us to calculate stack slot for remained part properly.
1620         offset = RegEnd - RegBegin;
1621
1622         CCInfo.nextInRegsParam();
1623       }
1624
1625       if (Flags.getByValSize() > 4*offset) {
1626         unsigned LocMemOffset = VA.getLocMemOffset();
1627         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1628         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1629                                   StkPtrOff);
1630         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1631         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1632         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1633                                            MVT::i32);
1634         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1635                                             MVT::i32);
1636
1637         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1638         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1639         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1640                                           Ops));
1641       }
1642     } else if (!isSibCall) {
1643       assert(VA.isMemLoc());
1644
1645       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1646                                              dl, DAG, VA, Flags));
1647     }
1648   }
1649
1650   if (!MemOpChains.empty())
1651     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1652
1653   // Build a sequence of copy-to-reg nodes chained together with token chain
1654   // and flag operands which copy the outgoing args into the appropriate regs.
1655   SDValue InFlag;
1656   // Tail call byval lowering might overwrite argument registers so in case of
1657   // tail call optimization the copies to registers are lowered later.
1658   if (!isTailCall)
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
1665   // For tail calls lower the arguments to the 'real' stack slot.
1666   if (isTailCall) {
1667     // Force all the incoming stack arguments to be loaded from the stack
1668     // before any new outgoing arguments are stored to the stack, because the
1669     // outgoing stack slots may alias the incoming argument stack slots, and
1670     // the alias isn't otherwise explicit. This is slightly more conservative
1671     // than necessary, because it means that each store effectively depends
1672     // on every argument instead of just those arguments it would clobber.
1673
1674     // Do not flag preceding copytoreg stuff together with the following stuff.
1675     InFlag = SDValue();
1676     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1677       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1678                                RegsToPass[i].second, InFlag);
1679       InFlag = Chain.getValue(1);
1680     }
1681     InFlag = SDValue();
1682   }
1683
1684   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1685   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1686   // node so that legalize doesn't hack it.
1687   bool isDirect = false;
1688   bool isARMFunc = false;
1689   bool isLocalARMFunc = false;
1690   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1691
1692   if (Subtarget->genLongCalls()) {
1693     assert((Subtarget->isTargetWindows() ||
1694             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1695            "long-calls with non-static relocation model!");
1696     // Handle a global address or an external symbol. If it's not one of
1697     // those, the target's already in a register, so we don't need to do
1698     // anything extra.
1699     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1700       const GlobalValue *GV = G->getGlobal();
1701       // Create a constant pool entry for the callee address
1702       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1703       ARMConstantPoolValue *CPV =
1704         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1705
1706       // Get the address of the callee into a register
1707       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1708       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1709       Callee = DAG.getLoad(getPointerTy(), dl,
1710                            DAG.getEntryNode(), CPAddr,
1711                            MachinePointerInfo::getConstantPool(),
1712                            false, false, false, 0);
1713     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1714       const char *Sym = S->getSymbol();
1715
1716       // Create a constant pool entry for the callee address
1717       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1718       ARMConstantPoolValue *CPV =
1719         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1720                                       ARMPCLabelIndex, 0);
1721       // Get the address of the callee into a register
1722       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1723       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1724       Callee = DAG.getLoad(getPointerTy(), dl,
1725                            DAG.getEntryNode(), CPAddr,
1726                            MachinePointerInfo::getConstantPool(),
1727                            false, false, false, 0);
1728     }
1729   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1730     const GlobalValue *GV = G->getGlobal();
1731     isDirect = true;
1732     bool isDef = GV->isStrongDefinitionForLinker();
1733     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1734                    getTargetMachine().getRelocationModel() != Reloc::Static;
1735     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1736     // ARM call to a local ARM function is predicable.
1737     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1738     // tBX takes a register source operand.
1739     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1740       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1741       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1742                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1743                                                       0, ARMII::MO_NONLAZY));
1744       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1745                            MachinePointerInfo::getGOT(), false, false, true, 0);
1746     } else if (Subtarget->isTargetCOFF()) {
1747       assert(Subtarget->isTargetWindows() &&
1748              "Windows is the only supported COFF target");
1749       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1750                                  ? ARMII::MO_DLLIMPORT
1751                                  : ARMII::MO_NO_FLAG;
1752       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1753                                           TargetFlags);
1754       if (GV->hasDLLImportStorageClass())
1755         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1756                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1757                                          Callee), MachinePointerInfo::getGOT(),
1758                              false, false, false, 0);
1759     } else {
1760       // On ELF targets for PIC code, direct calls should go through the PLT
1761       unsigned OpFlags = 0;
1762       if (Subtarget->isTargetELF() &&
1763           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1764         OpFlags = ARMII::MO_PLT;
1765       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1766     }
1767   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1768     isDirect = true;
1769     bool isStub = Subtarget->isTargetMachO() &&
1770                   getTargetMachine().getRelocationModel() != Reloc::Static;
1771     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1772     // tBX takes a register source operand.
1773     const char *Sym = S->getSymbol();
1774     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1775       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1776       ARMConstantPoolValue *CPV =
1777         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1778                                       ARMPCLabelIndex, 4);
1779       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1780       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1781       Callee = DAG.getLoad(getPointerTy(), dl,
1782                            DAG.getEntryNode(), CPAddr,
1783                            MachinePointerInfo::getConstantPool(),
1784                            false, false, false, 0);
1785       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1786       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1787                            getPointerTy(), Callee, PICLabel);
1788     } else {
1789       unsigned OpFlags = 0;
1790       // On ELF targets for PIC code, direct calls should go through the PLT
1791       if (Subtarget->isTargetELF() &&
1792                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1793         OpFlags = ARMII::MO_PLT;
1794       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1795     }
1796   }
1797
1798   // FIXME: handle tail calls differently.
1799   unsigned CallOpc;
1800   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1801   if (Subtarget->isThumb()) {
1802     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1803       CallOpc = ARMISD::CALL_NOLINK;
1804     else
1805       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1806   } else {
1807     if (!isDirect && !Subtarget->hasV5TOps())
1808       CallOpc = ARMISD::CALL_NOLINK;
1809     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1810                // Emit regular call when code size is the priority
1811                !HasMinSizeAttr)
1812       // "mov lr, pc; b _foo" to avoid confusing the RSP
1813       CallOpc = ARMISD::CALL_NOLINK;
1814     else
1815       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1816   }
1817
1818   std::vector<SDValue> Ops;
1819   Ops.push_back(Chain);
1820   Ops.push_back(Callee);
1821
1822   // Add argument registers to the end of the list so that they are known live
1823   // into the call.
1824   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1825     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1826                                   RegsToPass[i].second.getValueType()));
1827
1828   // Add a register mask operand representing the call-preserved registers.
1829   if (!isTailCall) {
1830     const uint32_t *Mask;
1831     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1832     if (isThisReturn) {
1833       // For 'this' returns, use the R0-preserving mask if applicable
1834       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1835       if (!Mask) {
1836         // Set isThisReturn to false if the calling convention is not one that
1837         // allows 'returned' to be modeled in this way, so LowerCallResult does
1838         // not try to pass 'this' straight through
1839         isThisReturn = false;
1840         Mask = ARI->getCallPreservedMask(MF, CallConv);
1841       }
1842     } else
1843       Mask = ARI->getCallPreservedMask(MF, CallConv);
1844
1845     assert(Mask && "Missing call preserved mask for calling convention");
1846     Ops.push_back(DAG.getRegisterMask(Mask));
1847   }
1848
1849   if (InFlag.getNode())
1850     Ops.push_back(InFlag);
1851
1852   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1853   if (isTailCall) {
1854     MF.getFrameInfo()->setHasTailCall();
1855     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1856   }
1857
1858   // Returns a chain and a flag for retval copy to use.
1859   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1860   InFlag = Chain.getValue(1);
1861
1862   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1863                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1864   if (!Ins.empty())
1865     InFlag = Chain.getValue(1);
1866
1867   // Handle result values, copying them out of physregs into vregs that we
1868   // return.
1869   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1870                          InVals, isThisReturn,
1871                          isThisReturn ? OutVals[0] : SDValue());
1872 }
1873
1874 /// HandleByVal - Every parameter *after* a byval parameter is passed
1875 /// on the stack.  Remember the next parameter register to allocate,
1876 /// and then confiscate the rest of the parameter registers to insure
1877 /// this.
1878 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1879                                     unsigned Align) const {
1880   assert((State->getCallOrPrologue() == Prologue ||
1881           State->getCallOrPrologue() == Call) &&
1882          "unhandled ParmContext");
1883
1884   // Byval (as with any stack) slots are always at least 4 byte aligned.
1885   Align = std::max(Align, 4U);
1886
1887   unsigned Reg = State->AllocateReg(GPRArgRegs);
1888   if (!Reg)
1889     return;
1890
1891   unsigned AlignInRegs = Align / 4;
1892   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1893   for (unsigned i = 0; i < Waste; ++i)
1894     Reg = State->AllocateReg(GPRArgRegs);
1895
1896   if (!Reg)
1897     return;
1898
1899   unsigned Excess = 4 * (ARM::R4 - Reg);
1900
1901   // Special case when NSAA != SP and parameter size greater than size of
1902   // all remained GPR regs. In that case we can't split parameter, we must
1903   // send it to stack. We also must set NCRN to R4, so waste all
1904   // remained registers.
1905   const unsigned NSAAOffset = State->getNextStackOffset();
1906   if (NSAAOffset != 0 && Size > Excess) {
1907     while (State->AllocateReg(GPRArgRegs))
1908       ;
1909     return;
1910   }
1911
1912   // First register for byval parameter is the first register that wasn't
1913   // allocated before this method call, so it would be "reg".
1914   // If parameter is small enough to be saved in range [reg, r4), then
1915   // the end (first after last) register would be reg + param-size-in-regs,
1916   // else parameter would be splitted between registers and stack,
1917   // end register would be r4 in this case.
1918   unsigned ByValRegBegin = Reg;
1919   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1920   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1921   // Note, first register is allocated in the beginning of function already,
1922   // allocate remained amount of registers we need.
1923   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1924     State->AllocateReg(GPRArgRegs);
1925   // A byval parameter that is split between registers and memory needs its
1926   // size truncated here.
1927   // In the case where the entire structure fits in registers, we set the
1928   // size in memory to zero.
1929   Size = std::max<int>(Size - Excess, 0);
1930 }
1931
1932 /// MatchingStackOffset - Return true if the given stack call argument is
1933 /// already available in the same position (relatively) of the caller's
1934 /// incoming argument stack.
1935 static
1936 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1937                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1938                          const TargetInstrInfo *TII) {
1939   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1940   int FI = INT_MAX;
1941   if (Arg.getOpcode() == ISD::CopyFromReg) {
1942     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1943     if (!TargetRegisterInfo::isVirtualRegister(VR))
1944       return false;
1945     MachineInstr *Def = MRI->getVRegDef(VR);
1946     if (!Def)
1947       return false;
1948     if (!Flags.isByVal()) {
1949       if (!TII->isLoadFromStackSlot(Def, FI))
1950         return false;
1951     } else {
1952       return false;
1953     }
1954   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1955     if (Flags.isByVal())
1956       // ByVal argument is passed in as a pointer but it's now being
1957       // dereferenced. e.g.
1958       // define @foo(%struct.X* %A) {
1959       //   tail call @bar(%struct.X* byval %A)
1960       // }
1961       return false;
1962     SDValue Ptr = Ld->getBasePtr();
1963     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1964     if (!FINode)
1965       return false;
1966     FI = FINode->getIndex();
1967   } else
1968     return false;
1969
1970   assert(FI != INT_MAX);
1971   if (!MFI->isFixedObjectIndex(FI))
1972     return false;
1973   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1974 }
1975
1976 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1977 /// for tail call optimization. Targets which want to do tail call
1978 /// optimization should implement this function.
1979 bool
1980 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1981                                                      CallingConv::ID CalleeCC,
1982                                                      bool isVarArg,
1983                                                      bool isCalleeStructRet,
1984                                                      bool isCallerStructRet,
1985                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1986                                     const SmallVectorImpl<SDValue> &OutVals,
1987                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1988                                                      SelectionDAG& DAG) const {
1989   const Function *CallerF = DAG.getMachineFunction().getFunction();
1990   CallingConv::ID CallerCC = CallerF->getCallingConv();
1991   bool CCMatch = CallerCC == CalleeCC;
1992
1993   // Look for obvious safe cases to perform tail call optimization that do not
1994   // require ABI changes. This is what gcc calls sibcall.
1995
1996   // Do not sibcall optimize vararg calls unless the call site is not passing
1997   // any arguments.
1998   if (isVarArg && !Outs.empty())
1999     return false;
2000
2001   // Exception-handling functions need a special set of instructions to indicate
2002   // a return to the hardware. Tail-calling another function would probably
2003   // break this.
2004   if (CallerF->hasFnAttribute("interrupt"))
2005     return false;
2006
2007   // Also avoid sibcall optimization if either caller or callee uses struct
2008   // return semantics.
2009   if (isCalleeStructRet || isCallerStructRet)
2010     return false;
2011
2012   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2013   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2014   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2015   // support in the assembler and linker to be used. This would need to be
2016   // fixed to fully support tail calls in Thumb1.
2017   //
2018   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2019   // LR.  This means if we need to reload LR, it takes an extra instructions,
2020   // which outweighs the value of the tail call; but here we don't know yet
2021   // whether LR is going to be used.  Probably the right approach is to
2022   // generate the tail call here and turn it back into CALL/RET in
2023   // emitEpilogue if LR is used.
2024
2025   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2026   // but we need to make sure there are enough registers; the only valid
2027   // registers are the 4 used for parameters.  We don't currently do this
2028   // case.
2029   if (Subtarget->isThumb1Only())
2030     return false;
2031
2032   // Externally-defined functions with weak linkage should not be
2033   // tail-called on ARM when the OS does not support dynamic
2034   // pre-emption of symbols, as the AAELF spec requires normal calls
2035   // to undefined weak functions to be replaced with a NOP or jump to the
2036   // next instruction. The behaviour of branch instructions in this
2037   // situation (as used for tail calls) is implementation-defined, so we
2038   // cannot rely on the linker replacing the tail call with a return.
2039   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2040     const GlobalValue *GV = G->getGlobal();
2041     const Triple &TT = getTargetMachine().getTargetTriple();
2042     if (GV->hasExternalWeakLinkage() &&
2043         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2044       return false;
2045   }
2046
2047   // If the calling conventions do not match, then we'd better make sure the
2048   // results are returned in the same way as what the caller expects.
2049   if (!CCMatch) {
2050     SmallVector<CCValAssign, 16> RVLocs1;
2051     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2052                        *DAG.getContext(), Call);
2053     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2054
2055     SmallVector<CCValAssign, 16> RVLocs2;
2056     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2057                        *DAG.getContext(), Call);
2058     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2059
2060     if (RVLocs1.size() != RVLocs2.size())
2061       return false;
2062     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2063       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2064         return false;
2065       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2066         return false;
2067       if (RVLocs1[i].isRegLoc()) {
2068         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2069           return false;
2070       } else {
2071         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2072           return false;
2073       }
2074     }
2075   }
2076
2077   // If Caller's vararg or byval argument has been split between registers and
2078   // stack, do not perform tail call, since part of the argument is in caller's
2079   // local frame.
2080   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2081                                       getInfo<ARMFunctionInfo>();
2082   if (AFI_Caller->getArgRegsSaveSize())
2083     return false;
2084
2085   // If the callee takes no arguments then go on to check the results of the
2086   // call.
2087   if (!Outs.empty()) {
2088     // Check if stack adjustment is needed. For now, do not do this if any
2089     // argument is passed on the stack.
2090     SmallVector<CCValAssign, 16> ArgLocs;
2091     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2092                       *DAG.getContext(), Call);
2093     CCInfo.AnalyzeCallOperands(Outs,
2094                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2095     if (CCInfo.getNextStackOffset()) {
2096       MachineFunction &MF = DAG.getMachineFunction();
2097
2098       // Check if the arguments are already laid out in the right way as
2099       // the caller's fixed stack objects.
2100       MachineFrameInfo *MFI = MF.getFrameInfo();
2101       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2102       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2103       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2104            i != e;
2105            ++i, ++realArgIdx) {
2106         CCValAssign &VA = ArgLocs[i];
2107         EVT RegVT = VA.getLocVT();
2108         SDValue Arg = OutVals[realArgIdx];
2109         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2110         if (VA.getLocInfo() == CCValAssign::Indirect)
2111           return false;
2112         if (VA.needsCustom()) {
2113           // f64 and vector types are split into multiple registers or
2114           // register/stack-slot combinations.  The types will not match
2115           // the registers; give up on memory f64 refs until we figure
2116           // out what to do about this.
2117           if (!VA.isRegLoc())
2118             return false;
2119           if (!ArgLocs[++i].isRegLoc())
2120             return false;
2121           if (RegVT == MVT::v2f64) {
2122             if (!ArgLocs[++i].isRegLoc())
2123               return false;
2124             if (!ArgLocs[++i].isRegLoc())
2125               return false;
2126           }
2127         } else if (!VA.isRegLoc()) {
2128           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2129                                    MFI, MRI, TII))
2130             return false;
2131         }
2132       }
2133     }
2134   }
2135
2136   return true;
2137 }
2138
2139 bool
2140 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2141                                   MachineFunction &MF, bool isVarArg,
2142                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2143                                   LLVMContext &Context) const {
2144   SmallVector<CCValAssign, 16> RVLocs;
2145   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2146   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2147                                                     isVarArg));
2148 }
2149
2150 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2151                                     SDLoc DL, SelectionDAG &DAG) {
2152   const MachineFunction &MF = DAG.getMachineFunction();
2153   const Function *F = MF.getFunction();
2154
2155   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2156
2157   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2158   // version of the "preferred return address". These offsets affect the return
2159   // instruction if this is a return from PL1 without hypervisor extensions.
2160   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2161   //    SWI:     0      "subs pc, lr, #0"
2162   //    ABORT:   +4     "subs pc, lr, #4"
2163   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2164   // UNDEF varies depending on where the exception came from ARM or Thumb
2165   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2166
2167   int64_t LROffset;
2168   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2169       IntKind == "ABORT")
2170     LROffset = 4;
2171   else if (IntKind == "SWI" || IntKind == "UNDEF")
2172     LROffset = 0;
2173   else
2174     report_fatal_error("Unsupported interrupt attribute. If present, value "
2175                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2176
2177   RetOps.insert(RetOps.begin() + 1,
2178                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2179
2180   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2181 }
2182
2183 SDValue
2184 ARMTargetLowering::LowerReturn(SDValue Chain,
2185                                CallingConv::ID CallConv, bool isVarArg,
2186                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2187                                const SmallVectorImpl<SDValue> &OutVals,
2188                                SDLoc dl, SelectionDAG &DAG) const {
2189
2190   // CCValAssign - represent the assignment of the return value to a location.
2191   SmallVector<CCValAssign, 16> RVLocs;
2192
2193   // CCState - Info about the registers and stack slots.
2194   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2195                     *DAG.getContext(), Call);
2196
2197   // Analyze outgoing return values.
2198   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2199                                                isVarArg));
2200
2201   SDValue Flag;
2202   SmallVector<SDValue, 4> RetOps;
2203   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2204   bool isLittleEndian = Subtarget->isLittle();
2205
2206   MachineFunction &MF = DAG.getMachineFunction();
2207   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2208   AFI->setReturnRegsCount(RVLocs.size());
2209
2210   // Copy the result values into the output registers.
2211   for (unsigned i = 0, realRVLocIdx = 0;
2212        i != RVLocs.size();
2213        ++i, ++realRVLocIdx) {
2214     CCValAssign &VA = RVLocs[i];
2215     assert(VA.isRegLoc() && "Can only return in registers!");
2216
2217     SDValue Arg = OutVals[realRVLocIdx];
2218
2219     switch (VA.getLocInfo()) {
2220     default: llvm_unreachable("Unknown loc info!");
2221     case CCValAssign::Full: break;
2222     case CCValAssign::BCvt:
2223       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2224       break;
2225     }
2226
2227     if (VA.needsCustom()) {
2228       if (VA.getLocVT() == MVT::v2f64) {
2229         // Extract the first half and return it in two registers.
2230         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2231                                    DAG.getConstant(0, dl, MVT::i32));
2232         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2233                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2234
2235         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2236                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2237                                  Flag);
2238         Flag = Chain.getValue(1);
2239         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2240         VA = RVLocs[++i]; // skip ahead to next loc
2241         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2242                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2243                                  Flag);
2244         Flag = Chain.getValue(1);
2245         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2246         VA = RVLocs[++i]; // skip ahead to next loc
2247
2248         // Extract the 2nd half and fall through to handle it as an f64 value.
2249         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2250                           DAG.getConstant(1, dl, MVT::i32));
2251       }
2252       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2253       // available.
2254       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2255                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2256       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2257                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2258                                Flag);
2259       Flag = Chain.getValue(1);
2260       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2261       VA = RVLocs[++i]; // skip ahead to next loc
2262       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2263                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2264                                Flag);
2265     } else
2266       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2267
2268     // Guarantee that all emitted copies are
2269     // stuck together, avoiding something bad.
2270     Flag = Chain.getValue(1);
2271     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2272   }
2273
2274   // Update chain and glue.
2275   RetOps[0] = Chain;
2276   if (Flag.getNode())
2277     RetOps.push_back(Flag);
2278
2279   // CPUs which aren't M-class use a special sequence to return from
2280   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2281   // though we use "subs pc, lr, #N").
2282   //
2283   // M-class CPUs actually use a normal return sequence with a special
2284   // (hardware-provided) value in LR, so the normal code path works.
2285   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2286       !Subtarget->isMClass()) {
2287     if (Subtarget->isThumb1Only())
2288       report_fatal_error("interrupt attribute is not supported in Thumb1");
2289     return LowerInterruptReturn(RetOps, dl, DAG);
2290   }
2291
2292   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2293 }
2294
2295 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2296   if (N->getNumValues() != 1)
2297     return false;
2298   if (!N->hasNUsesOfValue(1, 0))
2299     return false;
2300
2301   SDValue TCChain = Chain;
2302   SDNode *Copy = *N->use_begin();
2303   if (Copy->getOpcode() == ISD::CopyToReg) {
2304     // If the copy has a glue operand, we conservatively assume it isn't safe to
2305     // perform a tail call.
2306     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2307       return false;
2308     TCChain = Copy->getOperand(0);
2309   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2310     SDNode *VMov = Copy;
2311     // f64 returned in a pair of GPRs.
2312     SmallPtrSet<SDNode*, 2> Copies;
2313     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2314          UI != UE; ++UI) {
2315       if (UI->getOpcode() != ISD::CopyToReg)
2316         return false;
2317       Copies.insert(*UI);
2318     }
2319     if (Copies.size() > 2)
2320       return false;
2321
2322     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2323          UI != UE; ++UI) {
2324       SDValue UseChain = UI->getOperand(0);
2325       if (Copies.count(UseChain.getNode()))
2326         // Second CopyToReg
2327         Copy = *UI;
2328       else {
2329         // We are at the top of this chain.
2330         // If the copy has a glue operand, we conservatively assume it
2331         // isn't safe to perform a tail call.
2332         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2333           return false;
2334         // First CopyToReg
2335         TCChain = UseChain;
2336       }
2337     }
2338   } else if (Copy->getOpcode() == ISD::BITCAST) {
2339     // f32 returned in a single GPR.
2340     if (!Copy->hasOneUse())
2341       return false;
2342     Copy = *Copy->use_begin();
2343     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2344       return false;
2345     // If the copy has a glue operand, we conservatively assume it isn't safe to
2346     // perform a tail call.
2347     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2348       return false;
2349     TCChain = Copy->getOperand(0);
2350   } else {
2351     return false;
2352   }
2353
2354   bool HasRet = false;
2355   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2356        UI != UE; ++UI) {
2357     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2358         UI->getOpcode() != ARMISD::INTRET_FLAG)
2359       return false;
2360     HasRet = true;
2361   }
2362
2363   if (!HasRet)
2364     return false;
2365
2366   Chain = TCChain;
2367   return true;
2368 }
2369
2370 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2371   if (!Subtarget->supportsTailCall())
2372     return false;
2373
2374   auto Attr =
2375       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2376   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2377     return false;
2378
2379   return !Subtarget->isThumb1Only();
2380 }
2381
2382 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2383 // and pass the lower and high parts through.
2384 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2385   SDLoc DL(Op);
2386   SDValue WriteValue = Op->getOperand(2);
2387
2388   // This function is only supposed to be called for i64 type argument.
2389   assert(WriteValue.getValueType() == MVT::i64
2390           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2391
2392   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2393                            DAG.getConstant(0, DL, MVT::i32));
2394   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2395                            DAG.getConstant(1, DL, MVT::i32));
2396   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2397   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2398 }
2399
2400 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2401 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2402 // one of the above mentioned nodes. It has to be wrapped because otherwise
2403 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2404 // be used to form addressing mode. These wrapped nodes will be selected
2405 // into MOVi.
2406 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2407   EVT PtrVT = Op.getValueType();
2408   // FIXME there is no actual debug info here
2409   SDLoc dl(Op);
2410   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2411   SDValue Res;
2412   if (CP->isMachineConstantPoolEntry())
2413     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2414                                     CP->getAlignment());
2415   else
2416     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2417                                     CP->getAlignment());
2418   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2419 }
2420
2421 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2422   return MachineJumpTableInfo::EK_Inline;
2423 }
2424
2425 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2426                                              SelectionDAG &DAG) const {
2427   MachineFunction &MF = DAG.getMachineFunction();
2428   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2429   unsigned ARMPCLabelIndex = 0;
2430   SDLoc DL(Op);
2431   EVT PtrVT = getPointerTy();
2432   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2433   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2434   SDValue CPAddr;
2435   if (RelocM == Reloc::Static) {
2436     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2437   } else {
2438     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2439     ARMPCLabelIndex = AFI->createPICLabelUId();
2440     ARMConstantPoolValue *CPV =
2441       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2442                                       ARMCP::CPBlockAddress, PCAdj);
2443     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2444   }
2445   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2446   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2447                                MachinePointerInfo::getConstantPool(),
2448                                false, false, false, 0);
2449   if (RelocM == Reloc::Static)
2450     return Result;
2451   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2452   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2453 }
2454
2455 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2456 SDValue
2457 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2458                                                  SelectionDAG &DAG) const {
2459   SDLoc dl(GA);
2460   EVT PtrVT = getPointerTy();
2461   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2462   MachineFunction &MF = DAG.getMachineFunction();
2463   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2464   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2465   ARMConstantPoolValue *CPV =
2466     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2467                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2468   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2469   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2470   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2471                          MachinePointerInfo::getConstantPool(),
2472                          false, false, false, 0);
2473   SDValue Chain = Argument.getValue(1);
2474
2475   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2476   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2477
2478   // call __tls_get_addr.
2479   ArgListTy Args;
2480   ArgListEntry Entry;
2481   Entry.Node = Argument;
2482   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2483   Args.push_back(Entry);
2484
2485   // FIXME: is there useful debug info available here?
2486   TargetLowering::CallLoweringInfo CLI(DAG);
2487   CLI.setDebugLoc(dl).setChain(Chain)
2488     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2489                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2490                0);
2491
2492   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2493   return CallResult.first;
2494 }
2495
2496 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2497 // "local exec" model.
2498 SDValue
2499 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2500                                         SelectionDAG &DAG,
2501                                         TLSModel::Model model) const {
2502   const GlobalValue *GV = GA->getGlobal();
2503   SDLoc dl(GA);
2504   SDValue Offset;
2505   SDValue Chain = DAG.getEntryNode();
2506   EVT PtrVT = getPointerTy();
2507   // Get the Thread Pointer
2508   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2509
2510   if (model == TLSModel::InitialExec) {
2511     MachineFunction &MF = DAG.getMachineFunction();
2512     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2513     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2514     // Initial exec model.
2515     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2516     ARMConstantPoolValue *CPV =
2517       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2518                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2519                                       true);
2520     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2521     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2522     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2523                          MachinePointerInfo::getConstantPool(),
2524                          false, false, false, 0);
2525     Chain = Offset.getValue(1);
2526
2527     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2528     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2529
2530     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2531                          MachinePointerInfo::getConstantPool(),
2532                          false, false, false, 0);
2533   } else {
2534     // local exec model
2535     assert(model == TLSModel::LocalExec);
2536     ARMConstantPoolValue *CPV =
2537       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2538     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2539     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2540     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2541                          MachinePointerInfo::getConstantPool(),
2542                          false, false, false, 0);
2543   }
2544
2545   // The address of the thread local variable is the add of the thread
2546   // pointer with the offset of the variable.
2547   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2548 }
2549
2550 SDValue
2551 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2552   // TODO: implement the "local dynamic" model
2553   assert(Subtarget->isTargetELF() &&
2554          "TLS not implemented for non-ELF targets");
2555   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2556
2557   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2558
2559   switch (model) {
2560     case TLSModel::GeneralDynamic:
2561     case TLSModel::LocalDynamic:
2562       return LowerToTLSGeneralDynamicModel(GA, DAG);
2563     case TLSModel::InitialExec:
2564     case TLSModel::LocalExec:
2565       return LowerToTLSExecModels(GA, DAG, model);
2566   }
2567   llvm_unreachable("bogus TLS model");
2568 }
2569
2570 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2571                                                  SelectionDAG &DAG) const {
2572   EVT PtrVT = getPointerTy();
2573   SDLoc dl(Op);
2574   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2575   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2576     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2577     ARMConstantPoolValue *CPV =
2578       ARMConstantPoolConstant::Create(GV,
2579                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2580     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2581     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2582     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2583                                  CPAddr,
2584                                  MachinePointerInfo::getConstantPool(),
2585                                  false, false, false, 0);
2586     SDValue Chain = Result.getValue(1);
2587     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2588     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2589     if (!UseGOTOFF)
2590       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2591                            MachinePointerInfo::getGOT(),
2592                            false, false, false, 0);
2593     return Result;
2594   }
2595
2596   // If we have T2 ops, we can materialize the address directly via movt/movw
2597   // pair. This is always cheaper.
2598   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2599     ++NumMovwMovt;
2600     // FIXME: Once remat is capable of dealing with instructions with register
2601     // operands, expand this into two nodes.
2602     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2603                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2604   } else {
2605     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2606     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2607     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2608                        MachinePointerInfo::getConstantPool(),
2609                        false, false, false, 0);
2610   }
2611 }
2612
2613 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2614                                                     SelectionDAG &DAG) const {
2615   EVT PtrVT = getPointerTy();
2616   SDLoc dl(Op);
2617   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2618   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2619
2620   if (Subtarget->useMovt(DAG.getMachineFunction()))
2621     ++NumMovwMovt;
2622
2623   // FIXME: Once remat is capable of dealing with instructions with register
2624   // operands, expand this into multiple nodes
2625   unsigned Wrapper =
2626       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2627
2628   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2629   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2630
2631   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2632     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2633                          MachinePointerInfo::getGOT(), false, false, false, 0);
2634   return Result;
2635 }
2636
2637 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2638                                                      SelectionDAG &DAG) const {
2639   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2640   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2641          "Windows on ARM expects to use movw/movt");
2642
2643   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2644   const ARMII::TOF TargetFlags =
2645     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2646   EVT PtrVT = getPointerTy();
2647   SDValue Result;
2648   SDLoc DL(Op);
2649
2650   ++NumMovwMovt;
2651
2652   // FIXME: Once remat is capable of dealing with instructions with register
2653   // operands, expand this into two nodes.
2654   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2655                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2656                                                   TargetFlags));
2657   if (GV->hasDLLImportStorageClass())
2658     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2659                          MachinePointerInfo::getGOT(), false, false, false, 0);
2660   return Result;
2661 }
2662
2663 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2664                                                     SelectionDAG &DAG) const {
2665   assert(Subtarget->isTargetELF() &&
2666          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2667   MachineFunction &MF = DAG.getMachineFunction();
2668   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2669   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2670   EVT PtrVT = getPointerTy();
2671   SDLoc dl(Op);
2672   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2673   ARMConstantPoolValue *CPV =
2674     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2675                                   ARMPCLabelIndex, PCAdj);
2676   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2677   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2678   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2679                                MachinePointerInfo::getConstantPool(),
2680                                false, false, false, 0);
2681   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2682   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2683 }
2684
2685 SDValue
2686 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2687   SDLoc dl(Op);
2688   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2689   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2690                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2691                      Op.getOperand(1), Val);
2692 }
2693
2694 SDValue
2695 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2696   SDLoc dl(Op);
2697   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2698                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2699 }
2700
2701 SDValue
2702 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2703                                           const ARMSubtarget *Subtarget) const {
2704   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2705   SDLoc dl(Op);
2706   switch (IntNo) {
2707   default: return SDValue();    // Don't custom lower most intrinsics.
2708   case Intrinsic::arm_rbit: {
2709     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2710            "RBIT intrinsic must have i32 type!");
2711     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2712   }
2713   case Intrinsic::arm_thread_pointer: {
2714     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2715     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2716   }
2717   case Intrinsic::eh_sjlj_lsda: {
2718     MachineFunction &MF = DAG.getMachineFunction();
2719     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2720     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2721     EVT PtrVT = getPointerTy();
2722     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2723     SDValue CPAddr;
2724     unsigned PCAdj = (RelocM != Reloc::PIC_)
2725       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2726     ARMConstantPoolValue *CPV =
2727       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2728                                       ARMCP::CPLSDA, PCAdj);
2729     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2730     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2731     SDValue Result =
2732       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2733                   MachinePointerInfo::getConstantPool(),
2734                   false, false, false, 0);
2735
2736     if (RelocM == Reloc::PIC_) {
2737       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2738       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2739     }
2740     return Result;
2741   }
2742   case Intrinsic::arm_neon_vmulls:
2743   case Intrinsic::arm_neon_vmullu: {
2744     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2745       ? ARMISD::VMULLs : ARMISD::VMULLu;
2746     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2747                        Op.getOperand(1), Op.getOperand(2));
2748   }
2749   }
2750 }
2751
2752 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2753                                  const ARMSubtarget *Subtarget) {
2754   // FIXME: handle "fence singlethread" more efficiently.
2755   SDLoc dl(Op);
2756   if (!Subtarget->hasDataBarrier()) {
2757     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2758     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2759     // here.
2760     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2761            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2762     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2763                        DAG.getConstant(0, dl, MVT::i32));
2764   }
2765
2766   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2767   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2768   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2769   if (Subtarget->isMClass()) {
2770     // Only a full system barrier exists in the M-class architectures.
2771     Domain = ARM_MB::SY;
2772   } else if (Subtarget->isSwift() && Ord == Release) {
2773     // Swift happens to implement ISHST barriers in a way that's compatible with
2774     // Release semantics but weaker than ISH so we'd be fools not to use
2775     // it. Beware: other processors probably don't!
2776     Domain = ARM_MB::ISHST;
2777   }
2778
2779   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2780                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2781                      DAG.getConstant(Domain, dl, MVT::i32));
2782 }
2783
2784 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2785                              const ARMSubtarget *Subtarget) {
2786   // ARM pre v5TE and Thumb1 does not have preload instructions.
2787   if (!(Subtarget->isThumb2() ||
2788         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2789     // Just preserve the chain.
2790     return Op.getOperand(0);
2791
2792   SDLoc dl(Op);
2793   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2794   if (!isRead &&
2795       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2796     // ARMv7 with MP extension has PLDW.
2797     return Op.getOperand(0);
2798
2799   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2800   if (Subtarget->isThumb()) {
2801     // Invert the bits.
2802     isRead = ~isRead & 1;
2803     isData = ~isData & 1;
2804   }
2805
2806   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2807                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2808                      DAG.getConstant(isData, dl, MVT::i32));
2809 }
2810
2811 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2812   MachineFunction &MF = DAG.getMachineFunction();
2813   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2814
2815   // vastart just stores the address of the VarArgsFrameIndex slot into the
2816   // memory location argument.
2817   SDLoc dl(Op);
2818   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2819   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2820   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2821   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2822                       MachinePointerInfo(SV), false, false, 0);
2823 }
2824
2825 SDValue
2826 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2827                                         SDValue &Root, SelectionDAG &DAG,
2828                                         SDLoc dl) const {
2829   MachineFunction &MF = DAG.getMachineFunction();
2830   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2831
2832   const TargetRegisterClass *RC;
2833   if (AFI->isThumb1OnlyFunction())
2834     RC = &ARM::tGPRRegClass;
2835   else
2836     RC = &ARM::GPRRegClass;
2837
2838   // Transform the arguments stored in physical registers into virtual ones.
2839   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2840   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2841
2842   SDValue ArgValue2;
2843   if (NextVA.isMemLoc()) {
2844     MachineFrameInfo *MFI = MF.getFrameInfo();
2845     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2846
2847     // Create load node to retrieve arguments from the stack.
2848     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2849     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2850                             MachinePointerInfo::getFixedStack(FI),
2851                             false, false, false, 0);
2852   } else {
2853     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2854     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2855   }
2856   if (!Subtarget->isLittle())
2857     std::swap (ArgValue, ArgValue2);
2858   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2859 }
2860
2861 // The remaining GPRs hold either the beginning of variable-argument
2862 // data, or the beginning of an aggregate passed by value (usually
2863 // byval).  Either way, we allocate stack slots adjacent to the data
2864 // provided by our caller, and store the unallocated registers there.
2865 // If this is a variadic function, the va_list pointer will begin with
2866 // these values; otherwise, this reassembles a (byval) structure that
2867 // was split between registers and memory.
2868 // Return: The frame index registers were stored into.
2869 int
2870 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2871                                   SDLoc dl, SDValue &Chain,
2872                                   const Value *OrigArg,
2873                                   unsigned InRegsParamRecordIdx,
2874                                   int ArgOffset,
2875                                   unsigned ArgSize) const {
2876   // Currently, two use-cases possible:
2877   // Case #1. Non-var-args function, and we meet first byval parameter.
2878   //          Setup first unallocated register as first byval register;
2879   //          eat all remained registers
2880   //          (these two actions are performed by HandleByVal method).
2881   //          Then, here, we initialize stack frame with
2882   //          "store-reg" instructions.
2883   // Case #2. Var-args function, that doesn't contain byval parameters.
2884   //          The same: eat all remained unallocated registers,
2885   //          initialize stack frame.
2886
2887   MachineFunction &MF = DAG.getMachineFunction();
2888   MachineFrameInfo *MFI = MF.getFrameInfo();
2889   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2890   unsigned RBegin, REnd;
2891   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2892     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2893   } else {
2894     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2895     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2896     REnd = ARM::R4;
2897   }
2898
2899   if (REnd != RBegin)
2900     ArgOffset = -4 * (ARM::R4 - RBegin);
2901
2902   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2903   SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2904
2905   SmallVector<SDValue, 4> MemOps;
2906   const TargetRegisterClass *RC =
2907       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2908
2909   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2910     unsigned VReg = MF.addLiveIn(Reg, RC);
2911     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2912     SDValue Store =
2913         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2914                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2915     MemOps.push_back(Store);
2916     FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2917                       DAG.getConstant(4, dl, getPointerTy()));
2918   }
2919
2920   if (!MemOps.empty())
2921     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2922   return FrameIndex;
2923 }
2924
2925 // Setup stack frame, the va_list pointer will start from.
2926 void
2927 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2928                                         SDLoc dl, SDValue &Chain,
2929                                         unsigned ArgOffset,
2930                                         unsigned TotalArgRegsSaveSize,
2931                                         bool ForceMutable) const {
2932   MachineFunction &MF = DAG.getMachineFunction();
2933   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2934
2935   // Try to store any remaining integer argument regs
2936   // to their spots on the stack so that they may be loaded by deferencing
2937   // the result of va_next.
2938   // If there is no regs to be stored, just point address after last
2939   // argument passed via stack.
2940   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2941                                   CCInfo.getInRegsParamsCount(),
2942                                   CCInfo.getNextStackOffset(), 4);
2943   AFI->setVarArgsFrameIndex(FrameIndex);
2944 }
2945
2946 SDValue
2947 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2948                                         CallingConv::ID CallConv, bool isVarArg,
2949                                         const SmallVectorImpl<ISD::InputArg>
2950                                           &Ins,
2951                                         SDLoc dl, SelectionDAG &DAG,
2952                                         SmallVectorImpl<SDValue> &InVals)
2953                                           const {
2954   MachineFunction &MF = DAG.getMachineFunction();
2955   MachineFrameInfo *MFI = MF.getFrameInfo();
2956
2957   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2958
2959   // Assign locations to all of the incoming arguments.
2960   SmallVector<CCValAssign, 16> ArgLocs;
2961   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2962                     *DAG.getContext(), Prologue);
2963   CCInfo.AnalyzeFormalArguments(Ins,
2964                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2965                                                   isVarArg));
2966
2967   SmallVector<SDValue, 16> ArgValues;
2968   SDValue ArgValue;
2969   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2970   unsigned CurArgIdx = 0;
2971
2972   // Initially ArgRegsSaveSize is zero.
2973   // Then we increase this value each time we meet byval parameter.
2974   // We also increase this value in case of varargs function.
2975   AFI->setArgRegsSaveSize(0);
2976
2977   // Calculate the amount of stack space that we need to allocate to store
2978   // byval and variadic arguments that are passed in registers.
2979   // We need to know this before we allocate the first byval or variadic
2980   // argument, as they will be allocated a stack slot below the CFA (Canonical
2981   // Frame Address, the stack pointer at entry to the function).
2982   unsigned ArgRegBegin = ARM::R4;
2983   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2984     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
2985       break;
2986
2987     CCValAssign &VA = ArgLocs[i];
2988     unsigned Index = VA.getValNo();
2989     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
2990     if (!Flags.isByVal())
2991       continue;
2992
2993     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
2994     unsigned RBegin, REnd;
2995     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
2996     ArgRegBegin = std::min(ArgRegBegin, RBegin);
2997
2998     CCInfo.nextInRegsParam();
2999   }
3000   CCInfo.rewindByValRegsInfo();
3001
3002   int lastInsIndex = -1;
3003   if (isVarArg && MFI->hasVAStart()) {
3004     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3005     if (RegIdx != array_lengthof(GPRArgRegs))
3006       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3007   }
3008
3009   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3010   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3011
3012   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3013     CCValAssign &VA = ArgLocs[i];
3014     if (Ins[VA.getValNo()].isOrigArg()) {
3015       std::advance(CurOrigArg,
3016                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3017       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3018     }
3019     // Arguments stored in registers.
3020     if (VA.isRegLoc()) {
3021       EVT RegVT = VA.getLocVT();
3022
3023       if (VA.needsCustom()) {
3024         // f64 and vector types are split up into multiple registers or
3025         // combinations of registers and stack slots.
3026         if (VA.getLocVT() == MVT::v2f64) {
3027           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3028                                                    Chain, DAG, dl);
3029           VA = ArgLocs[++i]; // skip ahead to next loc
3030           SDValue ArgValue2;
3031           if (VA.isMemLoc()) {
3032             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3033             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3034             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3035                                     MachinePointerInfo::getFixedStack(FI),
3036                                     false, false, false, 0);
3037           } else {
3038             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3039                                              Chain, DAG, dl);
3040           }
3041           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3042           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3043                                  ArgValue, ArgValue1,
3044                                  DAG.getIntPtrConstant(0, dl));
3045           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3046                                  ArgValue, ArgValue2,
3047                                  DAG.getIntPtrConstant(1, dl));
3048         } else
3049           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3050
3051       } else {
3052         const TargetRegisterClass *RC;
3053
3054         if (RegVT == MVT::f32)
3055           RC = &ARM::SPRRegClass;
3056         else if (RegVT == MVT::f64)
3057           RC = &ARM::DPRRegClass;
3058         else if (RegVT == MVT::v2f64)
3059           RC = &ARM::QPRRegClass;
3060         else if (RegVT == MVT::i32)
3061           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3062                                            : &ARM::GPRRegClass;
3063         else
3064           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3065
3066         // Transform the arguments in physical registers into virtual ones.
3067         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3068         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3069       }
3070
3071       // If this is an 8 or 16-bit value, it is really passed promoted
3072       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3073       // truncate to the right size.
3074       switch (VA.getLocInfo()) {
3075       default: llvm_unreachable("Unknown loc info!");
3076       case CCValAssign::Full: break;
3077       case CCValAssign::BCvt:
3078         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3079         break;
3080       case CCValAssign::SExt:
3081         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3082                                DAG.getValueType(VA.getValVT()));
3083         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3084         break;
3085       case CCValAssign::ZExt:
3086         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3087                                DAG.getValueType(VA.getValVT()));
3088         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3089         break;
3090       }
3091
3092       InVals.push_back(ArgValue);
3093
3094     } else { // VA.isRegLoc()
3095
3096       // sanity check
3097       assert(VA.isMemLoc());
3098       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3099
3100       int index = VA.getValNo();
3101
3102       // Some Ins[] entries become multiple ArgLoc[] entries.
3103       // Process them only once.
3104       if (index != lastInsIndex)
3105         {
3106           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3107           // FIXME: For now, all byval parameter objects are marked mutable.
3108           // This can be changed with more analysis.
3109           // In case of tail call optimization mark all arguments mutable.
3110           // Since they could be overwritten by lowering of arguments in case of
3111           // a tail call.
3112           if (Flags.isByVal()) {
3113             assert(Ins[index].isOrigArg() &&
3114                    "Byval arguments cannot be implicit");
3115             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3116
3117             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3118                                             CurByValIndex, VA.getLocMemOffset(),
3119                                             Flags.getByValSize());
3120             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3121             CCInfo.nextInRegsParam();
3122           } else {
3123             unsigned FIOffset = VA.getLocMemOffset();
3124             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3125                                             FIOffset, true);
3126
3127             // Create load nodes to retrieve arguments from the stack.
3128             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3129             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3130                                          MachinePointerInfo::getFixedStack(FI),
3131                                          false, false, false, 0));
3132           }
3133           lastInsIndex = index;
3134         }
3135     }
3136   }
3137
3138   // varargs
3139   if (isVarArg && MFI->hasVAStart())
3140     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3141                          CCInfo.getNextStackOffset(),
3142                          TotalArgRegsSaveSize);
3143
3144   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3145
3146   return Chain;
3147 }
3148
3149 /// isFloatingPointZero - Return true if this is +0.0.
3150 static bool isFloatingPointZero(SDValue Op) {
3151   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3152     return CFP->getValueAPF().isPosZero();
3153   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3154     // Maybe this has already been legalized into the constant pool?
3155     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3156       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3157       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3158         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3159           return CFP->getValueAPF().isPosZero();
3160     }
3161   } else if (Op->getOpcode() == ISD::BITCAST &&
3162              Op->getValueType(0) == MVT::f64) {
3163     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3164     // created by LowerConstantFP().
3165     SDValue BitcastOp = Op->getOperand(0);
3166     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3167       SDValue MoveOp = BitcastOp->getOperand(0);
3168       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3169           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3170         return true;
3171       }
3172     }
3173   }
3174   return false;
3175 }
3176
3177 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3178 /// the given operands.
3179 SDValue
3180 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3181                              SDValue &ARMcc, SelectionDAG &DAG,
3182                              SDLoc dl) const {
3183   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3184     unsigned C = RHSC->getZExtValue();
3185     if (!isLegalICmpImmediate(C)) {
3186       // Constant does not fit, try adjusting it by one?
3187       switch (CC) {
3188       default: break;
3189       case ISD::SETLT:
3190       case ISD::SETGE:
3191         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3192           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3193           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3194         }
3195         break;
3196       case ISD::SETULT:
3197       case ISD::SETUGE:
3198         if (C != 0 && isLegalICmpImmediate(C-1)) {
3199           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3200           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3201         }
3202         break;
3203       case ISD::SETLE:
3204       case ISD::SETGT:
3205         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3206           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3207           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3208         }
3209         break;
3210       case ISD::SETULE:
3211       case ISD::SETUGT:
3212         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3213           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3214           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3215         }
3216         break;
3217       }
3218     }
3219   }
3220
3221   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3222   ARMISD::NodeType CompareType;
3223   switch (CondCode) {
3224   default:
3225     CompareType = ARMISD::CMP;
3226     break;
3227   case ARMCC::EQ:
3228   case ARMCC::NE:
3229     // Uses only Z Flag
3230     CompareType = ARMISD::CMPZ;
3231     break;
3232   }
3233   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3234   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3235 }
3236
3237 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3238 SDValue
3239 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3240                              SDLoc dl) const {
3241   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3242   SDValue Cmp;
3243   if (!isFloatingPointZero(RHS))
3244     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3245   else
3246     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3247   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3248 }
3249
3250 /// duplicateCmp - Glue values can have only one use, so this function
3251 /// duplicates a comparison node.
3252 SDValue
3253 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3254   unsigned Opc = Cmp.getOpcode();
3255   SDLoc DL(Cmp);
3256   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3257     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3258
3259   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3260   Cmp = Cmp.getOperand(0);
3261   Opc = Cmp.getOpcode();
3262   if (Opc == ARMISD::CMPFP)
3263     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3264   else {
3265     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3266     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3267   }
3268   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3269 }
3270
3271 std::pair<SDValue, SDValue>
3272 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3273                                  SDValue &ARMcc) const {
3274   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3275
3276   SDValue Value, OverflowCmp;
3277   SDValue LHS = Op.getOperand(0);
3278   SDValue RHS = Op.getOperand(1);
3279   SDLoc dl(Op);
3280
3281   // FIXME: We are currently always generating CMPs because we don't support
3282   // generating CMN through the backend. This is not as good as the natural
3283   // CMP case because it causes a register dependency and cannot be folded
3284   // later.
3285
3286   switch (Op.getOpcode()) {
3287   default:
3288     llvm_unreachable("Unknown overflow instruction!");
3289   case ISD::SADDO:
3290     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3291     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3292     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3293     break;
3294   case ISD::UADDO:
3295     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3296     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3297     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3298     break;
3299   case ISD::SSUBO:
3300     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3301     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3302     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3303     break;
3304   case ISD::USUBO:
3305     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3306     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3307     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3308     break;
3309   } // switch (...)
3310
3311   return std::make_pair(Value, OverflowCmp);
3312 }
3313
3314
3315 SDValue
3316 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3317   // Let legalize expand this if it isn't a legal type yet.
3318   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3319     return SDValue();
3320
3321   SDValue Value, OverflowCmp;
3322   SDValue ARMcc;
3323   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3324   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3325   SDLoc dl(Op);
3326   // We use 0 and 1 as false and true values.
3327   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3328   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3329   EVT VT = Op.getValueType();
3330
3331   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3332                                  ARMcc, CCR, OverflowCmp);
3333
3334   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3335   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3336 }
3337
3338
3339 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3340   SDValue Cond = Op.getOperand(0);
3341   SDValue SelectTrue = Op.getOperand(1);
3342   SDValue SelectFalse = Op.getOperand(2);
3343   SDLoc dl(Op);
3344   unsigned Opc = Cond.getOpcode();
3345
3346   if (Cond.getResNo() == 1 &&
3347       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3348        Opc == ISD::USUBO)) {
3349     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3350       return SDValue();
3351
3352     SDValue Value, OverflowCmp;
3353     SDValue ARMcc;
3354     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3355     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3356     EVT VT = Op.getValueType();
3357
3358     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3359                    OverflowCmp, DAG);
3360   }
3361
3362   // Convert:
3363   //
3364   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3365   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3366   //
3367   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3368     const ConstantSDNode *CMOVTrue =
3369       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3370     const ConstantSDNode *CMOVFalse =
3371       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3372
3373     if (CMOVTrue && CMOVFalse) {
3374       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3375       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3376
3377       SDValue True;
3378       SDValue False;
3379       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3380         True = SelectTrue;
3381         False = SelectFalse;
3382       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3383         True = SelectFalse;
3384         False = SelectTrue;
3385       }
3386
3387       if (True.getNode() && False.getNode()) {
3388         EVT VT = Op.getValueType();
3389         SDValue ARMcc = Cond.getOperand(2);
3390         SDValue CCR = Cond.getOperand(3);
3391         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3392         assert(True.getValueType() == VT);
3393         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3394       }
3395     }
3396   }
3397
3398   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3399   // undefined bits before doing a full-word comparison with zero.
3400   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3401                      DAG.getConstant(1, dl, Cond.getValueType()));
3402
3403   return DAG.getSelectCC(dl, Cond,
3404                          DAG.getConstant(0, dl, Cond.getValueType()),
3405                          SelectTrue, SelectFalse, ISD::SETNE);
3406 }
3407
3408 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3409                                  bool &swpCmpOps, bool &swpVselOps) {
3410   // Start by selecting the GE condition code for opcodes that return true for
3411   // 'equality'
3412   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3413       CC == ISD::SETULE)
3414     CondCode = ARMCC::GE;
3415
3416   // and GT for opcodes that return false for 'equality'.
3417   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3418            CC == ISD::SETULT)
3419     CondCode = ARMCC::GT;
3420
3421   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3422   // to swap the compare operands.
3423   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3424       CC == ISD::SETULT)
3425     swpCmpOps = true;
3426
3427   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3428   // If we have an unordered opcode, we need to swap the operands to the VSEL
3429   // instruction (effectively negating the condition).
3430   //
3431   // This also has the effect of swapping which one of 'less' or 'greater'
3432   // returns true, so we also swap the compare operands. It also switches
3433   // whether we return true for 'equality', so we compensate by picking the
3434   // opposite condition code to our original choice.
3435   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3436       CC == ISD::SETUGT) {
3437     swpCmpOps = !swpCmpOps;
3438     swpVselOps = !swpVselOps;
3439     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3440   }
3441
3442   // 'ordered' is 'anything but unordered', so use the VS condition code and
3443   // swap the VSEL operands.
3444   if (CC == ISD::SETO) {
3445     CondCode = ARMCC::VS;
3446     swpVselOps = true;
3447   }
3448
3449   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3450   // code and swap the VSEL operands.
3451   if (CC == ISD::SETUNE) {
3452     CondCode = ARMCC::EQ;
3453     swpVselOps = true;
3454   }
3455 }
3456
3457 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3458                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3459                                    SDValue Cmp, SelectionDAG &DAG) const {
3460   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3461     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3462                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3463     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3464                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3465
3466     SDValue TrueLow = TrueVal.getValue(0);
3467     SDValue TrueHigh = TrueVal.getValue(1);
3468     SDValue FalseLow = FalseVal.getValue(0);
3469     SDValue FalseHigh = FalseVal.getValue(1);
3470
3471     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3472                               ARMcc, CCR, Cmp);
3473     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3474                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3475
3476     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3477   } else {
3478     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3479                        Cmp);
3480   }
3481 }
3482
3483 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3484   EVT VT = Op.getValueType();
3485   SDValue LHS = Op.getOperand(0);
3486   SDValue RHS = Op.getOperand(1);
3487   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3488   SDValue TrueVal = Op.getOperand(2);
3489   SDValue FalseVal = Op.getOperand(3);
3490   SDLoc dl(Op);
3491
3492   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3493     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3494                                                     dl);
3495
3496     // If softenSetCCOperands only returned one value, we should compare it to
3497     // zero.
3498     if (!RHS.getNode()) {
3499       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3500       CC = ISD::SETNE;
3501     }
3502   }
3503
3504   if (LHS.getValueType() == MVT::i32) {
3505     // Try to generate VSEL on ARMv8.
3506     // The VSEL instruction can't use all the usual ARM condition
3507     // codes: it only has two bits to select the condition code, so it's
3508     // constrained to use only GE, GT, VS and EQ.
3509     //
3510     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3511     // swap the operands of the previous compare instruction (effectively
3512     // inverting the compare condition, swapping 'less' and 'greater') and
3513     // sometimes need to swap the operands to the VSEL (which inverts the
3514     // condition in the sense of firing whenever the previous condition didn't)
3515     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3516                                     TrueVal.getValueType() == MVT::f64)) {
3517       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3518       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3519           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3520         CC = ISD::getSetCCInverse(CC, true);
3521         std::swap(TrueVal, FalseVal);
3522       }
3523     }
3524
3525     SDValue ARMcc;
3526     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3527     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3528     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3529   }
3530
3531   ARMCC::CondCodes CondCode, CondCode2;
3532   FPCCToARMCC(CC, CondCode, CondCode2);
3533
3534   // Try to generate VMAXNM/VMINNM on ARMv8.
3535   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3536                                   TrueVal.getValueType() == MVT::f64)) {
3537     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3538     // same operands, as follows:
3539     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3540     //   select c, a, b
3541     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3542     bool swapSides = false;
3543     if (!getTargetMachine().Options.NoNaNsFPMath) {
3544       // transformability may depend on which way around we compare
3545       switch (CC) {
3546       default:
3547         break;
3548       case ISD::SETOGT:
3549       case ISD::SETOGE:
3550       case ISD::SETOLT:
3551       case ISD::SETOLE:
3552         // the non-NaN should be RHS
3553         swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3554         break;
3555       case ISD::SETUGT:
3556       case ISD::SETUGE:
3557       case ISD::SETULT:
3558       case ISD::SETULE:
3559         // the non-NaN should be LHS
3560         swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3561         break;
3562       }
3563     }
3564     swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3565     if (swapSides) {
3566       CC = ISD::getSetCCSwappedOperands(CC);
3567       std::swap(LHS, RHS);
3568     }
3569     if (LHS == TrueVal && RHS == FalseVal) {
3570       bool canTransform = true;
3571       // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3572       if (!getTargetMachine().Options.UnsafeFPMath &&
3573           !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3574         const ConstantFPSDNode *Zero;
3575         switch (CC) {
3576         default:
3577           break;
3578         case ISD::SETOGT:
3579         case ISD::SETUGT:
3580         case ISD::SETGT:
3581           // RHS must not be -0
3582           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3583                          !Zero->isNegative();
3584           break;
3585         case ISD::SETOGE:
3586         case ISD::SETUGE:
3587         case ISD::SETGE:
3588           // LHS must not be -0
3589           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3590                          !Zero->isNegative();
3591           break;
3592         case ISD::SETOLT:
3593         case ISD::SETULT:
3594         case ISD::SETLT:
3595           // RHS must not be +0
3596           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3597                           Zero->isNegative();
3598           break;
3599         case ISD::SETOLE:
3600         case ISD::SETULE:
3601         case ISD::SETLE:
3602           // LHS must not be +0
3603           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3604                           Zero->isNegative();
3605           break;
3606         }
3607       }
3608       if (canTransform) {
3609         // Note: If one of the elements in a pair is a number and the other
3610         // element is NaN, the corresponding result element is the number.
3611         // This is consistent with the IEEE 754-2008 standard.
3612         // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3613         switch (CC) {
3614         default:
3615           break;
3616         case ISD::SETOGT:
3617         case ISD::SETOGE:
3618           if (!DAG.isKnownNeverNaN(RHS))
3619             break;
3620           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3621         case ISD::SETUGT:
3622         case ISD::SETUGE:
3623           if (!DAG.isKnownNeverNaN(LHS))
3624             break;
3625         case ISD::SETGT:
3626         case ISD::SETGE:
3627           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3628         case ISD::SETOLT:
3629         case ISD::SETOLE:
3630           if (!DAG.isKnownNeverNaN(RHS))
3631             break;
3632           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3633         case ISD::SETULT:
3634         case ISD::SETULE:
3635           if (!DAG.isKnownNeverNaN(LHS))
3636             break;
3637         case ISD::SETLT:
3638         case ISD::SETLE:
3639           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3640         }
3641       }
3642     }
3643
3644     bool swpCmpOps = false;
3645     bool swpVselOps = false;
3646     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3647
3648     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3649         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3650       if (swpCmpOps)
3651         std::swap(LHS, RHS);
3652       if (swpVselOps)
3653         std::swap(TrueVal, FalseVal);
3654     }
3655   }
3656
3657   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3658   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3659   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3660   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3661   if (CondCode2 != ARMCC::AL) {
3662     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3663     // FIXME: Needs another CMP because flag can have but one use.
3664     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3665     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3666   }
3667   return Result;
3668 }
3669
3670 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3671 /// to morph to an integer compare sequence.
3672 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3673                            const ARMSubtarget *Subtarget) {
3674   SDNode *N = Op.getNode();
3675   if (!N->hasOneUse())
3676     // Otherwise it requires moving the value from fp to integer registers.
3677     return false;
3678   if (!N->getNumValues())
3679     return false;
3680   EVT VT = Op.getValueType();
3681   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3682     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3683     // vmrs are very slow, e.g. cortex-a8.
3684     return false;
3685
3686   if (isFloatingPointZero(Op)) {
3687     SeenZero = true;
3688     return true;
3689   }
3690   return ISD::isNormalLoad(N);
3691 }
3692
3693 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3694   if (isFloatingPointZero(Op))
3695     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3696
3697   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3698     return DAG.getLoad(MVT::i32, SDLoc(Op),
3699                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3700                        Ld->isVolatile(), Ld->isNonTemporal(),
3701                        Ld->isInvariant(), Ld->getAlignment());
3702
3703   llvm_unreachable("Unknown VFP cmp argument!");
3704 }
3705
3706 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3707                            SDValue &RetVal1, SDValue &RetVal2) {
3708   SDLoc dl(Op);
3709
3710   if (isFloatingPointZero(Op)) {
3711     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3712     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3713     return;
3714   }
3715
3716   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3717     SDValue Ptr = Ld->getBasePtr();
3718     RetVal1 = DAG.getLoad(MVT::i32, dl,
3719                           Ld->getChain(), Ptr,
3720                           Ld->getPointerInfo(),
3721                           Ld->isVolatile(), Ld->isNonTemporal(),
3722                           Ld->isInvariant(), Ld->getAlignment());
3723
3724     EVT PtrType = Ptr.getValueType();
3725     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3726     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3727                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3728     RetVal2 = DAG.getLoad(MVT::i32, dl,
3729                           Ld->getChain(), NewPtr,
3730                           Ld->getPointerInfo().getWithOffset(4),
3731                           Ld->isVolatile(), Ld->isNonTemporal(),
3732                           Ld->isInvariant(), NewAlign);
3733     return;
3734   }
3735
3736   llvm_unreachable("Unknown VFP cmp argument!");
3737 }
3738
3739 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3740 /// f32 and even f64 comparisons to integer ones.
3741 SDValue
3742 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3743   SDValue Chain = Op.getOperand(0);
3744   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3745   SDValue LHS = Op.getOperand(2);
3746   SDValue RHS = Op.getOperand(3);
3747   SDValue Dest = Op.getOperand(4);
3748   SDLoc dl(Op);
3749
3750   bool LHSSeenZero = false;
3751   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3752   bool RHSSeenZero = false;
3753   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3754   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3755     // If unsafe fp math optimization is enabled and there are no other uses of
3756     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3757     // to an integer comparison.
3758     if (CC == ISD::SETOEQ)
3759       CC = ISD::SETEQ;
3760     else if (CC == ISD::SETUNE)
3761       CC = ISD::SETNE;
3762
3763     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3764     SDValue ARMcc;
3765     if (LHS.getValueType() == MVT::f32) {
3766       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3767                         bitcastf32Toi32(LHS, DAG), Mask);
3768       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3769                         bitcastf32Toi32(RHS, DAG), Mask);
3770       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3771       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3772       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3773                          Chain, Dest, ARMcc, CCR, Cmp);
3774     }
3775
3776     SDValue LHS1, LHS2;
3777     SDValue RHS1, RHS2;
3778     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3779     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3780     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3781     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3782     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3783     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3784     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3785     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3786     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3787   }
3788
3789   return SDValue();
3790 }
3791
3792 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3793   SDValue Chain = Op.getOperand(0);
3794   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3795   SDValue LHS = Op.getOperand(2);
3796   SDValue RHS = Op.getOperand(3);
3797   SDValue Dest = Op.getOperand(4);
3798   SDLoc dl(Op);
3799
3800   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3801     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3802                                                     dl);
3803
3804     // If softenSetCCOperands only returned one value, we should compare it to
3805     // zero.
3806     if (!RHS.getNode()) {
3807       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3808       CC = ISD::SETNE;
3809     }
3810   }
3811
3812   if (LHS.getValueType() == MVT::i32) {
3813     SDValue ARMcc;
3814     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3815     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3816     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3817                        Chain, Dest, ARMcc, CCR, Cmp);
3818   }
3819
3820   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3821
3822   if (getTargetMachine().Options.UnsafeFPMath &&
3823       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3824        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3825     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3826     if (Result.getNode())
3827       return Result;
3828   }
3829
3830   ARMCC::CondCodes CondCode, CondCode2;
3831   FPCCToARMCC(CC, CondCode, CondCode2);
3832
3833   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3834   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3835   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3836   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3837   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3838   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3839   if (CondCode2 != ARMCC::AL) {
3840     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3841     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3842     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3843   }
3844   return Res;
3845 }
3846
3847 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3848   SDValue Chain = Op.getOperand(0);
3849   SDValue Table = Op.getOperand(1);
3850   SDValue Index = Op.getOperand(2);
3851   SDLoc dl(Op);
3852
3853   EVT PTy = getPointerTy();
3854   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3855   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3856   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3857   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3858   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3859   if (Subtarget->isThumb2()) {
3860     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3861     // which does another jump to the destination. This also makes it easier
3862     // to translate it to TBB / TBH later.
3863     // FIXME: This might not work if the function is extremely large.
3864     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3865                        Addr, Op.getOperand(2), JTI);
3866   }
3867   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3868     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3869                        MachinePointerInfo::getJumpTable(),
3870                        false, false, false, 0);
3871     Chain = Addr.getValue(1);
3872     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3873     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3874   } else {
3875     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3876                        MachinePointerInfo::getJumpTable(),
3877                        false, false, false, 0);
3878     Chain = Addr.getValue(1);
3879     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3880   }
3881 }
3882
3883 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3884   EVT VT = Op.getValueType();
3885   SDLoc dl(Op);
3886
3887   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3888     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3889       return Op;
3890     return DAG.UnrollVectorOp(Op.getNode());
3891   }
3892
3893   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3894          "Invalid type for custom lowering!");
3895   if (VT != MVT::v4i16)
3896     return DAG.UnrollVectorOp(Op.getNode());
3897
3898   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3899   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3900 }
3901
3902 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3903   EVT VT = Op.getValueType();
3904   if (VT.isVector())
3905     return LowerVectorFP_TO_INT(Op, DAG);
3906   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3907     RTLIB::Libcall LC;
3908     if (Op.getOpcode() == ISD::FP_TO_SINT)
3909       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3910                               Op.getValueType());
3911     else
3912       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3913                               Op.getValueType());
3914     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3915                        /*isSigned*/ false, SDLoc(Op)).first;
3916   }
3917
3918   return Op;
3919 }
3920
3921 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3922   EVT VT = Op.getValueType();
3923   SDLoc dl(Op);
3924
3925   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3926     if (VT.getVectorElementType() == MVT::f32)
3927       return Op;
3928     return DAG.UnrollVectorOp(Op.getNode());
3929   }
3930
3931   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3932          "Invalid type for custom lowering!");
3933   if (VT != MVT::v4f32)
3934     return DAG.UnrollVectorOp(Op.getNode());
3935
3936   unsigned CastOpc;
3937   unsigned Opc;
3938   switch (Op.getOpcode()) {
3939   default: llvm_unreachable("Invalid opcode!");
3940   case ISD::SINT_TO_FP:
3941     CastOpc = ISD::SIGN_EXTEND;
3942     Opc = ISD::SINT_TO_FP;
3943     break;
3944   case ISD::UINT_TO_FP:
3945     CastOpc = ISD::ZERO_EXTEND;
3946     Opc = ISD::UINT_TO_FP;
3947     break;
3948   }
3949
3950   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3951   return DAG.getNode(Opc, dl, VT, Op);
3952 }
3953
3954 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3955   EVT VT = Op.getValueType();
3956   if (VT.isVector())
3957     return LowerVectorINT_TO_FP(Op, DAG);
3958   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3959     RTLIB::Libcall LC;
3960     if (Op.getOpcode() == ISD::SINT_TO_FP)
3961       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3962                               Op.getValueType());
3963     else
3964       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3965                               Op.getValueType());
3966     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3967                        /*isSigned*/ false, SDLoc(Op)).first;
3968   }
3969
3970   return Op;
3971 }
3972
3973 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3974   // Implement fcopysign with a fabs and a conditional fneg.
3975   SDValue Tmp0 = Op.getOperand(0);
3976   SDValue Tmp1 = Op.getOperand(1);
3977   SDLoc dl(Op);
3978   EVT VT = Op.getValueType();
3979   EVT SrcVT = Tmp1.getValueType();
3980   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3981     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3982   bool UseNEON = !InGPR && Subtarget->hasNEON();
3983
3984   if (UseNEON) {
3985     // Use VBSL to copy the sign bit.
3986     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3987     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3988                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3989     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3990     if (VT == MVT::f64)
3991       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3992                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3993                          DAG.getConstant(32, dl, MVT::i32));
3994     else /*if (VT == MVT::f32)*/
3995       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3996     if (SrcVT == MVT::f32) {
3997       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3998       if (VT == MVT::f64)
3999         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4000                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4001                            DAG.getConstant(32, dl, MVT::i32));
4002     } else if (VT == MVT::f32)
4003       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4004                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4005                          DAG.getConstant(32, dl, MVT::i32));
4006     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4007     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4008
4009     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4010                                             dl, MVT::i32);
4011     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4012     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4013                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4014
4015     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4016                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4017                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4018     if (VT == MVT::f32) {
4019       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4020       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4021                         DAG.getConstant(0, dl, MVT::i32));
4022     } else {
4023       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4024     }
4025
4026     return Res;
4027   }
4028
4029   // Bitcast operand 1 to i32.
4030   if (SrcVT == MVT::f64)
4031     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4032                        Tmp1).getValue(1);
4033   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4034
4035   // Or in the signbit with integer operations.
4036   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4037   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4038   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4039   if (VT == MVT::f32) {
4040     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4041                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4042     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4043                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4044   }
4045
4046   // f64: Or the high part with signbit and then combine two parts.
4047   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4048                      Tmp0);
4049   SDValue Lo = Tmp0.getValue(0);
4050   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4051   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4052   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4053 }
4054
4055 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4056   MachineFunction &MF = DAG.getMachineFunction();
4057   MachineFrameInfo *MFI = MF.getFrameInfo();
4058   MFI->setReturnAddressIsTaken(true);
4059
4060   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4061     return SDValue();
4062
4063   EVT VT = Op.getValueType();
4064   SDLoc dl(Op);
4065   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4066   if (Depth) {
4067     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4068     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4069     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4070                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4071                        MachinePointerInfo(), false, false, false, 0);
4072   }
4073
4074   // Return LR, which contains the return address. Mark it an implicit live-in.
4075   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4076   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4077 }
4078
4079 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4080   const ARMBaseRegisterInfo &ARI =
4081     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4082   MachineFunction &MF = DAG.getMachineFunction();
4083   MachineFrameInfo *MFI = MF.getFrameInfo();
4084   MFI->setFrameAddressIsTaken(true);
4085
4086   EVT VT = Op.getValueType();
4087   SDLoc dl(Op);  // FIXME probably not meaningful
4088   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4089   unsigned FrameReg = ARI.getFrameRegister(MF);
4090   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4091   while (Depth--)
4092     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4093                             MachinePointerInfo(),
4094                             false, false, false, 0);
4095   return FrameAddr;
4096 }
4097
4098 // FIXME? Maybe this could be a TableGen attribute on some registers and
4099 // this table could be generated automatically from RegInfo.
4100 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4101                                               EVT VT) const {
4102   unsigned Reg = StringSwitch<unsigned>(RegName)
4103                        .Case("sp", ARM::SP)
4104                        .Default(0);
4105   if (Reg)
4106     return Reg;
4107   report_fatal_error(Twine("Invalid register name \""
4108                               + StringRef(RegName)  + "\"."));
4109 }
4110
4111 // Result is 64 bit value so split into two 32 bit values and return as a
4112 // pair of values.
4113 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4114                                 SelectionDAG &DAG) {
4115   SDLoc DL(N);
4116
4117   // This function is only supposed to be called for i64 type destination.
4118   assert(N->getValueType(0) == MVT::i64
4119           && "ExpandREAD_REGISTER called for non-i64 type result.");
4120
4121   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4122                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4123                              N->getOperand(0),
4124                              N->getOperand(1));
4125
4126   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4127                     Read.getValue(1)));
4128   Results.push_back(Read.getOperand(0));
4129 }
4130
4131 /// ExpandBITCAST - If the target supports VFP, this function is called to
4132 /// expand a bit convert where either the source or destination type is i64 to
4133 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4134 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4135 /// vectors), since the legalizer won't know what to do with that.
4136 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4137   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4138   SDLoc dl(N);
4139   SDValue Op = N->getOperand(0);
4140
4141   // This function is only supposed to be called for i64 types, either as the
4142   // source or destination of the bit convert.
4143   EVT SrcVT = Op.getValueType();
4144   EVT DstVT = N->getValueType(0);
4145   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4146          "ExpandBITCAST called for non-i64 type");
4147
4148   // Turn i64->f64 into VMOVDRR.
4149   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4150     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4151                              DAG.getConstant(0, dl, MVT::i32));
4152     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4153                              DAG.getConstant(1, dl, MVT::i32));
4154     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4155                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4156   }
4157
4158   // Turn f64->i64 into VMOVRRD.
4159   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4160     SDValue Cvt;
4161     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4162         SrcVT.getVectorNumElements() > 1)
4163       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4164                         DAG.getVTList(MVT::i32, MVT::i32),
4165                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4166     else
4167       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4168                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4169     // Merge the pieces into a single i64 value.
4170     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4171   }
4172
4173   return SDValue();
4174 }
4175
4176 /// getZeroVector - Returns a vector of specified type with all zero elements.
4177 /// Zero vectors are used to represent vector negation and in those cases
4178 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4179 /// not support i64 elements, so sometimes the zero vectors will need to be
4180 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4181 /// zero vector.
4182 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4183   assert(VT.isVector() && "Expected a vector type");
4184   // The canonical modified immediate encoding of a zero vector is....0!
4185   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4186   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4187   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4188   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4189 }
4190
4191 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4192 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4193 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4194                                                 SelectionDAG &DAG) const {
4195   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4196   EVT VT = Op.getValueType();
4197   unsigned VTBits = VT.getSizeInBits();
4198   SDLoc dl(Op);
4199   SDValue ShOpLo = Op.getOperand(0);
4200   SDValue ShOpHi = Op.getOperand(1);
4201   SDValue ShAmt  = Op.getOperand(2);
4202   SDValue ARMcc;
4203   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4204
4205   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4206
4207   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4208                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4209   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4210   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4211                                    DAG.getConstant(VTBits, dl, MVT::i32));
4212   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4213   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4214   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4215
4216   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4217   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4218                           ISD::SETGE, ARMcc, DAG, dl);
4219   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4220   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4221                            CCR, Cmp);
4222
4223   SDValue Ops[2] = { Lo, Hi };
4224   return DAG.getMergeValues(Ops, dl);
4225 }
4226
4227 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4228 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4229 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4230                                                SelectionDAG &DAG) const {
4231   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4232   EVT VT = Op.getValueType();
4233   unsigned VTBits = VT.getSizeInBits();
4234   SDLoc dl(Op);
4235   SDValue ShOpLo = Op.getOperand(0);
4236   SDValue ShOpHi = Op.getOperand(1);
4237   SDValue ShAmt  = Op.getOperand(2);
4238   SDValue ARMcc;
4239
4240   assert(Op.getOpcode() == ISD::SHL_PARTS);
4241   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4242                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4243   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4244   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4245                                    DAG.getConstant(VTBits, dl, MVT::i32));
4246   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4247   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4248
4249   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4250   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4251   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4252                           ISD::SETGE, ARMcc, DAG, dl);
4253   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4254   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4255                            CCR, Cmp);
4256
4257   SDValue Ops[2] = { Lo, Hi };
4258   return DAG.getMergeValues(Ops, dl);
4259 }
4260
4261 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4262                                             SelectionDAG &DAG) const {
4263   // The rounding mode is in bits 23:22 of the FPSCR.
4264   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4265   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4266   // so that the shift + and get folded into a bitfield extract.
4267   SDLoc dl(Op);
4268   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4269                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4270                                               MVT::i32));
4271   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4272                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4273   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4274                               DAG.getConstant(22, dl, MVT::i32));
4275   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4276                      DAG.getConstant(3, dl, MVT::i32));
4277 }
4278
4279 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4280                          const ARMSubtarget *ST) {
4281   EVT VT = N->getValueType(0);
4282   SDLoc dl(N);
4283
4284   if (!ST->hasV6T2Ops())
4285     return SDValue();
4286
4287   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4288   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4289 }
4290
4291 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4292 /// for each 16-bit element from operand, repeated.  The basic idea is to
4293 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4294 ///
4295 /// Trace for v4i16:
4296 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4297 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4298 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4299 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4300 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4301 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4302 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4303 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4304 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4305   EVT VT = N->getValueType(0);
4306   SDLoc DL(N);
4307
4308   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4309   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4310   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4311   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4312   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4313   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4314 }
4315
4316 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4317 /// bit-count for each 16-bit element from the operand.  We need slightly
4318 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4319 /// 64/128-bit registers.
4320 ///
4321 /// Trace for v4i16:
4322 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4323 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4324 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4325 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4326 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4327   EVT VT = N->getValueType(0);
4328   SDLoc DL(N);
4329
4330   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4331   if (VT.is64BitVector()) {
4332     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4333     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4334                        DAG.getIntPtrConstant(0, DL));
4335   } else {
4336     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4337                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4338     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4339   }
4340 }
4341
4342 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4343 /// bit-count for each 32-bit element from the operand.  The idea here is
4344 /// to split the vector into 16-bit elements, leverage the 16-bit count
4345 /// routine, and then combine the results.
4346 ///
4347 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4348 /// input    = [v0    v1    ] (vi: 32-bit elements)
4349 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4350 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4351 /// vrev: N0 = [k1 k0 k3 k2 ]
4352 ///            [k0 k1 k2 k3 ]
4353 ///       N1 =+[k1 k0 k3 k2 ]
4354 ///            [k0 k2 k1 k3 ]
4355 ///       N2 =+[k1 k3 k0 k2 ]
4356 ///            [k0    k2    k1    k3    ]
4357 /// Extended =+[k1    k3    k0    k2    ]
4358 ///            [k0    k2    ]
4359 /// Extracted=+[k1    k3    ]
4360 ///
4361 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4362   EVT VT = N->getValueType(0);
4363   SDLoc DL(N);
4364
4365   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4366
4367   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4368   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4369   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4370   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4371   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4372
4373   if (VT.is64BitVector()) {
4374     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4375     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4376                        DAG.getIntPtrConstant(0, DL));
4377   } else {
4378     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4379                                     DAG.getIntPtrConstant(0, DL));
4380     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4381   }
4382 }
4383
4384 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4385                           const ARMSubtarget *ST) {
4386   EVT VT = N->getValueType(0);
4387
4388   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4389   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4390           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4391          "Unexpected type for custom ctpop lowering");
4392
4393   if (VT.getVectorElementType() == MVT::i32)
4394     return lowerCTPOP32BitElements(N, DAG);
4395   else
4396     return lowerCTPOP16BitElements(N, DAG);
4397 }
4398
4399 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4400                           const ARMSubtarget *ST) {
4401   EVT VT = N->getValueType(0);
4402   SDLoc dl(N);
4403
4404   if (!VT.isVector())
4405     return SDValue();
4406
4407   // Lower vector shifts on NEON to use VSHL.
4408   assert(ST->hasNEON() && "unexpected vector shift");
4409
4410   // Left shifts translate directly to the vshiftu intrinsic.
4411   if (N->getOpcode() == ISD::SHL)
4412     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4413                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4414                                        MVT::i32),
4415                        N->getOperand(0), N->getOperand(1));
4416
4417   assert((N->getOpcode() == ISD::SRA ||
4418           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4419
4420   // NEON uses the same intrinsics for both left and right shifts.  For
4421   // right shifts, the shift amounts are negative, so negate the vector of
4422   // shift amounts.
4423   EVT ShiftVT = N->getOperand(1).getValueType();
4424   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4425                                      getZeroVector(ShiftVT, DAG, dl),
4426                                      N->getOperand(1));
4427   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4428                              Intrinsic::arm_neon_vshifts :
4429                              Intrinsic::arm_neon_vshiftu);
4430   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4431                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4432                      N->getOperand(0), NegatedCount);
4433 }
4434
4435 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4436                                 const ARMSubtarget *ST) {
4437   EVT VT = N->getValueType(0);
4438   SDLoc dl(N);
4439
4440   // We can get here for a node like i32 = ISD::SHL i32, i64
4441   if (VT != MVT::i64)
4442     return SDValue();
4443
4444   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4445          "Unknown shift to lower!");
4446
4447   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4448   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4449       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4450     return SDValue();
4451
4452   // If we are in thumb mode, we don't have RRX.
4453   if (ST->isThumb1Only()) return SDValue();
4454
4455   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4456   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4457                            DAG.getConstant(0, dl, MVT::i32));
4458   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4459                            DAG.getConstant(1, dl, MVT::i32));
4460
4461   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4462   // captures the result into a carry flag.
4463   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4464   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4465
4466   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4467   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4468
4469   // Merge the pieces into a single i64 value.
4470  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4471 }
4472
4473 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4474   SDValue TmpOp0, TmpOp1;
4475   bool Invert = false;
4476   bool Swap = false;
4477   unsigned Opc = 0;
4478
4479   SDValue Op0 = Op.getOperand(0);
4480   SDValue Op1 = Op.getOperand(1);
4481   SDValue CC = Op.getOperand(2);
4482   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4483   EVT VT = Op.getValueType();
4484   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4485   SDLoc dl(Op);
4486
4487   if (Op1.getValueType().isFloatingPoint()) {
4488     switch (SetCCOpcode) {
4489     default: llvm_unreachable("Illegal FP comparison");
4490     case ISD::SETUNE:
4491     case ISD::SETNE:  Invert = true; // Fallthrough
4492     case ISD::SETOEQ:
4493     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4494     case ISD::SETOLT:
4495     case ISD::SETLT: Swap = true; // Fallthrough
4496     case ISD::SETOGT:
4497     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4498     case ISD::SETOLE:
4499     case ISD::SETLE:  Swap = true; // Fallthrough
4500     case ISD::SETOGE:
4501     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4502     case ISD::SETUGE: Swap = true; // Fallthrough
4503     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4504     case ISD::SETUGT: Swap = true; // Fallthrough
4505     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4506     case ISD::SETUEQ: Invert = true; // Fallthrough
4507     case ISD::SETONE:
4508       // Expand this to (OLT | OGT).
4509       TmpOp0 = Op0;
4510       TmpOp1 = Op1;
4511       Opc = ISD::OR;
4512       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4513       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4514       break;
4515     case ISD::SETUO: Invert = true; // Fallthrough
4516     case ISD::SETO:
4517       // Expand this to (OLT | OGE).
4518       TmpOp0 = Op0;
4519       TmpOp1 = Op1;
4520       Opc = ISD::OR;
4521       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4522       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4523       break;
4524     }
4525   } else {
4526     // Integer comparisons.
4527     switch (SetCCOpcode) {
4528     default: llvm_unreachable("Illegal integer comparison");
4529     case ISD::SETNE:  Invert = true;
4530     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4531     case ISD::SETLT:  Swap = true;
4532     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4533     case ISD::SETLE:  Swap = true;
4534     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4535     case ISD::SETULT: Swap = true;
4536     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4537     case ISD::SETULE: Swap = true;
4538     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4539     }
4540
4541     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4542     if (Opc == ARMISD::VCEQ) {
4543
4544       SDValue AndOp;
4545       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4546         AndOp = Op0;
4547       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4548         AndOp = Op1;
4549
4550       // Ignore bitconvert.
4551       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4552         AndOp = AndOp.getOperand(0);
4553
4554       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4555         Opc = ARMISD::VTST;
4556         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4557         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4558         Invert = !Invert;
4559       }
4560     }
4561   }
4562
4563   if (Swap)
4564     std::swap(Op0, Op1);
4565
4566   // If one of the operands is a constant vector zero, attempt to fold the
4567   // comparison to a specialized compare-against-zero form.
4568   SDValue SingleOp;
4569   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4570     SingleOp = Op0;
4571   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4572     if (Opc == ARMISD::VCGE)
4573       Opc = ARMISD::VCLEZ;
4574     else if (Opc == ARMISD::VCGT)
4575       Opc = ARMISD::VCLTZ;
4576     SingleOp = Op1;
4577   }
4578
4579   SDValue Result;
4580   if (SingleOp.getNode()) {
4581     switch (Opc) {
4582     case ARMISD::VCEQ:
4583       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4584     case ARMISD::VCGE:
4585       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4586     case ARMISD::VCLEZ:
4587       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4588     case ARMISD::VCGT:
4589       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4590     case ARMISD::VCLTZ:
4591       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4592     default:
4593       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4594     }
4595   } else {
4596      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4597   }
4598
4599   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4600
4601   if (Invert)
4602     Result = DAG.getNOT(dl, Result, VT);
4603
4604   return Result;
4605 }
4606
4607 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4608 /// valid vector constant for a NEON instruction with a "modified immediate"
4609 /// operand (e.g., VMOV).  If so, return the encoded value.
4610 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4611                                  unsigned SplatBitSize, SelectionDAG &DAG,
4612                                  SDLoc dl, EVT &VT, bool is128Bits,
4613                                  NEONModImmType type) {
4614   unsigned OpCmode, Imm;
4615
4616   // SplatBitSize is set to the smallest size that splats the vector, so a
4617   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4618   // immediate instructions others than VMOV do not support the 8-bit encoding
4619   // of a zero vector, and the default encoding of zero is supposed to be the
4620   // 32-bit version.
4621   if (SplatBits == 0)
4622     SplatBitSize = 32;
4623
4624   switch (SplatBitSize) {
4625   case 8:
4626     if (type != VMOVModImm)
4627       return SDValue();
4628     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4629     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4630     OpCmode = 0xe;
4631     Imm = SplatBits;
4632     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4633     break;
4634
4635   case 16:
4636     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4637     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4638     if ((SplatBits & ~0xff) == 0) {
4639       // Value = 0x00nn: Op=x, Cmode=100x.
4640       OpCmode = 0x8;
4641       Imm = SplatBits;
4642       break;
4643     }
4644     if ((SplatBits & ~0xff00) == 0) {
4645       // Value = 0xnn00: Op=x, Cmode=101x.
4646       OpCmode = 0xa;
4647       Imm = SplatBits >> 8;
4648       break;
4649     }
4650     return SDValue();
4651
4652   case 32:
4653     // NEON's 32-bit VMOV supports splat values where:
4654     // * only one byte is nonzero, or
4655     // * the least significant byte is 0xff and the second byte is nonzero, or
4656     // * the least significant 2 bytes are 0xff and the third is nonzero.
4657     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4658     if ((SplatBits & ~0xff) == 0) {
4659       // Value = 0x000000nn: Op=x, Cmode=000x.
4660       OpCmode = 0;
4661       Imm = SplatBits;
4662       break;
4663     }
4664     if ((SplatBits & ~0xff00) == 0) {
4665       // Value = 0x0000nn00: Op=x, Cmode=001x.
4666       OpCmode = 0x2;
4667       Imm = SplatBits >> 8;
4668       break;
4669     }
4670     if ((SplatBits & ~0xff0000) == 0) {
4671       // Value = 0x00nn0000: Op=x, Cmode=010x.
4672       OpCmode = 0x4;
4673       Imm = SplatBits >> 16;
4674       break;
4675     }
4676     if ((SplatBits & ~0xff000000) == 0) {
4677       // Value = 0xnn000000: Op=x, Cmode=011x.
4678       OpCmode = 0x6;
4679       Imm = SplatBits >> 24;
4680       break;
4681     }
4682
4683     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4684     if (type == OtherModImm) return SDValue();
4685
4686     if ((SplatBits & ~0xffff) == 0 &&
4687         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4688       // Value = 0x0000nnff: Op=x, Cmode=1100.
4689       OpCmode = 0xc;
4690       Imm = SplatBits >> 8;
4691       break;
4692     }
4693
4694     if ((SplatBits & ~0xffffff) == 0 &&
4695         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4696       // Value = 0x00nnffff: Op=x, Cmode=1101.
4697       OpCmode = 0xd;
4698       Imm = SplatBits >> 16;
4699       break;
4700     }
4701
4702     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4703     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4704     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4705     // and fall through here to test for a valid 64-bit splat.  But, then the
4706     // caller would also need to check and handle the change in size.
4707     return SDValue();
4708
4709   case 64: {
4710     if (type != VMOVModImm)
4711       return SDValue();
4712     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4713     uint64_t BitMask = 0xff;
4714     uint64_t Val = 0;
4715     unsigned ImmMask = 1;
4716     Imm = 0;
4717     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4718       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4719         Val |= BitMask;
4720         Imm |= ImmMask;
4721       } else if ((SplatBits & BitMask) != 0) {
4722         return SDValue();
4723       }
4724       BitMask <<= 8;
4725       ImmMask <<= 1;
4726     }
4727
4728     if (DAG.getDataLayout().isBigEndian())
4729       // swap higher and lower 32 bit word
4730       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4731
4732     // Op=1, Cmode=1110.
4733     OpCmode = 0x1e;
4734     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4735     break;
4736   }
4737
4738   default:
4739     llvm_unreachable("unexpected size for isNEONModifiedImm");
4740   }
4741
4742   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4743   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4744 }
4745
4746 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4747                                            const ARMSubtarget *ST) const {
4748   if (!ST->hasVFP3())
4749     return SDValue();
4750
4751   bool IsDouble = Op.getValueType() == MVT::f64;
4752   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4753
4754   // Use the default (constant pool) lowering for double constants when we have
4755   // an SP-only FPU
4756   if (IsDouble && Subtarget->isFPOnlySP())
4757     return SDValue();
4758
4759   // Try splatting with a VMOV.f32...
4760   APFloat FPVal = CFP->getValueAPF();
4761   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4762
4763   if (ImmVal != -1) {
4764     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4765       // We have code in place to select a valid ConstantFP already, no need to
4766       // do any mangling.
4767       return Op;
4768     }
4769
4770     // It's a float and we are trying to use NEON operations where
4771     // possible. Lower it to a splat followed by an extract.
4772     SDLoc DL(Op);
4773     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4774     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4775                                       NewVal);
4776     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4777                        DAG.getConstant(0, DL, MVT::i32));
4778   }
4779
4780   // The rest of our options are NEON only, make sure that's allowed before
4781   // proceeding..
4782   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4783     return SDValue();
4784
4785   EVT VMovVT;
4786   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4787
4788   // It wouldn't really be worth bothering for doubles except for one very
4789   // important value, which does happen to match: 0.0. So make sure we don't do
4790   // anything stupid.
4791   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4792     return SDValue();
4793
4794   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4795   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4796                                      VMovVT, false, VMOVModImm);
4797   if (NewVal != SDValue()) {
4798     SDLoc DL(Op);
4799     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4800                                       NewVal);
4801     if (IsDouble)
4802       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4803
4804     // It's a float: cast and extract a vector element.
4805     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4806                                        VecConstant);
4807     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4808                        DAG.getConstant(0, DL, MVT::i32));
4809   }
4810
4811   // Finally, try a VMVN.i32
4812   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4813                              false, VMVNModImm);
4814   if (NewVal != SDValue()) {
4815     SDLoc DL(Op);
4816     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4817
4818     if (IsDouble)
4819       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4820
4821     // It's a float: cast and extract a vector element.
4822     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4823                                        VecConstant);
4824     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4825                        DAG.getConstant(0, DL, MVT::i32));
4826   }
4827
4828   return SDValue();
4829 }
4830
4831 // check if an VEXT instruction can handle the shuffle mask when the
4832 // vector sources of the shuffle are the same.
4833 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4834   unsigned NumElts = VT.getVectorNumElements();
4835
4836   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4837   if (M[0] < 0)
4838     return false;
4839
4840   Imm = M[0];
4841
4842   // If this is a VEXT shuffle, the immediate value is the index of the first
4843   // element.  The other shuffle indices must be the successive elements after
4844   // the first one.
4845   unsigned ExpectedElt = Imm;
4846   for (unsigned i = 1; i < NumElts; ++i) {
4847     // Increment the expected index.  If it wraps around, just follow it
4848     // back to index zero and keep going.
4849     ++ExpectedElt;
4850     if (ExpectedElt == NumElts)
4851       ExpectedElt = 0;
4852
4853     if (M[i] < 0) continue; // ignore UNDEF indices
4854     if (ExpectedElt != static_cast<unsigned>(M[i]))
4855       return false;
4856   }
4857
4858   return true;
4859 }
4860
4861
4862 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4863                        bool &ReverseVEXT, unsigned &Imm) {
4864   unsigned NumElts = VT.getVectorNumElements();
4865   ReverseVEXT = false;
4866
4867   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4868   if (M[0] < 0)
4869     return false;
4870
4871   Imm = M[0];
4872
4873   // If this is a VEXT shuffle, the immediate value is the index of the first
4874   // element.  The other shuffle indices must be the successive elements after
4875   // the first one.
4876   unsigned ExpectedElt = Imm;
4877   for (unsigned i = 1; i < NumElts; ++i) {
4878     // Increment the expected index.  If it wraps around, it may still be
4879     // a VEXT but the source vectors must be swapped.
4880     ExpectedElt += 1;
4881     if (ExpectedElt == NumElts * 2) {
4882       ExpectedElt = 0;
4883       ReverseVEXT = true;
4884     }
4885
4886     if (M[i] < 0) continue; // ignore UNDEF indices
4887     if (ExpectedElt != static_cast<unsigned>(M[i]))
4888       return false;
4889   }
4890
4891   // Adjust the index value if the source operands will be swapped.
4892   if (ReverseVEXT)
4893     Imm -= NumElts;
4894
4895   return true;
4896 }
4897
4898 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4899 /// instruction with the specified blocksize.  (The order of the elements
4900 /// within each block of the vector is reversed.)
4901 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4902   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4903          "Only possible block sizes for VREV are: 16, 32, 64");
4904
4905   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4906   if (EltSz == 64)
4907     return false;
4908
4909   unsigned NumElts = VT.getVectorNumElements();
4910   unsigned BlockElts = M[0] + 1;
4911   // If the first shuffle index is UNDEF, be optimistic.
4912   if (M[0] < 0)
4913     BlockElts = BlockSize / EltSz;
4914
4915   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4916     return false;
4917
4918   for (unsigned i = 0; i < NumElts; ++i) {
4919     if (M[i] < 0) continue; // ignore UNDEF indices
4920     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4921       return false;
4922   }
4923
4924   return true;
4925 }
4926
4927 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4928   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4929   // range, then 0 is placed into the resulting vector. So pretty much any mask
4930   // of 8 elements can work here.
4931   return VT == MVT::v8i8 && M.size() == 8;
4932 }
4933
4934 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4935   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4936   if (EltSz == 64)
4937     return false;
4938
4939   unsigned NumElts = VT.getVectorNumElements();
4940   WhichResult = (M[0] == 0 ? 0 : 1);
4941   for (unsigned i = 0; i < NumElts; i += 2) {
4942     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4943         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4944       return false;
4945   }
4946   return true;
4947 }
4948
4949 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4950 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4951 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4952 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4953   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4954   if (EltSz == 64)
4955     return false;
4956
4957   unsigned NumElts = VT.getVectorNumElements();
4958   WhichResult = (M[0] == 0 ? 0 : 1);
4959   for (unsigned i = 0; i < NumElts; i += 2) {
4960     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4961         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4962       return false;
4963   }
4964   return true;
4965 }
4966
4967 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4968   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4969   if (EltSz == 64)
4970     return false;
4971
4972   unsigned NumElts = VT.getVectorNumElements();
4973   WhichResult = (M[0] == 0 ? 0 : 1);
4974   for (unsigned i = 0; i != NumElts; ++i) {
4975     if (M[i] < 0) continue; // ignore UNDEF indices
4976     if ((unsigned) M[i] != 2 * i + WhichResult)
4977       return false;
4978   }
4979
4980   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4981   if (VT.is64BitVector() && EltSz == 32)
4982     return false;
4983
4984   return true;
4985 }
4986
4987 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4988 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4989 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4990 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4991   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4992   if (EltSz == 64)
4993     return false;
4994
4995   unsigned Half = VT.getVectorNumElements() / 2;
4996   WhichResult = (M[0] == 0 ? 0 : 1);
4997   for (unsigned j = 0; j != 2; ++j) {
4998     unsigned Idx = WhichResult;
4999     for (unsigned i = 0; i != Half; ++i) {
5000       int MIdx = M[i + j * Half];
5001       if (MIdx >= 0 && (unsigned) MIdx != Idx)
5002         return false;
5003       Idx += 2;
5004     }
5005   }
5006
5007   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5008   if (VT.is64BitVector() && EltSz == 32)
5009     return false;
5010
5011   return true;
5012 }
5013
5014 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5015   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5016   if (EltSz == 64)
5017     return false;
5018
5019   unsigned NumElts = VT.getVectorNumElements();
5020   WhichResult = (M[0] == 0 ? 0 : 1);
5021   unsigned Idx = WhichResult * NumElts / 2;
5022   for (unsigned i = 0; i != NumElts; i += 2) {
5023     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5024         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5025       return false;
5026     Idx += 1;
5027   }
5028
5029   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5030   if (VT.is64BitVector() && EltSz == 32)
5031     return false;
5032
5033   return true;
5034 }
5035
5036 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5037 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5038 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5039 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5040   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5041   if (EltSz == 64)
5042     return false;
5043
5044   unsigned NumElts = VT.getVectorNumElements();
5045   WhichResult = (M[0] == 0 ? 0 : 1);
5046   unsigned Idx = WhichResult * NumElts / 2;
5047   for (unsigned i = 0; i != NumElts; i += 2) {
5048     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5049         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5050       return false;
5051     Idx += 1;
5052   }
5053
5054   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5055   if (VT.is64BitVector() && EltSz == 32)
5056     return false;
5057
5058   return true;
5059 }
5060
5061 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5062 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5063 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5064                                            unsigned &WhichResult,
5065                                            bool &isV_UNDEF) {
5066   isV_UNDEF = false;
5067   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5068     return ARMISD::VTRN;
5069   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5070     return ARMISD::VUZP;
5071   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5072     return ARMISD::VZIP;
5073
5074   isV_UNDEF = true;
5075   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5076     return ARMISD::VTRN;
5077   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5078     return ARMISD::VUZP;
5079   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5080     return ARMISD::VZIP;
5081
5082   return 0;
5083 }
5084
5085 /// \return true if this is a reverse operation on an vector.
5086 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5087   unsigned NumElts = VT.getVectorNumElements();
5088   // Make sure the mask has the right size.
5089   if (NumElts != M.size())
5090       return false;
5091
5092   // Look for <15, ..., 3, -1, 1, 0>.
5093   for (unsigned i = 0; i != NumElts; ++i)
5094     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5095       return false;
5096
5097   return true;
5098 }
5099
5100 // If N is an integer constant that can be moved into a register in one
5101 // instruction, return an SDValue of such a constant (will become a MOV
5102 // instruction).  Otherwise return null.
5103 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5104                                      const ARMSubtarget *ST, SDLoc dl) {
5105   uint64_t Val;
5106   if (!isa<ConstantSDNode>(N))
5107     return SDValue();
5108   Val = cast<ConstantSDNode>(N)->getZExtValue();
5109
5110   if (ST->isThumb1Only()) {
5111     if (Val <= 255 || ~Val <= 255)
5112       return DAG.getConstant(Val, dl, MVT::i32);
5113   } else {
5114     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5115       return DAG.getConstant(Val, dl, MVT::i32);
5116   }
5117   return SDValue();
5118 }
5119
5120 // If this is a case we can't handle, return null and let the default
5121 // expansion code take care of it.
5122 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5123                                              const ARMSubtarget *ST) const {
5124   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5125   SDLoc dl(Op);
5126   EVT VT = Op.getValueType();
5127
5128   APInt SplatBits, SplatUndef;
5129   unsigned SplatBitSize;
5130   bool HasAnyUndefs;
5131   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5132     if (SplatBitSize <= 64) {
5133       // Check if an immediate VMOV works.
5134       EVT VmovVT;
5135       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5136                                       SplatUndef.getZExtValue(), SplatBitSize,
5137                                       DAG, dl, VmovVT, VT.is128BitVector(),
5138                                       VMOVModImm);
5139       if (Val.getNode()) {
5140         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5141         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5142       }
5143
5144       // Try an immediate VMVN.
5145       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5146       Val = isNEONModifiedImm(NegatedImm,
5147                                       SplatUndef.getZExtValue(), SplatBitSize,
5148                                       DAG, dl, VmovVT, VT.is128BitVector(),
5149                                       VMVNModImm);
5150       if (Val.getNode()) {
5151         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5152         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5153       }
5154
5155       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5156       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5157         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5158         if (ImmVal != -1) {
5159           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5160           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5161         }
5162       }
5163     }
5164   }
5165
5166   // Scan through the operands to see if only one value is used.
5167   //
5168   // As an optimisation, even if more than one value is used it may be more
5169   // profitable to splat with one value then change some lanes.
5170   //
5171   // Heuristically we decide to do this if the vector has a "dominant" value,
5172   // defined as splatted to more than half of the lanes.
5173   unsigned NumElts = VT.getVectorNumElements();
5174   bool isOnlyLowElement = true;
5175   bool usesOnlyOneValue = true;
5176   bool hasDominantValue = false;
5177   bool isConstant = true;
5178
5179   // Map of the number of times a particular SDValue appears in the
5180   // element list.
5181   DenseMap<SDValue, unsigned> ValueCounts;
5182   SDValue Value;
5183   for (unsigned i = 0; i < NumElts; ++i) {
5184     SDValue V = Op.getOperand(i);
5185     if (V.getOpcode() == ISD::UNDEF)
5186       continue;
5187     if (i > 0)
5188       isOnlyLowElement = false;
5189     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5190       isConstant = false;
5191
5192     ValueCounts.insert(std::make_pair(V, 0));
5193     unsigned &Count = ValueCounts[V];
5194
5195     // Is this value dominant? (takes up more than half of the lanes)
5196     if (++Count > (NumElts / 2)) {
5197       hasDominantValue = true;
5198       Value = V;
5199     }
5200   }
5201   if (ValueCounts.size() != 1)
5202     usesOnlyOneValue = false;
5203   if (!Value.getNode() && ValueCounts.size() > 0)
5204     Value = ValueCounts.begin()->first;
5205
5206   if (ValueCounts.size() == 0)
5207     return DAG.getUNDEF(VT);
5208
5209   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5210   // Keep going if we are hitting this case.
5211   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5212     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5213
5214   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5215
5216   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5217   // i32 and try again.
5218   if (hasDominantValue && EltSize <= 32) {
5219     if (!isConstant) {
5220       SDValue N;
5221
5222       // If we are VDUPing a value that comes directly from a vector, that will
5223       // cause an unnecessary move to and from a GPR, where instead we could
5224       // just use VDUPLANE. We can only do this if the lane being extracted
5225       // is at a constant index, as the VDUP from lane instructions only have
5226       // constant-index forms.
5227       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5228           isa<ConstantSDNode>(Value->getOperand(1))) {
5229         // We need to create a new undef vector to use for the VDUPLANE if the
5230         // size of the vector from which we get the value is different than the
5231         // size of the vector that we need to create. We will insert the element
5232         // such that the register coalescer will remove unnecessary copies.
5233         if (VT != Value->getOperand(0).getValueType()) {
5234           ConstantSDNode *constIndex;
5235           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5236           assert(constIndex && "The index is not a constant!");
5237           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5238                              VT.getVectorNumElements();
5239           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5240                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5241                         Value, DAG.getConstant(index, dl, MVT::i32)),
5242                            DAG.getConstant(index, dl, MVT::i32));
5243         } else
5244           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5245                         Value->getOperand(0), Value->getOperand(1));
5246       } else
5247         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5248
5249       if (!usesOnlyOneValue) {
5250         // The dominant value was splatted as 'N', but we now have to insert
5251         // all differing elements.
5252         for (unsigned I = 0; I < NumElts; ++I) {
5253           if (Op.getOperand(I) == Value)
5254             continue;
5255           SmallVector<SDValue, 3> Ops;
5256           Ops.push_back(N);
5257           Ops.push_back(Op.getOperand(I));
5258           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5259           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5260         }
5261       }
5262       return N;
5263     }
5264     if (VT.getVectorElementType().isFloatingPoint()) {
5265       SmallVector<SDValue, 8> Ops;
5266       for (unsigned i = 0; i < NumElts; ++i)
5267         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5268                                   Op.getOperand(i)));
5269       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5270       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5271       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5272       if (Val.getNode())
5273         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5274     }
5275     if (usesOnlyOneValue) {
5276       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5277       if (isConstant && Val.getNode())
5278         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5279     }
5280   }
5281
5282   // If all elements are constants and the case above didn't get hit, fall back
5283   // to the default expansion, which will generate a load from the constant
5284   // pool.
5285   if (isConstant)
5286     return SDValue();
5287
5288   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5289   if (NumElts >= 4) {
5290     SDValue shuffle = ReconstructShuffle(Op, DAG);
5291     if (shuffle != SDValue())
5292       return shuffle;
5293   }
5294
5295   // Vectors with 32- or 64-bit elements can be built by directly assigning
5296   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5297   // will be legalized.
5298   if (EltSize >= 32) {
5299     // Do the expansion with floating-point types, since that is what the VFP
5300     // registers are defined to use, and since i64 is not legal.
5301     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5302     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5303     SmallVector<SDValue, 8> Ops;
5304     for (unsigned i = 0; i < NumElts; ++i)
5305       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5306     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5307     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5308   }
5309
5310   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5311   // know the default expansion would otherwise fall back on something even
5312   // worse. For a vector with one or two non-undef values, that's
5313   // scalar_to_vector for the elements followed by a shuffle (provided the
5314   // shuffle is valid for the target) and materialization element by element
5315   // on the stack followed by a load for everything else.
5316   if (!isConstant && !usesOnlyOneValue) {
5317     SDValue Vec = DAG.getUNDEF(VT);
5318     for (unsigned i = 0 ; i < NumElts; ++i) {
5319       SDValue V = Op.getOperand(i);
5320       if (V.getOpcode() == ISD::UNDEF)
5321         continue;
5322       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5323       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5324     }
5325     return Vec;
5326   }
5327
5328   return SDValue();
5329 }
5330
5331 // Gather data to see if the operation can be modelled as a
5332 // shuffle in combination with VEXTs.
5333 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5334                                               SelectionDAG &DAG) const {
5335   SDLoc dl(Op);
5336   EVT VT = Op.getValueType();
5337   unsigned NumElts = VT.getVectorNumElements();
5338
5339   SmallVector<SDValue, 2> SourceVecs;
5340   SmallVector<unsigned, 2> MinElts;
5341   SmallVector<unsigned, 2> MaxElts;
5342
5343   for (unsigned i = 0; i < NumElts; ++i) {
5344     SDValue V = Op.getOperand(i);
5345     if (V.getOpcode() == ISD::UNDEF)
5346       continue;
5347     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5348       // A shuffle can only come from building a vector from various
5349       // elements of other vectors.
5350       return SDValue();
5351     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5352                VT.getVectorElementType()) {
5353       // This code doesn't know how to handle shuffles where the vector
5354       // element types do not match (this happens because type legalization
5355       // promotes the return type of EXTRACT_VECTOR_ELT).
5356       // FIXME: It might be appropriate to extend this code to handle
5357       // mismatched types.
5358       return SDValue();
5359     }
5360
5361     // Record this extraction against the appropriate vector if possible...
5362     SDValue SourceVec = V.getOperand(0);
5363     // If the element number isn't a constant, we can't effectively
5364     // analyze what's going on.
5365     if (!isa<ConstantSDNode>(V.getOperand(1)))
5366       return SDValue();
5367     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5368     bool FoundSource = false;
5369     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5370       if (SourceVecs[j] == SourceVec) {
5371         if (MinElts[j] > EltNo)
5372           MinElts[j] = EltNo;
5373         if (MaxElts[j] < EltNo)
5374           MaxElts[j] = EltNo;
5375         FoundSource = true;
5376         break;
5377       }
5378     }
5379
5380     // Or record a new source if not...
5381     if (!FoundSource) {
5382       SourceVecs.push_back(SourceVec);
5383       MinElts.push_back(EltNo);
5384       MaxElts.push_back(EltNo);
5385     }
5386   }
5387
5388   // Currently only do something sane when at most two source vectors
5389   // involved.
5390   if (SourceVecs.size() > 2)
5391     return SDValue();
5392
5393   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5394   int VEXTOffsets[2] = {0, 0};
5395
5396   // This loop extracts the usage patterns of the source vectors
5397   // and prepares appropriate SDValues for a shuffle if possible.
5398   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5399     if (SourceVecs[i].getValueType() == VT) {
5400       // No VEXT necessary
5401       ShuffleSrcs[i] = SourceVecs[i];
5402       VEXTOffsets[i] = 0;
5403       continue;
5404     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5405       // It probably isn't worth padding out a smaller vector just to
5406       // break it down again in a shuffle.
5407       return SDValue();
5408     }
5409
5410     // Since only 64-bit and 128-bit vectors are legal on ARM and
5411     // we've eliminated the other cases...
5412     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5413            "unexpected vector sizes in ReconstructShuffle");
5414
5415     if (MaxElts[i] - MinElts[i] >= NumElts) {
5416       // Span too large for a VEXT to cope
5417       return SDValue();
5418     }
5419
5420     if (MinElts[i] >= NumElts) {
5421       // The extraction can just take the second half
5422       VEXTOffsets[i] = NumElts;
5423       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5424                                    SourceVecs[i],
5425                                    DAG.getIntPtrConstant(NumElts, dl));
5426     } else if (MaxElts[i] < NumElts) {
5427       // The extraction can just take the first half
5428       VEXTOffsets[i] = 0;
5429       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5430                                    SourceVecs[i],
5431                                    DAG.getIntPtrConstant(0, dl));
5432     } else {
5433       // An actual VEXT is needed
5434       VEXTOffsets[i] = MinElts[i];
5435       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5436                                      SourceVecs[i],
5437                                      DAG.getIntPtrConstant(0, dl));
5438       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5439                                      SourceVecs[i],
5440                                      DAG.getIntPtrConstant(NumElts, dl));
5441       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5442                                    DAG.getConstant(VEXTOffsets[i], dl,
5443                                                    MVT::i32));
5444     }
5445   }
5446
5447   SmallVector<int, 8> Mask;
5448
5449   for (unsigned i = 0; i < NumElts; ++i) {
5450     SDValue Entry = Op.getOperand(i);
5451     if (Entry.getOpcode() == ISD::UNDEF) {
5452       Mask.push_back(-1);
5453       continue;
5454     }
5455
5456     SDValue ExtractVec = Entry.getOperand(0);
5457     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5458                                           .getOperand(1))->getSExtValue();
5459     if (ExtractVec == SourceVecs[0]) {
5460       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5461     } else {
5462       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5463     }
5464   }
5465
5466   // Final check before we try to produce nonsense...
5467   if (isShuffleMaskLegal(Mask, VT))
5468     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5469                                 &Mask[0]);
5470
5471   return SDValue();
5472 }
5473
5474 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5475 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5476 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5477 /// are assumed to be legal.
5478 bool
5479 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5480                                       EVT VT) const {
5481   if (VT.getVectorNumElements() == 4 &&
5482       (VT.is128BitVector() || VT.is64BitVector())) {
5483     unsigned PFIndexes[4];
5484     for (unsigned i = 0; i != 4; ++i) {
5485       if (M[i] < 0)
5486         PFIndexes[i] = 8;
5487       else
5488         PFIndexes[i] = M[i];
5489     }
5490
5491     // Compute the index in the perfect shuffle table.
5492     unsigned PFTableIndex =
5493       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5494     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5495     unsigned Cost = (PFEntry >> 30);
5496
5497     if (Cost <= 4)
5498       return true;
5499   }
5500
5501   bool ReverseVEXT, isV_UNDEF;
5502   unsigned Imm, WhichResult;
5503
5504   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5505   return (EltSize >= 32 ||
5506           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5507           isVREVMask(M, VT, 64) ||
5508           isVREVMask(M, VT, 32) ||
5509           isVREVMask(M, VT, 16) ||
5510           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5511           isVTBLMask(M, VT) ||
5512           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5513           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5514 }
5515
5516 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5517 /// the specified operations to build the shuffle.
5518 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5519                                       SDValue RHS, SelectionDAG &DAG,
5520                                       SDLoc dl) {
5521   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5522   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5523   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5524
5525   enum {
5526     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5527     OP_VREV,
5528     OP_VDUP0,
5529     OP_VDUP1,
5530     OP_VDUP2,
5531     OP_VDUP3,
5532     OP_VEXT1,
5533     OP_VEXT2,
5534     OP_VEXT3,
5535     OP_VUZPL, // VUZP, left result
5536     OP_VUZPR, // VUZP, right result
5537     OP_VZIPL, // VZIP, left result
5538     OP_VZIPR, // VZIP, right result
5539     OP_VTRNL, // VTRN, left result
5540     OP_VTRNR  // VTRN, right result
5541   };
5542
5543   if (OpNum == OP_COPY) {
5544     if (LHSID == (1*9+2)*9+3) return LHS;
5545     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5546     return RHS;
5547   }
5548
5549   SDValue OpLHS, OpRHS;
5550   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5551   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5552   EVT VT = OpLHS.getValueType();
5553
5554   switch (OpNum) {
5555   default: llvm_unreachable("Unknown shuffle opcode!");
5556   case OP_VREV:
5557     // VREV divides the vector in half and swaps within the half.
5558     if (VT.getVectorElementType() == MVT::i32 ||
5559         VT.getVectorElementType() == MVT::f32)
5560       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5561     // vrev <4 x i16> -> VREV32
5562     if (VT.getVectorElementType() == MVT::i16)
5563       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5564     // vrev <4 x i8> -> VREV16
5565     assert(VT.getVectorElementType() == MVT::i8);
5566     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5567   case OP_VDUP0:
5568   case OP_VDUP1:
5569   case OP_VDUP2:
5570   case OP_VDUP3:
5571     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5572                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5573   case OP_VEXT1:
5574   case OP_VEXT2:
5575   case OP_VEXT3:
5576     return DAG.getNode(ARMISD::VEXT, dl, VT,
5577                        OpLHS, OpRHS,
5578                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5579   case OP_VUZPL:
5580   case OP_VUZPR:
5581     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5582                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5583   case OP_VZIPL:
5584   case OP_VZIPR:
5585     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5586                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5587   case OP_VTRNL:
5588   case OP_VTRNR:
5589     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5590                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5591   }
5592 }
5593
5594 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5595                                        ArrayRef<int> ShuffleMask,
5596                                        SelectionDAG &DAG) {
5597   // Check to see if we can use the VTBL instruction.
5598   SDValue V1 = Op.getOperand(0);
5599   SDValue V2 = Op.getOperand(1);
5600   SDLoc DL(Op);
5601
5602   SmallVector<SDValue, 8> VTBLMask;
5603   for (ArrayRef<int>::iterator
5604          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5605     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5606
5607   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5608     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5609                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5610
5611   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5612                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5613 }
5614
5615 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5616                                                       SelectionDAG &DAG) {
5617   SDLoc DL(Op);
5618   SDValue OpLHS = Op.getOperand(0);
5619   EVT VT = OpLHS.getValueType();
5620
5621   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5622          "Expect an v8i16/v16i8 type");
5623   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5624   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5625   // extract the first 8 bytes into the top double word and the last 8 bytes
5626   // into the bottom double word. The v8i16 case is similar.
5627   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5628   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5629                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5630 }
5631
5632 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5633   SDValue V1 = Op.getOperand(0);
5634   SDValue V2 = Op.getOperand(1);
5635   SDLoc dl(Op);
5636   EVT VT = Op.getValueType();
5637   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5638
5639   // Convert shuffles that are directly supported on NEON to target-specific
5640   // DAG nodes, instead of keeping them as shuffles and matching them again
5641   // during code selection.  This is more efficient and avoids the possibility
5642   // of inconsistencies between legalization and selection.
5643   // FIXME: floating-point vectors should be canonicalized to integer vectors
5644   // of the same time so that they get CSEd properly.
5645   ArrayRef<int> ShuffleMask = SVN->getMask();
5646
5647   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5648   if (EltSize <= 32) {
5649     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5650       int Lane = SVN->getSplatIndex();
5651       // If this is undef splat, generate it via "just" vdup, if possible.
5652       if (Lane == -1) Lane = 0;
5653
5654       // Test if V1 is a SCALAR_TO_VECTOR.
5655       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5656         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5657       }
5658       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5659       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5660       // reaches it).
5661       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5662           !isa<ConstantSDNode>(V1.getOperand(0))) {
5663         bool IsScalarToVector = true;
5664         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5665           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5666             IsScalarToVector = false;
5667             break;
5668           }
5669         if (IsScalarToVector)
5670           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5671       }
5672       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5673                          DAG.getConstant(Lane, dl, MVT::i32));
5674     }
5675
5676     bool ReverseVEXT;
5677     unsigned Imm;
5678     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5679       if (ReverseVEXT)
5680         std::swap(V1, V2);
5681       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5682                          DAG.getConstant(Imm, dl, MVT::i32));
5683     }
5684
5685     if (isVREVMask(ShuffleMask, VT, 64))
5686       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5687     if (isVREVMask(ShuffleMask, VT, 32))
5688       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5689     if (isVREVMask(ShuffleMask, VT, 16))
5690       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5691
5692     if (V2->getOpcode() == ISD::UNDEF &&
5693         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5694       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5695                          DAG.getConstant(Imm, dl, MVT::i32));
5696     }
5697
5698     // Check for Neon shuffles that modify both input vectors in place.
5699     // If both results are used, i.e., if there are two shuffles with the same
5700     // source operands and with masks corresponding to both results of one of
5701     // these operations, DAG memoization will ensure that a single node is
5702     // used for both shuffles.
5703     unsigned WhichResult;
5704     bool isV_UNDEF;
5705     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5706             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5707       if (isV_UNDEF)
5708         V2 = V1;
5709       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5710           .getValue(WhichResult);
5711     }
5712
5713     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5714     // shuffles that produce a result larger than their operands with:
5715     //   shuffle(concat(v1, undef), concat(v2, undef))
5716     // ->
5717     //   shuffle(concat(v1, v2), undef)
5718     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5719     //
5720     // This is useful in the general case, but there are special cases where
5721     // native shuffles produce larger results: the two-result ops.
5722     //
5723     // Look through the concat when lowering them:
5724     //   shuffle(concat(v1, v2), undef)
5725     // ->
5726     //   concat(VZIP(v1, v2):0, :1)
5727     //
5728     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5729         V2->getOpcode() == ISD::UNDEF) {
5730       SDValue SubV1 = V1->getOperand(0);
5731       SDValue SubV2 = V1->getOperand(1);
5732       EVT SubVT = SubV1.getValueType();
5733
5734       // We expect these to have been canonicalized to -1.
5735       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5736         return i < (int)VT.getVectorNumElements();
5737       }) && "Unexpected shuffle index into UNDEF operand!");
5738
5739       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5740               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5741         if (isV_UNDEF)
5742           SubV2 = SubV1;
5743         assert((WhichResult == 0) &&
5744                "In-place shuffle of concat can only have one result!");
5745         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5746                                   SubV1, SubV2);
5747         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5748                            Res.getValue(1));
5749       }
5750     }
5751   }
5752
5753   // If the shuffle is not directly supported and it has 4 elements, use
5754   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5755   unsigned NumElts = VT.getVectorNumElements();
5756   if (NumElts == 4) {
5757     unsigned PFIndexes[4];
5758     for (unsigned i = 0; i != 4; ++i) {
5759       if (ShuffleMask[i] < 0)
5760         PFIndexes[i] = 8;
5761       else
5762         PFIndexes[i] = ShuffleMask[i];
5763     }
5764
5765     // Compute the index in the perfect shuffle table.
5766     unsigned PFTableIndex =
5767       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5768     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5769     unsigned Cost = (PFEntry >> 30);
5770
5771     if (Cost <= 4)
5772       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5773   }
5774
5775   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5776   if (EltSize >= 32) {
5777     // Do the expansion with floating-point types, since that is what the VFP
5778     // registers are defined to use, and since i64 is not legal.
5779     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5780     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5781     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5782     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5783     SmallVector<SDValue, 8> Ops;
5784     for (unsigned i = 0; i < NumElts; ++i) {
5785       if (ShuffleMask[i] < 0)
5786         Ops.push_back(DAG.getUNDEF(EltVT));
5787       else
5788         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5789                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5790                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5791                                                   dl, MVT::i32)));
5792     }
5793     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5794     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5795   }
5796
5797   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5798     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5799
5800   if (VT == MVT::v8i8) {
5801     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5802     if (NewOp.getNode())
5803       return NewOp;
5804   }
5805
5806   return SDValue();
5807 }
5808
5809 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5810   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5811   SDValue Lane = Op.getOperand(2);
5812   if (!isa<ConstantSDNode>(Lane))
5813     return SDValue();
5814
5815   return Op;
5816 }
5817
5818 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5819   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5820   SDValue Lane = Op.getOperand(1);
5821   if (!isa<ConstantSDNode>(Lane))
5822     return SDValue();
5823
5824   SDValue Vec = Op.getOperand(0);
5825   if (Op.getValueType() == MVT::i32 &&
5826       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5827     SDLoc dl(Op);
5828     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5829   }
5830
5831   return Op;
5832 }
5833
5834 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5835   // The only time a CONCAT_VECTORS operation can have legal types is when
5836   // two 64-bit vectors are concatenated to a 128-bit vector.
5837   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5838          "unexpected CONCAT_VECTORS");
5839   SDLoc dl(Op);
5840   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5841   SDValue Op0 = Op.getOperand(0);
5842   SDValue Op1 = Op.getOperand(1);
5843   if (Op0.getOpcode() != ISD::UNDEF)
5844     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5845                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5846                       DAG.getIntPtrConstant(0, dl));
5847   if (Op1.getOpcode() != ISD::UNDEF)
5848     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5849                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5850                       DAG.getIntPtrConstant(1, dl));
5851   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5852 }
5853
5854 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5855 /// element has been zero/sign-extended, depending on the isSigned parameter,
5856 /// from an integer type half its size.
5857 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5858                                    bool isSigned) {
5859   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5860   EVT VT = N->getValueType(0);
5861   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5862     SDNode *BVN = N->getOperand(0).getNode();
5863     if (BVN->getValueType(0) != MVT::v4i32 ||
5864         BVN->getOpcode() != ISD::BUILD_VECTOR)
5865       return false;
5866     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
5867     unsigned HiElt = 1 - LoElt;
5868     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5869     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5870     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5871     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5872     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5873       return false;
5874     if (isSigned) {
5875       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5876           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5877         return true;
5878     } else {
5879       if (Hi0->isNullValue() && Hi1->isNullValue())
5880         return true;
5881     }
5882     return false;
5883   }
5884
5885   if (N->getOpcode() != ISD::BUILD_VECTOR)
5886     return false;
5887
5888   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5889     SDNode *Elt = N->getOperand(i).getNode();
5890     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5891       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5892       unsigned HalfSize = EltSize / 2;
5893       if (isSigned) {
5894         if (!isIntN(HalfSize, C->getSExtValue()))
5895           return false;
5896       } else {
5897         if (!isUIntN(HalfSize, C->getZExtValue()))
5898           return false;
5899       }
5900       continue;
5901     }
5902     return false;
5903   }
5904
5905   return true;
5906 }
5907
5908 /// isSignExtended - Check if a node is a vector value that is sign-extended
5909 /// or a constant BUILD_VECTOR with sign-extended elements.
5910 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5911   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5912     return true;
5913   if (isExtendedBUILD_VECTOR(N, DAG, true))
5914     return true;
5915   return false;
5916 }
5917
5918 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5919 /// or a constant BUILD_VECTOR with zero-extended elements.
5920 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5921   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5922     return true;
5923   if (isExtendedBUILD_VECTOR(N, DAG, false))
5924     return true;
5925   return false;
5926 }
5927
5928 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5929   if (OrigVT.getSizeInBits() >= 64)
5930     return OrigVT;
5931
5932   assert(OrigVT.isSimple() && "Expecting a simple value type");
5933
5934   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5935   switch (OrigSimpleTy) {
5936   default: llvm_unreachable("Unexpected Vector Type");
5937   case MVT::v2i8:
5938   case MVT::v2i16:
5939      return MVT::v2i32;
5940   case MVT::v4i8:
5941     return  MVT::v4i16;
5942   }
5943 }
5944
5945 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5946 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5947 /// We insert the required extension here to get the vector to fill a D register.
5948 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5949                                             const EVT &OrigTy,
5950                                             const EVT &ExtTy,
5951                                             unsigned ExtOpcode) {
5952   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5953   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5954   // 64-bits we need to insert a new extension so that it will be 64-bits.
5955   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5956   if (OrigTy.getSizeInBits() >= 64)
5957     return N;
5958
5959   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5960   EVT NewVT = getExtensionTo64Bits(OrigTy);
5961
5962   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5963 }
5964
5965 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5966 /// does not do any sign/zero extension. If the original vector is less
5967 /// than 64 bits, an appropriate extension will be added after the load to
5968 /// reach a total size of 64 bits. We have to add the extension separately
5969 /// because ARM does not have a sign/zero extending load for vectors.
5970 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5971   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5972
5973   // The load already has the right type.
5974   if (ExtendedTy == LD->getMemoryVT())
5975     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5976                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5977                 LD->isNonTemporal(), LD->isInvariant(),
5978                 LD->getAlignment());
5979
5980   // We need to create a zextload/sextload. We cannot just create a load
5981   // followed by a zext/zext node because LowerMUL is also run during normal
5982   // operation legalization where we can't create illegal types.
5983   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5984                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5985                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5986                         LD->isNonTemporal(), LD->getAlignment());
5987 }
5988
5989 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5990 /// extending load, or BUILD_VECTOR with extended elements, return the
5991 /// unextended value. The unextended vector should be 64 bits so that it can
5992 /// be used as an operand to a VMULL instruction. If the original vector size
5993 /// before extension is less than 64 bits we add a an extension to resize
5994 /// the vector to 64 bits.
5995 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5996   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5997     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5998                                         N->getOperand(0)->getValueType(0),
5999                                         N->getValueType(0),
6000                                         N->getOpcode());
6001
6002   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6003     return SkipLoadExtensionForVMULL(LD, DAG);
6004
6005   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6006   // have been legalized as a BITCAST from v4i32.
6007   if (N->getOpcode() == ISD::BITCAST) {
6008     SDNode *BVN = N->getOperand(0).getNode();
6009     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6010            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6011     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6012     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6013                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6014   }
6015   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6016   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6017   EVT VT = N->getValueType(0);
6018   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6019   unsigned NumElts = VT.getVectorNumElements();
6020   MVT TruncVT = MVT::getIntegerVT(EltSize);
6021   SmallVector<SDValue, 8> Ops;
6022   SDLoc dl(N);
6023   for (unsigned i = 0; i != NumElts; ++i) {
6024     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6025     const APInt &CInt = C->getAPIntValue();
6026     // Element types smaller than 32 bits are not legal, so use i32 elements.
6027     // The values are implicitly truncated so sext vs. zext doesn't matter.
6028     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6029   }
6030   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6031                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6032 }
6033
6034 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6035   unsigned Opcode = N->getOpcode();
6036   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6037     SDNode *N0 = N->getOperand(0).getNode();
6038     SDNode *N1 = N->getOperand(1).getNode();
6039     return N0->hasOneUse() && N1->hasOneUse() &&
6040       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6041   }
6042   return false;
6043 }
6044
6045 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6046   unsigned Opcode = N->getOpcode();
6047   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6048     SDNode *N0 = N->getOperand(0).getNode();
6049     SDNode *N1 = N->getOperand(1).getNode();
6050     return N0->hasOneUse() && N1->hasOneUse() &&
6051       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6052   }
6053   return false;
6054 }
6055
6056 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6057   // Multiplications are only custom-lowered for 128-bit vectors so that
6058   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6059   EVT VT = Op.getValueType();
6060   assert(VT.is128BitVector() && VT.isInteger() &&
6061          "unexpected type for custom-lowering ISD::MUL");
6062   SDNode *N0 = Op.getOperand(0).getNode();
6063   SDNode *N1 = Op.getOperand(1).getNode();
6064   unsigned NewOpc = 0;
6065   bool isMLA = false;
6066   bool isN0SExt = isSignExtended(N0, DAG);
6067   bool isN1SExt = isSignExtended(N1, DAG);
6068   if (isN0SExt && isN1SExt)
6069     NewOpc = ARMISD::VMULLs;
6070   else {
6071     bool isN0ZExt = isZeroExtended(N0, DAG);
6072     bool isN1ZExt = isZeroExtended(N1, DAG);
6073     if (isN0ZExt && isN1ZExt)
6074       NewOpc = ARMISD::VMULLu;
6075     else if (isN1SExt || isN1ZExt) {
6076       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6077       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6078       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6079         NewOpc = ARMISD::VMULLs;
6080         isMLA = true;
6081       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6082         NewOpc = ARMISD::VMULLu;
6083         isMLA = true;
6084       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6085         std::swap(N0, N1);
6086         NewOpc = ARMISD::VMULLu;
6087         isMLA = true;
6088       }
6089     }
6090
6091     if (!NewOpc) {
6092       if (VT == MVT::v2i64)
6093         // Fall through to expand this.  It is not legal.
6094         return SDValue();
6095       else
6096         // Other vector multiplications are legal.
6097         return Op;
6098     }
6099   }
6100
6101   // Legalize to a VMULL instruction.
6102   SDLoc DL(Op);
6103   SDValue Op0;
6104   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6105   if (!isMLA) {
6106     Op0 = SkipExtensionForVMULL(N0, DAG);
6107     assert(Op0.getValueType().is64BitVector() &&
6108            Op1.getValueType().is64BitVector() &&
6109            "unexpected types for extended operands to VMULL");
6110     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6111   }
6112
6113   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6114   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6115   //   vmull q0, d4, d6
6116   //   vmlal q0, d5, d6
6117   // is faster than
6118   //   vaddl q0, d4, d5
6119   //   vmovl q1, d6
6120   //   vmul  q0, q0, q1
6121   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6122   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6123   EVT Op1VT = Op1.getValueType();
6124   return DAG.getNode(N0->getOpcode(), DL, VT,
6125                      DAG.getNode(NewOpc, DL, VT,
6126                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6127                      DAG.getNode(NewOpc, DL, VT,
6128                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6129 }
6130
6131 static SDValue
6132 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6133   // Convert to float
6134   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6135   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6136   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6137   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6138   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6139   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6140   // Get reciprocal estimate.
6141   // float4 recip = vrecpeq_f32(yf);
6142   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6143                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6144                    Y);
6145   // Because char has a smaller range than uchar, we can actually get away
6146   // without any newton steps.  This requires that we use a weird bias
6147   // of 0xb000, however (again, this has been exhaustively tested).
6148   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6149   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6150   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6151   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6152   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6153   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6154   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6155   // Convert back to short.
6156   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6157   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6158   return X;
6159 }
6160
6161 static SDValue
6162 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6163   SDValue N2;
6164   // Convert to float.
6165   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6166   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6167   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6168   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6169   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6170   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6171
6172   // Use reciprocal estimate and one refinement step.
6173   // float4 recip = vrecpeq_f32(yf);
6174   // recip *= vrecpsq_f32(yf, recip);
6175   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6176                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6177                    N1);
6178   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6179                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6180                    N1, N2);
6181   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6182   // Because short has a smaller range than ushort, we can actually get away
6183   // with only a single newton step.  This requires that we use a weird bias
6184   // of 89, however (again, this has been exhaustively tested).
6185   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6186   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6187   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6188   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6189   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6190   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6191   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6192   // Convert back to integer and return.
6193   // return vmovn_s32(vcvt_s32_f32(result));
6194   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6195   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6196   return N0;
6197 }
6198
6199 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6200   EVT VT = Op.getValueType();
6201   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6202          "unexpected type for custom-lowering ISD::SDIV");
6203
6204   SDLoc dl(Op);
6205   SDValue N0 = Op.getOperand(0);
6206   SDValue N1 = Op.getOperand(1);
6207   SDValue N2, N3;
6208
6209   if (VT == MVT::v8i8) {
6210     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6211     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6212
6213     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6214                      DAG.getIntPtrConstant(4, dl));
6215     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6216                      DAG.getIntPtrConstant(4, dl));
6217     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6218                      DAG.getIntPtrConstant(0, dl));
6219     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6220                      DAG.getIntPtrConstant(0, dl));
6221
6222     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6223     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6224
6225     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6226     N0 = LowerCONCAT_VECTORS(N0, DAG);
6227
6228     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6229     return N0;
6230   }
6231   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6232 }
6233
6234 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6235   EVT VT = Op.getValueType();
6236   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6237          "unexpected type for custom-lowering ISD::UDIV");
6238
6239   SDLoc dl(Op);
6240   SDValue N0 = Op.getOperand(0);
6241   SDValue N1 = Op.getOperand(1);
6242   SDValue N2, N3;
6243
6244   if (VT == MVT::v8i8) {
6245     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6246     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6247
6248     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6249                      DAG.getIntPtrConstant(4, dl));
6250     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6251                      DAG.getIntPtrConstant(4, dl));
6252     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6253                      DAG.getIntPtrConstant(0, dl));
6254     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6255                      DAG.getIntPtrConstant(0, dl));
6256
6257     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6258     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6259
6260     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6261     N0 = LowerCONCAT_VECTORS(N0, DAG);
6262
6263     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6264                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6265                                      MVT::i32),
6266                      N0);
6267     return N0;
6268   }
6269
6270   // v4i16 sdiv ... Convert to float.
6271   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6272   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6273   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6274   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6275   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6276   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6277
6278   // Use reciprocal estimate and two refinement steps.
6279   // float4 recip = vrecpeq_f32(yf);
6280   // recip *= vrecpsq_f32(yf, recip);
6281   // recip *= vrecpsq_f32(yf, recip);
6282   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6283                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6284                    BN1);
6285   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6286                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6287                    BN1, N2);
6288   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6289   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6290                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6291                    BN1, N2);
6292   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6293   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6294   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6295   // and that it will never cause us to return an answer too large).
6296   // float4 result = as_float4(as_int4(xf*recip) + 2);
6297   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6298   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6299   N1 = DAG.getConstant(2, dl, MVT::i32);
6300   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6301   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6302   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6303   // Convert back to integer and return.
6304   // return vmovn_u32(vcvt_s32_f32(result));
6305   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6306   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6307   return N0;
6308 }
6309
6310 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6311   EVT VT = Op.getNode()->getValueType(0);
6312   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6313
6314   unsigned Opc;
6315   bool ExtraOp = false;
6316   switch (Op.getOpcode()) {
6317   default: llvm_unreachable("Invalid code");
6318   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6319   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6320   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6321   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6322   }
6323
6324   if (!ExtraOp)
6325     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6326                        Op.getOperand(1));
6327   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6328                      Op.getOperand(1), Op.getOperand(2));
6329 }
6330
6331 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6332   assert(Subtarget->isTargetDarwin());
6333
6334   // For iOS, we want to call an alternative entry point: __sincos_stret,
6335   // return values are passed via sret.
6336   SDLoc dl(Op);
6337   SDValue Arg = Op.getOperand(0);
6338   EVT ArgVT = Arg.getValueType();
6339   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6340
6341   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6342   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6343
6344   // Pair of floats / doubles used to pass the result.
6345   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6346
6347   // Create stack object for sret.
6348   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6349   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6350   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6351   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6352
6353   ArgListTy Args;
6354   ArgListEntry Entry;
6355
6356   Entry.Node = SRet;
6357   Entry.Ty = RetTy->getPointerTo();
6358   Entry.isSExt = false;
6359   Entry.isZExt = false;
6360   Entry.isSRet = true;
6361   Args.push_back(Entry);
6362
6363   Entry.Node = Arg;
6364   Entry.Ty = ArgTy;
6365   Entry.isSExt = false;
6366   Entry.isZExt = false;
6367   Args.push_back(Entry);
6368
6369   const char *LibcallName  = (ArgVT == MVT::f64)
6370   ? "__sincos_stret" : "__sincosf_stret";
6371   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6372
6373   TargetLowering::CallLoweringInfo CLI(DAG);
6374   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6375     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6376                std::move(Args), 0)
6377     .setDiscardResult();
6378
6379   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6380
6381   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6382                                 MachinePointerInfo(), false, false, false, 0);
6383
6384   // Address of cos field.
6385   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6386                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6387   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6388                                 MachinePointerInfo(), false, false, false, 0);
6389
6390   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6391   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6392                      LoadSin.getValue(0), LoadCos.getValue(0));
6393 }
6394
6395 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6396   // Monotonic load/store is legal for all targets
6397   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6398     return Op;
6399
6400   // Acquire/Release load/store is not legal for targets without a
6401   // dmb or equivalent available.
6402   return SDValue();
6403 }
6404
6405 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6406                                     SmallVectorImpl<SDValue> &Results,
6407                                     SelectionDAG &DAG,
6408                                     const ARMSubtarget *Subtarget) {
6409   SDLoc DL(N);
6410   SDValue Cycles32, OutChain;
6411
6412   if (Subtarget->hasPerfMon()) {
6413     // Under Power Management extensions, the cycle-count is:
6414     //    mrc p15, #0, <Rt>, c9, c13, #0
6415     SDValue Ops[] = { N->getOperand(0), // Chain
6416                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6417                       DAG.getConstant(15, DL, MVT::i32),
6418                       DAG.getConstant(0, DL, MVT::i32),
6419                       DAG.getConstant(9, DL, MVT::i32),
6420                       DAG.getConstant(13, DL, MVT::i32),
6421                       DAG.getConstant(0, DL, MVT::i32)
6422     };
6423
6424     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6425                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6426     OutChain = Cycles32.getValue(1);
6427   } else {
6428     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6429     // there are older ARM CPUs that have implementation-specific ways of
6430     // obtaining this information (FIXME!).
6431     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6432     OutChain = DAG.getEntryNode();
6433   }
6434
6435
6436   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6437                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6438   Results.push_back(Cycles64);
6439   Results.push_back(OutChain);
6440 }
6441
6442 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6443   switch (Op.getOpcode()) {
6444   default: llvm_unreachable("Don't know how to custom lower this!");
6445   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6446   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6447   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6448   case ISD::GlobalAddress:
6449     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6450     default: llvm_unreachable("unknown object format");
6451     case Triple::COFF:
6452       return LowerGlobalAddressWindows(Op, DAG);
6453     case Triple::ELF:
6454       return LowerGlobalAddressELF(Op, DAG);
6455     case Triple::MachO:
6456       return LowerGlobalAddressDarwin(Op, DAG);
6457     }
6458   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6459   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6460   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6461   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6462   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6463   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6464   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6465   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6466   case ISD::SINT_TO_FP:
6467   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6468   case ISD::FP_TO_SINT:
6469   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6470   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6471   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6472   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6473   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6474   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6475   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6476   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6477                                                                Subtarget);
6478   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6479   case ISD::SHL:
6480   case ISD::SRL:
6481   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6482   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6483   case ISD::SRL_PARTS:
6484   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6485   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6486   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6487   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6488   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6489   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6490   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6491   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6492   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6493   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6494   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6495   case ISD::MUL:           return LowerMUL(Op, DAG);
6496   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6497   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6498   case ISD::ADDC:
6499   case ISD::ADDE:
6500   case ISD::SUBC:
6501   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6502   case ISD::SADDO:
6503   case ISD::UADDO:
6504   case ISD::SSUBO:
6505   case ISD::USUBO:
6506     return LowerXALUO(Op, DAG);
6507   case ISD::ATOMIC_LOAD:
6508   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6509   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6510   case ISD::SDIVREM:
6511   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6512   case ISD::DYNAMIC_STACKALLOC:
6513     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6514       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6515     llvm_unreachable("Don't know how to custom lower this!");
6516   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6517   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6518   }
6519 }
6520
6521 /// ReplaceNodeResults - Replace the results of node with an illegal result
6522 /// type with new values built out of custom code.
6523 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6524                                            SmallVectorImpl<SDValue>&Results,
6525                                            SelectionDAG &DAG) const {
6526   SDValue Res;
6527   switch (N->getOpcode()) {
6528   default:
6529     llvm_unreachable("Don't know how to custom expand this!");
6530   case ISD::READ_REGISTER:
6531     ExpandREAD_REGISTER(N, Results, DAG);
6532     break;
6533   case ISD::BITCAST:
6534     Res = ExpandBITCAST(N, DAG);
6535     break;
6536   case ISD::SRL:
6537   case ISD::SRA:
6538     Res = Expand64BitShift(N, DAG, Subtarget);
6539     break;
6540   case ISD::READCYCLECOUNTER:
6541     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6542     return;
6543   }
6544   if (Res.getNode())
6545     Results.push_back(Res);
6546 }
6547
6548 //===----------------------------------------------------------------------===//
6549 //                           ARM Scheduler Hooks
6550 //===----------------------------------------------------------------------===//
6551
6552 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6553 /// registers the function context.
6554 void ARMTargetLowering::
6555 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6556                        MachineBasicBlock *DispatchBB, int FI) const {
6557   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6558   DebugLoc dl = MI->getDebugLoc();
6559   MachineFunction *MF = MBB->getParent();
6560   MachineRegisterInfo *MRI = &MF->getRegInfo();
6561   MachineConstantPool *MCP = MF->getConstantPool();
6562   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6563   const Function *F = MF->getFunction();
6564
6565   bool isThumb = Subtarget->isThumb();
6566   bool isThumb2 = Subtarget->isThumb2();
6567
6568   unsigned PCLabelId = AFI->createPICLabelUId();
6569   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6570   ARMConstantPoolValue *CPV =
6571     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6572   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6573
6574   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6575                                            : &ARM::GPRRegClass;
6576
6577   // Grab constant pool and fixed stack memory operands.
6578   MachineMemOperand *CPMMO =
6579     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6580                              MachineMemOperand::MOLoad, 4, 4);
6581
6582   MachineMemOperand *FIMMOSt =
6583     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6584                              MachineMemOperand::MOStore, 4, 4);
6585
6586   // Load the address of the dispatch MBB into the jump buffer.
6587   if (isThumb2) {
6588     // Incoming value: jbuf
6589     //   ldr.n  r5, LCPI1_1
6590     //   orr    r5, r5, #1
6591     //   add    r5, pc
6592     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6593     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6594     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6595                    .addConstantPoolIndex(CPI)
6596                    .addMemOperand(CPMMO));
6597     // Set the low bit because of thumb mode.
6598     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6599     AddDefaultCC(
6600       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6601                      .addReg(NewVReg1, RegState::Kill)
6602                      .addImm(0x01)));
6603     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6604     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6605       .addReg(NewVReg2, RegState::Kill)
6606       .addImm(PCLabelId);
6607     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6608                    .addReg(NewVReg3, RegState::Kill)
6609                    .addFrameIndex(FI)
6610                    .addImm(36)  // &jbuf[1] :: pc
6611                    .addMemOperand(FIMMOSt));
6612   } else if (isThumb) {
6613     // Incoming value: jbuf
6614     //   ldr.n  r1, LCPI1_4
6615     //   add    r1, pc
6616     //   mov    r2, #1
6617     //   orrs   r1, r2
6618     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6619     //   str    r1, [r2]
6620     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6621     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6622                    .addConstantPoolIndex(CPI)
6623                    .addMemOperand(CPMMO));
6624     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6625     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6626       .addReg(NewVReg1, RegState::Kill)
6627       .addImm(PCLabelId);
6628     // Set the low bit because of thumb mode.
6629     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6630     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6631                    .addReg(ARM::CPSR, RegState::Define)
6632                    .addImm(1));
6633     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6634     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6635                    .addReg(ARM::CPSR, RegState::Define)
6636                    .addReg(NewVReg2, RegState::Kill)
6637                    .addReg(NewVReg3, RegState::Kill));
6638     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6639     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6640             .addFrameIndex(FI)
6641             .addImm(36); // &jbuf[1] :: pc
6642     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6643                    .addReg(NewVReg4, RegState::Kill)
6644                    .addReg(NewVReg5, RegState::Kill)
6645                    .addImm(0)
6646                    .addMemOperand(FIMMOSt));
6647   } else {
6648     // Incoming value: jbuf
6649     //   ldr  r1, LCPI1_1
6650     //   add  r1, pc, r1
6651     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6652     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6653     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6654                    .addConstantPoolIndex(CPI)
6655                    .addImm(0)
6656                    .addMemOperand(CPMMO));
6657     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6658     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6659                    .addReg(NewVReg1, RegState::Kill)
6660                    .addImm(PCLabelId));
6661     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6662                    .addReg(NewVReg2, RegState::Kill)
6663                    .addFrameIndex(FI)
6664                    .addImm(36)  // &jbuf[1] :: pc
6665                    .addMemOperand(FIMMOSt));
6666   }
6667 }
6668
6669 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6670                                               MachineBasicBlock *MBB) const {
6671   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6672   DebugLoc dl = MI->getDebugLoc();
6673   MachineFunction *MF = MBB->getParent();
6674   MachineRegisterInfo *MRI = &MF->getRegInfo();
6675   MachineFrameInfo *MFI = MF->getFrameInfo();
6676   int FI = MFI->getFunctionContextIndex();
6677
6678   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6679                                                         : &ARM::GPRnopcRegClass;
6680
6681   // Get a mapping of the call site numbers to all of the landing pads they're
6682   // associated with.
6683   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6684   unsigned MaxCSNum = 0;
6685   MachineModuleInfo &MMI = MF->getMMI();
6686   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6687        ++BB) {
6688     if (!BB->isLandingPad()) continue;
6689
6690     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6691     // pad.
6692     for (MachineBasicBlock::iterator
6693            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6694       if (!II->isEHLabel()) continue;
6695
6696       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6697       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6698
6699       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6700       for (SmallVectorImpl<unsigned>::iterator
6701              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6702            CSI != CSE; ++CSI) {
6703         CallSiteNumToLPad[*CSI].push_back(BB);
6704         MaxCSNum = std::max(MaxCSNum, *CSI);
6705       }
6706       break;
6707     }
6708   }
6709
6710   // Get an ordered list of the machine basic blocks for the jump table.
6711   std::vector<MachineBasicBlock*> LPadList;
6712   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6713   LPadList.reserve(CallSiteNumToLPad.size());
6714   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6715     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6716     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6717            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6718       LPadList.push_back(*II);
6719       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6720     }
6721   }
6722
6723   assert(!LPadList.empty() &&
6724          "No landing pad destinations for the dispatch jump table!");
6725
6726   // Create the jump table and associated information.
6727   MachineJumpTableInfo *JTI =
6728     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6729   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6730   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6731
6732   // Create the MBBs for the dispatch code.
6733
6734   // Shove the dispatch's address into the return slot in the function context.
6735   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6736   DispatchBB->setIsLandingPad();
6737
6738   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6739   unsigned trap_opcode;
6740   if (Subtarget->isThumb())
6741     trap_opcode = ARM::tTRAP;
6742   else
6743     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6744
6745   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6746   DispatchBB->addSuccessor(TrapBB);
6747
6748   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6749   DispatchBB->addSuccessor(DispContBB);
6750
6751   // Insert and MBBs.
6752   MF->insert(MF->end(), DispatchBB);
6753   MF->insert(MF->end(), DispContBB);
6754   MF->insert(MF->end(), TrapBB);
6755
6756   // Insert code into the entry block that creates and registers the function
6757   // context.
6758   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6759
6760   MachineMemOperand *FIMMOLd =
6761     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6762                              MachineMemOperand::MOLoad |
6763                              MachineMemOperand::MOVolatile, 4, 4);
6764
6765   MachineInstrBuilder MIB;
6766   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6767
6768   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6769   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6770
6771   // Add a register mask with no preserved registers.  This results in all
6772   // registers being marked as clobbered.
6773   MIB.addRegMask(RI.getNoPreservedMask());
6774
6775   unsigned NumLPads = LPadList.size();
6776   if (Subtarget->isThumb2()) {
6777     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6778     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6779                    .addFrameIndex(FI)
6780                    .addImm(4)
6781                    .addMemOperand(FIMMOLd));
6782
6783     if (NumLPads < 256) {
6784       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6785                      .addReg(NewVReg1)
6786                      .addImm(LPadList.size()));
6787     } else {
6788       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6789       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6790                      .addImm(NumLPads & 0xFFFF));
6791
6792       unsigned VReg2 = VReg1;
6793       if ((NumLPads & 0xFFFF0000) != 0) {
6794         VReg2 = MRI->createVirtualRegister(TRC);
6795         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6796                        .addReg(VReg1)
6797                        .addImm(NumLPads >> 16));
6798       }
6799
6800       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6801                      .addReg(NewVReg1)
6802                      .addReg(VReg2));
6803     }
6804
6805     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6806       .addMBB(TrapBB)
6807       .addImm(ARMCC::HI)
6808       .addReg(ARM::CPSR);
6809
6810     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6811     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6812                    .addJumpTableIndex(MJTI));
6813
6814     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6815     AddDefaultCC(
6816       AddDefaultPred(
6817         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6818         .addReg(NewVReg3, RegState::Kill)
6819         .addReg(NewVReg1)
6820         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6821
6822     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6823       .addReg(NewVReg4, RegState::Kill)
6824       .addReg(NewVReg1)
6825       .addJumpTableIndex(MJTI);
6826   } else if (Subtarget->isThumb()) {
6827     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6828     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6829                    .addFrameIndex(FI)
6830                    .addImm(1)
6831                    .addMemOperand(FIMMOLd));
6832
6833     if (NumLPads < 256) {
6834       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6835                      .addReg(NewVReg1)
6836                      .addImm(NumLPads));
6837     } else {
6838       MachineConstantPool *ConstantPool = MF->getConstantPool();
6839       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6840       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6841
6842       // MachineConstantPool wants an explicit alignment.
6843       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6844       if (Align == 0)
6845         Align = getDataLayout()->getTypeAllocSize(C->getType());
6846       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6847
6848       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6849       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6850                      .addReg(VReg1, RegState::Define)
6851                      .addConstantPoolIndex(Idx));
6852       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6853                      .addReg(NewVReg1)
6854                      .addReg(VReg1));
6855     }
6856
6857     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6858       .addMBB(TrapBB)
6859       .addImm(ARMCC::HI)
6860       .addReg(ARM::CPSR);
6861
6862     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6863     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6864                    .addReg(ARM::CPSR, RegState::Define)
6865                    .addReg(NewVReg1)
6866                    .addImm(2));
6867
6868     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6869     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6870                    .addJumpTableIndex(MJTI));
6871
6872     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6873     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6874                    .addReg(ARM::CPSR, RegState::Define)
6875                    .addReg(NewVReg2, RegState::Kill)
6876                    .addReg(NewVReg3));
6877
6878     MachineMemOperand *JTMMOLd =
6879       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6880                                MachineMemOperand::MOLoad, 4, 4);
6881
6882     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6883     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6884                    .addReg(NewVReg4, RegState::Kill)
6885                    .addImm(0)
6886                    .addMemOperand(JTMMOLd));
6887
6888     unsigned NewVReg6 = NewVReg5;
6889     if (RelocM == Reloc::PIC_) {
6890       NewVReg6 = MRI->createVirtualRegister(TRC);
6891       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6892                      .addReg(ARM::CPSR, RegState::Define)
6893                      .addReg(NewVReg5, RegState::Kill)
6894                      .addReg(NewVReg3));
6895     }
6896
6897     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6898       .addReg(NewVReg6, RegState::Kill)
6899       .addJumpTableIndex(MJTI);
6900   } else {
6901     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6902     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6903                    .addFrameIndex(FI)
6904                    .addImm(4)
6905                    .addMemOperand(FIMMOLd));
6906
6907     if (NumLPads < 256) {
6908       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6909                      .addReg(NewVReg1)
6910                      .addImm(NumLPads));
6911     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6912       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6913       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6914                      .addImm(NumLPads & 0xFFFF));
6915
6916       unsigned VReg2 = VReg1;
6917       if ((NumLPads & 0xFFFF0000) != 0) {
6918         VReg2 = MRI->createVirtualRegister(TRC);
6919         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6920                        .addReg(VReg1)
6921                        .addImm(NumLPads >> 16));
6922       }
6923
6924       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6925                      .addReg(NewVReg1)
6926                      .addReg(VReg2));
6927     } else {
6928       MachineConstantPool *ConstantPool = MF->getConstantPool();
6929       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6930       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6931
6932       // MachineConstantPool wants an explicit alignment.
6933       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6934       if (Align == 0)
6935         Align = getDataLayout()->getTypeAllocSize(C->getType());
6936       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6937
6938       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6939       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6940                      .addReg(VReg1, RegState::Define)
6941                      .addConstantPoolIndex(Idx)
6942                      .addImm(0));
6943       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6944                      .addReg(NewVReg1)
6945                      .addReg(VReg1, RegState::Kill));
6946     }
6947
6948     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6949       .addMBB(TrapBB)
6950       .addImm(ARMCC::HI)
6951       .addReg(ARM::CPSR);
6952
6953     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6954     AddDefaultCC(
6955       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6956                      .addReg(NewVReg1)
6957                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6958     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6959     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6960                    .addJumpTableIndex(MJTI));
6961
6962     MachineMemOperand *JTMMOLd =
6963       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6964                                MachineMemOperand::MOLoad, 4, 4);
6965     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6966     AddDefaultPred(
6967       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6968       .addReg(NewVReg3, RegState::Kill)
6969       .addReg(NewVReg4)
6970       .addImm(0)
6971       .addMemOperand(JTMMOLd));
6972
6973     if (RelocM == Reloc::PIC_) {
6974       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6975         .addReg(NewVReg5, RegState::Kill)
6976         .addReg(NewVReg4)
6977         .addJumpTableIndex(MJTI);
6978     } else {
6979       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6980         .addReg(NewVReg5, RegState::Kill)
6981         .addJumpTableIndex(MJTI);
6982     }
6983   }
6984
6985   // Add the jump table entries as successors to the MBB.
6986   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6987   for (std::vector<MachineBasicBlock*>::iterator
6988          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6989     MachineBasicBlock *CurMBB = *I;
6990     if (SeenMBBs.insert(CurMBB).second)
6991       DispContBB->addSuccessor(CurMBB);
6992   }
6993
6994   // N.B. the order the invoke BBs are processed in doesn't matter here.
6995   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6996   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6997   for (MachineBasicBlock *BB : InvokeBBs) {
6998
6999     // Remove the landing pad successor from the invoke block and replace it
7000     // with the new dispatch block.
7001     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7002                                                   BB->succ_end());
7003     while (!Successors.empty()) {
7004       MachineBasicBlock *SMBB = Successors.pop_back_val();
7005       if (SMBB->isLandingPad()) {
7006         BB->removeSuccessor(SMBB);
7007         MBBLPads.push_back(SMBB);
7008       }
7009     }
7010
7011     BB->addSuccessor(DispatchBB);
7012
7013     // Find the invoke call and mark all of the callee-saved registers as
7014     // 'implicit defined' so that they're spilled. This prevents code from
7015     // moving instructions to before the EH block, where they will never be
7016     // executed.
7017     for (MachineBasicBlock::reverse_iterator
7018            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7019       if (!II->isCall()) continue;
7020
7021       DenseMap<unsigned, bool> DefRegs;
7022       for (MachineInstr::mop_iterator
7023              OI = II->operands_begin(), OE = II->operands_end();
7024            OI != OE; ++OI) {
7025         if (!OI->isReg()) continue;
7026         DefRegs[OI->getReg()] = true;
7027       }
7028
7029       MachineInstrBuilder MIB(*MF, &*II);
7030
7031       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7032         unsigned Reg = SavedRegs[i];
7033         if (Subtarget->isThumb2() &&
7034             !ARM::tGPRRegClass.contains(Reg) &&
7035             !ARM::hGPRRegClass.contains(Reg))
7036           continue;
7037         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7038           continue;
7039         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7040           continue;
7041         if (!DefRegs[Reg])
7042           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7043       }
7044
7045       break;
7046     }
7047   }
7048
7049   // Mark all former landing pads as non-landing pads. The dispatch is the only
7050   // landing pad now.
7051   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7052          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7053     (*I)->setIsLandingPad(false);
7054
7055   // The instruction is gone now.
7056   MI->eraseFromParent();
7057 }
7058
7059 static
7060 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7061   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7062        E = MBB->succ_end(); I != E; ++I)
7063     if (*I != Succ)
7064       return *I;
7065   llvm_unreachable("Expecting a BB with two successors!");
7066 }
7067
7068 /// Return the load opcode for a given load size. If load size >= 8,
7069 /// neon opcode will be returned.
7070 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7071   if (LdSize >= 8)
7072     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7073                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7074   if (IsThumb1)
7075     return LdSize == 4 ? ARM::tLDRi
7076                        : LdSize == 2 ? ARM::tLDRHi
7077                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7078   if (IsThumb2)
7079     return LdSize == 4 ? ARM::t2LDR_POST
7080                        : LdSize == 2 ? ARM::t2LDRH_POST
7081                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7082   return LdSize == 4 ? ARM::LDR_POST_IMM
7083                      : LdSize == 2 ? ARM::LDRH_POST
7084                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7085 }
7086
7087 /// Return the store opcode for a given store size. If store size >= 8,
7088 /// neon opcode will be returned.
7089 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7090   if (StSize >= 8)
7091     return StSize == 16 ? ARM::VST1q32wb_fixed
7092                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7093   if (IsThumb1)
7094     return StSize == 4 ? ARM::tSTRi
7095                        : StSize == 2 ? ARM::tSTRHi
7096                                      : StSize == 1 ? ARM::tSTRBi : 0;
7097   if (IsThumb2)
7098     return StSize == 4 ? ARM::t2STR_POST
7099                        : StSize == 2 ? ARM::t2STRH_POST
7100                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7101   return StSize == 4 ? ARM::STR_POST_IMM
7102                      : StSize == 2 ? ARM::STRH_POST
7103                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7104 }
7105
7106 /// Emit a post-increment load operation with given size. The instructions
7107 /// will be added to BB at Pos.
7108 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7109                        const TargetInstrInfo *TII, DebugLoc dl,
7110                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7111                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7112   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7113   assert(LdOpc != 0 && "Should have a load opcode");
7114   if (LdSize >= 8) {
7115     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7116                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7117                        .addImm(0));
7118   } else if (IsThumb1) {
7119     // load + update AddrIn
7120     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7121                        .addReg(AddrIn).addImm(0));
7122     MachineInstrBuilder MIB =
7123         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7124     MIB = AddDefaultT1CC(MIB);
7125     MIB.addReg(AddrIn).addImm(LdSize);
7126     AddDefaultPred(MIB);
7127   } else if (IsThumb2) {
7128     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7129                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7130                        .addImm(LdSize));
7131   } else { // arm
7132     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7133                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7134                        .addReg(0).addImm(LdSize));
7135   }
7136 }
7137
7138 /// Emit a post-increment store operation with given size. The instructions
7139 /// will be added to BB at Pos.
7140 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7141                        const TargetInstrInfo *TII, DebugLoc dl,
7142                        unsigned StSize, unsigned Data, unsigned AddrIn,
7143                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7144   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7145   assert(StOpc != 0 && "Should have a store opcode");
7146   if (StSize >= 8) {
7147     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7148                        .addReg(AddrIn).addImm(0).addReg(Data));
7149   } else if (IsThumb1) {
7150     // store + update AddrIn
7151     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7152                        .addReg(AddrIn).addImm(0));
7153     MachineInstrBuilder MIB =
7154         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7155     MIB = AddDefaultT1CC(MIB);
7156     MIB.addReg(AddrIn).addImm(StSize);
7157     AddDefaultPred(MIB);
7158   } else if (IsThumb2) {
7159     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7160                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7161   } else { // arm
7162     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7163                        .addReg(Data).addReg(AddrIn).addReg(0)
7164                        .addImm(StSize));
7165   }
7166 }
7167
7168 MachineBasicBlock *
7169 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7170                                    MachineBasicBlock *BB) const {
7171   // This pseudo instruction has 3 operands: dst, src, size
7172   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7173   // Otherwise, we will generate unrolled scalar copies.
7174   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7175   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7176   MachineFunction::iterator It = BB;
7177   ++It;
7178
7179   unsigned dest = MI->getOperand(0).getReg();
7180   unsigned src = MI->getOperand(1).getReg();
7181   unsigned SizeVal = MI->getOperand(2).getImm();
7182   unsigned Align = MI->getOperand(3).getImm();
7183   DebugLoc dl = MI->getDebugLoc();
7184
7185   MachineFunction *MF = BB->getParent();
7186   MachineRegisterInfo &MRI = MF->getRegInfo();
7187   unsigned UnitSize = 0;
7188   const TargetRegisterClass *TRC = nullptr;
7189   const TargetRegisterClass *VecTRC = nullptr;
7190
7191   bool IsThumb1 = Subtarget->isThumb1Only();
7192   bool IsThumb2 = Subtarget->isThumb2();
7193
7194   if (Align & 1) {
7195     UnitSize = 1;
7196   } else if (Align & 2) {
7197     UnitSize = 2;
7198   } else {
7199     // Check whether we can use NEON instructions.
7200     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7201         Subtarget->hasNEON()) {
7202       if ((Align % 16 == 0) && SizeVal >= 16)
7203         UnitSize = 16;
7204       else if ((Align % 8 == 0) && SizeVal >= 8)
7205         UnitSize = 8;
7206     }
7207     // Can't use NEON instructions.
7208     if (UnitSize == 0)
7209       UnitSize = 4;
7210   }
7211
7212   // Select the correct opcode and register class for unit size load/store
7213   bool IsNeon = UnitSize >= 8;
7214   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7215   if (IsNeon)
7216     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7217                             : UnitSize == 8 ? &ARM::DPRRegClass
7218                                             : nullptr;
7219
7220   unsigned BytesLeft = SizeVal % UnitSize;
7221   unsigned LoopSize = SizeVal - BytesLeft;
7222
7223   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7224     // Use LDR and STR to copy.
7225     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7226     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7227     unsigned srcIn = src;
7228     unsigned destIn = dest;
7229     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7230       unsigned srcOut = MRI.createVirtualRegister(TRC);
7231       unsigned destOut = MRI.createVirtualRegister(TRC);
7232       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7233       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7234                  IsThumb1, IsThumb2);
7235       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7236                  IsThumb1, IsThumb2);
7237       srcIn = srcOut;
7238       destIn = destOut;
7239     }
7240
7241     // Handle the leftover bytes with LDRB and STRB.
7242     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7243     // [destOut] = STRB_POST(scratch, destIn, 1)
7244     for (unsigned i = 0; i < BytesLeft; i++) {
7245       unsigned srcOut = MRI.createVirtualRegister(TRC);
7246       unsigned destOut = MRI.createVirtualRegister(TRC);
7247       unsigned scratch = MRI.createVirtualRegister(TRC);
7248       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7249                  IsThumb1, IsThumb2);
7250       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7251                  IsThumb1, IsThumb2);
7252       srcIn = srcOut;
7253       destIn = destOut;
7254     }
7255     MI->eraseFromParent();   // The instruction is gone now.
7256     return BB;
7257   }
7258
7259   // Expand the pseudo op to a loop.
7260   // thisMBB:
7261   //   ...
7262   //   movw varEnd, # --> with thumb2
7263   //   movt varEnd, #
7264   //   ldrcp varEnd, idx --> without thumb2
7265   //   fallthrough --> loopMBB
7266   // loopMBB:
7267   //   PHI varPhi, varEnd, varLoop
7268   //   PHI srcPhi, src, srcLoop
7269   //   PHI destPhi, dst, destLoop
7270   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7271   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7272   //   subs varLoop, varPhi, #UnitSize
7273   //   bne loopMBB
7274   //   fallthrough --> exitMBB
7275   // exitMBB:
7276   //   epilogue to handle left-over bytes
7277   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7278   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7279   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7280   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7281   MF->insert(It, loopMBB);
7282   MF->insert(It, exitMBB);
7283
7284   // Transfer the remainder of BB and its successor edges to exitMBB.
7285   exitMBB->splice(exitMBB->begin(), BB,
7286                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7287   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7288
7289   // Load an immediate to varEnd.
7290   unsigned varEnd = MRI.createVirtualRegister(TRC);
7291   if (Subtarget->useMovt(*MF)) {
7292     unsigned Vtmp = varEnd;
7293     if ((LoopSize & 0xFFFF0000) != 0)
7294       Vtmp = MRI.createVirtualRegister(TRC);
7295     AddDefaultPred(BuildMI(BB, dl,
7296                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7297                            Vtmp).addImm(LoopSize & 0xFFFF));
7298
7299     if ((LoopSize & 0xFFFF0000) != 0)
7300       AddDefaultPred(BuildMI(BB, dl,
7301                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7302                              varEnd)
7303                          .addReg(Vtmp)
7304                          .addImm(LoopSize >> 16));
7305   } else {
7306     MachineConstantPool *ConstantPool = MF->getConstantPool();
7307     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7308     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7309
7310     // MachineConstantPool wants an explicit alignment.
7311     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7312     if (Align == 0)
7313       Align = getDataLayout()->getTypeAllocSize(C->getType());
7314     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7315
7316     if (IsThumb1)
7317       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7318           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7319     else
7320       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7321           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7322   }
7323   BB->addSuccessor(loopMBB);
7324
7325   // Generate the loop body:
7326   //   varPhi = PHI(varLoop, varEnd)
7327   //   srcPhi = PHI(srcLoop, src)
7328   //   destPhi = PHI(destLoop, dst)
7329   MachineBasicBlock *entryBB = BB;
7330   BB = loopMBB;
7331   unsigned varLoop = MRI.createVirtualRegister(TRC);
7332   unsigned varPhi = MRI.createVirtualRegister(TRC);
7333   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7334   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7335   unsigned destLoop = MRI.createVirtualRegister(TRC);
7336   unsigned destPhi = MRI.createVirtualRegister(TRC);
7337
7338   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7339     .addReg(varLoop).addMBB(loopMBB)
7340     .addReg(varEnd).addMBB(entryBB);
7341   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7342     .addReg(srcLoop).addMBB(loopMBB)
7343     .addReg(src).addMBB(entryBB);
7344   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7345     .addReg(destLoop).addMBB(loopMBB)
7346     .addReg(dest).addMBB(entryBB);
7347
7348   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7349   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7350   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7351   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7352              IsThumb1, IsThumb2);
7353   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7354              IsThumb1, IsThumb2);
7355
7356   // Decrement loop variable by UnitSize.
7357   if (IsThumb1) {
7358     MachineInstrBuilder MIB =
7359         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7360     MIB = AddDefaultT1CC(MIB);
7361     MIB.addReg(varPhi).addImm(UnitSize);
7362     AddDefaultPred(MIB);
7363   } else {
7364     MachineInstrBuilder MIB =
7365         BuildMI(*BB, BB->end(), dl,
7366                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7367     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7368     MIB->getOperand(5).setReg(ARM::CPSR);
7369     MIB->getOperand(5).setIsDef(true);
7370   }
7371   BuildMI(*BB, BB->end(), dl,
7372           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7373       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7374
7375   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7376   BB->addSuccessor(loopMBB);
7377   BB->addSuccessor(exitMBB);
7378
7379   // Add epilogue to handle BytesLeft.
7380   BB = exitMBB;
7381   MachineInstr *StartOfExit = exitMBB->begin();
7382
7383   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7384   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7385   unsigned srcIn = srcLoop;
7386   unsigned destIn = destLoop;
7387   for (unsigned i = 0; i < BytesLeft; i++) {
7388     unsigned srcOut = MRI.createVirtualRegister(TRC);
7389     unsigned destOut = MRI.createVirtualRegister(TRC);
7390     unsigned scratch = MRI.createVirtualRegister(TRC);
7391     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7392                IsThumb1, IsThumb2);
7393     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7394                IsThumb1, IsThumb2);
7395     srcIn = srcOut;
7396     destIn = destOut;
7397   }
7398
7399   MI->eraseFromParent();   // The instruction is gone now.
7400   return BB;
7401 }
7402
7403 MachineBasicBlock *
7404 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7405                                        MachineBasicBlock *MBB) const {
7406   const TargetMachine &TM = getTargetMachine();
7407   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7408   DebugLoc DL = MI->getDebugLoc();
7409
7410   assert(Subtarget->isTargetWindows() &&
7411          "__chkstk is only supported on Windows");
7412   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7413
7414   // __chkstk takes the number of words to allocate on the stack in R4, and
7415   // returns the stack adjustment in number of bytes in R4.  This will not
7416   // clober any other registers (other than the obvious lr).
7417   //
7418   // Although, technically, IP should be considered a register which may be
7419   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7420   // thumb-2 environment, so there is no interworking required.  As a result, we
7421   // do not expect a veneer to be emitted by the linker, clobbering IP.
7422   //
7423   // Each module receives its own copy of __chkstk, so no import thunk is
7424   // required, again, ensuring that IP is not clobbered.
7425   //
7426   // Finally, although some linkers may theoretically provide a trampoline for
7427   // out of range calls (which is quite common due to a 32M range limitation of
7428   // branches for Thumb), we can generate the long-call version via
7429   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7430   // IP.
7431
7432   switch (TM.getCodeModel()) {
7433   case CodeModel::Small:
7434   case CodeModel::Medium:
7435   case CodeModel::Default:
7436   case CodeModel::Kernel:
7437     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7438       .addImm((unsigned)ARMCC::AL).addReg(0)
7439       .addExternalSymbol("__chkstk")
7440       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7441       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7442       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7443     break;
7444   case CodeModel::Large:
7445   case CodeModel::JITDefault: {
7446     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7447     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7448
7449     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7450       .addExternalSymbol("__chkstk");
7451     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7452       .addImm((unsigned)ARMCC::AL).addReg(0)
7453       .addReg(Reg, RegState::Kill)
7454       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7455       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7456       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7457     break;
7458   }
7459   }
7460
7461   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7462                                       ARM::SP)
7463                               .addReg(ARM::SP).addReg(ARM::R4)));
7464
7465   MI->eraseFromParent();
7466   return MBB;
7467 }
7468
7469 MachineBasicBlock *
7470 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7471                                                MachineBasicBlock *BB) const {
7472   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7473   DebugLoc dl = MI->getDebugLoc();
7474   bool isThumb2 = Subtarget->isThumb2();
7475   switch (MI->getOpcode()) {
7476   default: {
7477     MI->dump();
7478     llvm_unreachable("Unexpected instr type to insert");
7479   }
7480   // The Thumb2 pre-indexed stores have the same MI operands, they just
7481   // define them differently in the .td files from the isel patterns, so
7482   // they need pseudos.
7483   case ARM::t2STR_preidx:
7484     MI->setDesc(TII->get(ARM::t2STR_PRE));
7485     return BB;
7486   case ARM::t2STRB_preidx:
7487     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7488     return BB;
7489   case ARM::t2STRH_preidx:
7490     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7491     return BB;
7492
7493   case ARM::STRi_preidx:
7494   case ARM::STRBi_preidx: {
7495     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7496       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7497     // Decode the offset.
7498     unsigned Offset = MI->getOperand(4).getImm();
7499     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7500     Offset = ARM_AM::getAM2Offset(Offset);
7501     if (isSub)
7502       Offset = -Offset;
7503
7504     MachineMemOperand *MMO = *MI->memoperands_begin();
7505     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7506       .addOperand(MI->getOperand(0))  // Rn_wb
7507       .addOperand(MI->getOperand(1))  // Rt
7508       .addOperand(MI->getOperand(2))  // Rn
7509       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7510       .addOperand(MI->getOperand(5))  // pred
7511       .addOperand(MI->getOperand(6))
7512       .addMemOperand(MMO);
7513     MI->eraseFromParent();
7514     return BB;
7515   }
7516   case ARM::STRr_preidx:
7517   case ARM::STRBr_preidx:
7518   case ARM::STRH_preidx: {
7519     unsigned NewOpc;
7520     switch (MI->getOpcode()) {
7521     default: llvm_unreachable("unexpected opcode!");
7522     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7523     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7524     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7525     }
7526     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7527     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7528       MIB.addOperand(MI->getOperand(i));
7529     MI->eraseFromParent();
7530     return BB;
7531   }
7532
7533   case ARM::tMOVCCr_pseudo: {
7534     // To "insert" a SELECT_CC instruction, we actually have to insert the
7535     // diamond control-flow pattern.  The incoming instruction knows the
7536     // destination vreg to set, the condition code register to branch on, the
7537     // true/false values to select between, and a branch opcode to use.
7538     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7539     MachineFunction::iterator It = BB;
7540     ++It;
7541
7542     //  thisMBB:
7543     //  ...
7544     //   TrueVal = ...
7545     //   cmpTY ccX, r1, r2
7546     //   bCC copy1MBB
7547     //   fallthrough --> copy0MBB
7548     MachineBasicBlock *thisMBB  = BB;
7549     MachineFunction *F = BB->getParent();
7550     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7551     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7552     F->insert(It, copy0MBB);
7553     F->insert(It, sinkMBB);
7554
7555     // Transfer the remainder of BB and its successor edges to sinkMBB.
7556     sinkMBB->splice(sinkMBB->begin(), BB,
7557                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7558     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7559
7560     BB->addSuccessor(copy0MBB);
7561     BB->addSuccessor(sinkMBB);
7562
7563     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7564       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7565
7566     //  copy0MBB:
7567     //   %FalseValue = ...
7568     //   # fallthrough to sinkMBB
7569     BB = copy0MBB;
7570
7571     // Update machine-CFG edges
7572     BB->addSuccessor(sinkMBB);
7573
7574     //  sinkMBB:
7575     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7576     //  ...
7577     BB = sinkMBB;
7578     BuildMI(*BB, BB->begin(), dl,
7579             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7580       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7581       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7582
7583     MI->eraseFromParent();   // The pseudo instruction is gone now.
7584     return BB;
7585   }
7586
7587   case ARM::BCCi64:
7588   case ARM::BCCZi64: {
7589     // If there is an unconditional branch to the other successor, remove it.
7590     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7591
7592     // Compare both parts that make up the double comparison separately for
7593     // equality.
7594     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7595
7596     unsigned LHS1 = MI->getOperand(1).getReg();
7597     unsigned LHS2 = MI->getOperand(2).getReg();
7598     if (RHSisZero) {
7599       AddDefaultPred(BuildMI(BB, dl,
7600                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7601                      .addReg(LHS1).addImm(0));
7602       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7603         .addReg(LHS2).addImm(0)
7604         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7605     } else {
7606       unsigned RHS1 = MI->getOperand(3).getReg();
7607       unsigned RHS2 = MI->getOperand(4).getReg();
7608       AddDefaultPred(BuildMI(BB, dl,
7609                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7610                      .addReg(LHS1).addReg(RHS1));
7611       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7612         .addReg(LHS2).addReg(RHS2)
7613         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7614     }
7615
7616     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7617     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7618     if (MI->getOperand(0).getImm() == ARMCC::NE)
7619       std::swap(destMBB, exitMBB);
7620
7621     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7622       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7623     if (isThumb2)
7624       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7625     else
7626       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7627
7628     MI->eraseFromParent();   // The pseudo instruction is gone now.
7629     return BB;
7630   }
7631
7632   case ARM::Int_eh_sjlj_setjmp:
7633   case ARM::Int_eh_sjlj_setjmp_nofp:
7634   case ARM::tInt_eh_sjlj_setjmp:
7635   case ARM::t2Int_eh_sjlj_setjmp:
7636   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7637     EmitSjLjDispatchBlock(MI, BB);
7638     return BB;
7639
7640   case ARM::ABS:
7641   case ARM::t2ABS: {
7642     // To insert an ABS instruction, we have to insert the
7643     // diamond control-flow pattern.  The incoming instruction knows the
7644     // source vreg to test against 0, the destination vreg to set,
7645     // the condition code register to branch on, the
7646     // true/false values to select between, and a branch opcode to use.
7647     // It transforms
7648     //     V1 = ABS V0
7649     // into
7650     //     V2 = MOVS V0
7651     //     BCC                      (branch to SinkBB if V0 >= 0)
7652     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7653     //     SinkBB: V1 = PHI(V2, V3)
7654     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7655     MachineFunction::iterator BBI = BB;
7656     ++BBI;
7657     MachineFunction *Fn = BB->getParent();
7658     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7659     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7660     Fn->insert(BBI, RSBBB);
7661     Fn->insert(BBI, SinkBB);
7662
7663     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7664     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7665     bool ABSSrcKIll = MI->getOperand(1).isKill();
7666     bool isThumb2 = Subtarget->isThumb2();
7667     MachineRegisterInfo &MRI = Fn->getRegInfo();
7668     // In Thumb mode S must not be specified if source register is the SP or
7669     // PC and if destination register is the SP, so restrict register class
7670     unsigned NewRsbDstReg =
7671       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7672
7673     // Transfer the remainder of BB and its successor edges to sinkMBB.
7674     SinkBB->splice(SinkBB->begin(), BB,
7675                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7676     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7677
7678     BB->addSuccessor(RSBBB);
7679     BB->addSuccessor(SinkBB);
7680
7681     // fall through to SinkMBB
7682     RSBBB->addSuccessor(SinkBB);
7683
7684     // insert a cmp at the end of BB
7685     AddDefaultPred(BuildMI(BB, dl,
7686                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7687                    .addReg(ABSSrcReg).addImm(0));
7688
7689     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7690     BuildMI(BB, dl,
7691       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7692       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7693
7694     // insert rsbri in RSBBB
7695     // Note: BCC and rsbri will be converted into predicated rsbmi
7696     // by if-conversion pass
7697     BuildMI(*RSBBB, RSBBB->begin(), dl,
7698       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7699       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7700       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7701
7702     // insert PHI in SinkBB,
7703     // reuse ABSDstReg to not change uses of ABS instruction
7704     BuildMI(*SinkBB, SinkBB->begin(), dl,
7705       TII->get(ARM::PHI), ABSDstReg)
7706       .addReg(NewRsbDstReg).addMBB(RSBBB)
7707       .addReg(ABSSrcReg).addMBB(BB);
7708
7709     // remove ABS instruction
7710     MI->eraseFromParent();
7711
7712     // return last added BB
7713     return SinkBB;
7714   }
7715   case ARM::COPY_STRUCT_BYVAL_I32:
7716     ++NumLoopByVals;
7717     return EmitStructByval(MI, BB);
7718   case ARM::WIN__CHKSTK:
7719     return EmitLowered__chkstk(MI, BB);
7720   }
7721 }
7722
7723 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7724                                                       SDNode *Node) const {
7725   const MCInstrDesc *MCID = &MI->getDesc();
7726   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7727   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7728   // operand is still set to noreg. If needed, set the optional operand's
7729   // register to CPSR, and remove the redundant implicit def.
7730   //
7731   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7732
7733   // Rename pseudo opcodes.
7734   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7735   if (NewOpc) {
7736     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7737     MCID = &TII->get(NewOpc);
7738
7739     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7740            "converted opcode should be the same except for cc_out");
7741
7742     MI->setDesc(*MCID);
7743
7744     // Add the optional cc_out operand
7745     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7746   }
7747   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7748
7749   // Any ARM instruction that sets the 's' bit should specify an optional
7750   // "cc_out" operand in the last operand position.
7751   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7752     assert(!NewOpc && "Optional cc_out operand required");
7753     return;
7754   }
7755   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7756   // since we already have an optional CPSR def.
7757   bool definesCPSR = false;
7758   bool deadCPSR = false;
7759   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7760        i != e; ++i) {
7761     const MachineOperand &MO = MI->getOperand(i);
7762     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7763       definesCPSR = true;
7764       if (MO.isDead())
7765         deadCPSR = true;
7766       MI->RemoveOperand(i);
7767       break;
7768     }
7769   }
7770   if (!definesCPSR) {
7771     assert(!NewOpc && "Optional cc_out operand required");
7772     return;
7773   }
7774   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7775   if (deadCPSR) {
7776     assert(!MI->getOperand(ccOutIdx).getReg() &&
7777            "expect uninitialized optional cc_out operand");
7778     return;
7779   }
7780
7781   // If this instruction was defined with an optional CPSR def and its dag node
7782   // had a live implicit CPSR def, then activate the optional CPSR def.
7783   MachineOperand &MO = MI->getOperand(ccOutIdx);
7784   MO.setReg(ARM::CPSR);
7785   MO.setIsDef(true);
7786 }
7787
7788 //===----------------------------------------------------------------------===//
7789 //                           ARM Optimization Hooks
7790 //===----------------------------------------------------------------------===//
7791
7792 // Helper function that checks if N is a null or all ones constant.
7793 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7794   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7795   if (!C)
7796     return false;
7797   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7798 }
7799
7800 // Return true if N is conditionally 0 or all ones.
7801 // Detects these expressions where cc is an i1 value:
7802 //
7803 //   (select cc 0, y)   [AllOnes=0]
7804 //   (select cc y, 0)   [AllOnes=0]
7805 //   (zext cc)          [AllOnes=0]
7806 //   (sext cc)          [AllOnes=0/1]
7807 //   (select cc -1, y)  [AllOnes=1]
7808 //   (select cc y, -1)  [AllOnes=1]
7809 //
7810 // Invert is set when N is the null/all ones constant when CC is false.
7811 // OtherOp is set to the alternative value of N.
7812 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7813                                        SDValue &CC, bool &Invert,
7814                                        SDValue &OtherOp,
7815                                        SelectionDAG &DAG) {
7816   switch (N->getOpcode()) {
7817   default: return false;
7818   case ISD::SELECT: {
7819     CC = N->getOperand(0);
7820     SDValue N1 = N->getOperand(1);
7821     SDValue N2 = N->getOperand(2);
7822     if (isZeroOrAllOnes(N1, AllOnes)) {
7823       Invert = false;
7824       OtherOp = N2;
7825       return true;
7826     }
7827     if (isZeroOrAllOnes(N2, AllOnes)) {
7828       Invert = true;
7829       OtherOp = N1;
7830       return true;
7831     }
7832     return false;
7833   }
7834   case ISD::ZERO_EXTEND:
7835     // (zext cc) can never be the all ones value.
7836     if (AllOnes)
7837       return false;
7838     // Fall through.
7839   case ISD::SIGN_EXTEND: {
7840     SDLoc dl(N);
7841     EVT VT = N->getValueType(0);
7842     CC = N->getOperand(0);
7843     if (CC.getValueType() != MVT::i1)
7844       return false;
7845     Invert = !AllOnes;
7846     if (AllOnes)
7847       // When looking for an AllOnes constant, N is an sext, and the 'other'
7848       // value is 0.
7849       OtherOp = DAG.getConstant(0, dl, VT);
7850     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7851       // When looking for a 0 constant, N can be zext or sext.
7852       OtherOp = DAG.getConstant(1, dl, VT);
7853     else
7854       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
7855                                 VT);
7856     return true;
7857   }
7858   }
7859 }
7860
7861 // Combine a constant select operand into its use:
7862 //
7863 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7864 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7865 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7866 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7867 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7868 //
7869 // The transform is rejected if the select doesn't have a constant operand that
7870 // is null, or all ones when AllOnes is set.
7871 //
7872 // Also recognize sext/zext from i1:
7873 //
7874 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7875 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7876 //
7877 // These transformations eventually create predicated instructions.
7878 //
7879 // @param N       The node to transform.
7880 // @param Slct    The N operand that is a select.
7881 // @param OtherOp The other N operand (x above).
7882 // @param DCI     Context.
7883 // @param AllOnes Require the select constant to be all ones instead of null.
7884 // @returns The new node, or SDValue() on failure.
7885 static
7886 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7887                             TargetLowering::DAGCombinerInfo &DCI,
7888                             bool AllOnes = false) {
7889   SelectionDAG &DAG = DCI.DAG;
7890   EVT VT = N->getValueType(0);
7891   SDValue NonConstantVal;
7892   SDValue CCOp;
7893   bool SwapSelectOps;
7894   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7895                                   NonConstantVal, DAG))
7896     return SDValue();
7897
7898   // Slct is now know to be the desired identity constant when CC is true.
7899   SDValue TrueVal = OtherOp;
7900   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7901                                  OtherOp, NonConstantVal);
7902   // Unless SwapSelectOps says CC should be false.
7903   if (SwapSelectOps)
7904     std::swap(TrueVal, FalseVal);
7905
7906   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7907                      CCOp, TrueVal, FalseVal);
7908 }
7909
7910 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7911 static
7912 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7913                                        TargetLowering::DAGCombinerInfo &DCI) {
7914   SDValue N0 = N->getOperand(0);
7915   SDValue N1 = N->getOperand(1);
7916   if (N0.getNode()->hasOneUse()) {
7917     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7918     if (Result.getNode())
7919       return Result;
7920   }
7921   if (N1.getNode()->hasOneUse()) {
7922     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7923     if (Result.getNode())
7924       return Result;
7925   }
7926   return SDValue();
7927 }
7928
7929 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7930 // (only after legalization).
7931 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7932                                  TargetLowering::DAGCombinerInfo &DCI,
7933                                  const ARMSubtarget *Subtarget) {
7934
7935   // Only perform optimization if after legalize, and if NEON is available. We
7936   // also expected both operands to be BUILD_VECTORs.
7937   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7938       || N0.getOpcode() != ISD::BUILD_VECTOR
7939       || N1.getOpcode() != ISD::BUILD_VECTOR)
7940     return SDValue();
7941
7942   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7943   EVT VT = N->getValueType(0);
7944   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7945     return SDValue();
7946
7947   // Check that the vector operands are of the right form.
7948   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7949   // operands, where N is the size of the formed vector.
7950   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7951   // index such that we have a pair wise add pattern.
7952
7953   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7954   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7955     return SDValue();
7956   SDValue Vec = N0->getOperand(0)->getOperand(0);
7957   SDNode *V = Vec.getNode();
7958   unsigned nextIndex = 0;
7959
7960   // For each operands to the ADD which are BUILD_VECTORs,
7961   // check to see if each of their operands are an EXTRACT_VECTOR with
7962   // the same vector and appropriate index.
7963   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7964     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7965         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7966
7967       SDValue ExtVec0 = N0->getOperand(i);
7968       SDValue ExtVec1 = N1->getOperand(i);
7969
7970       // First operand is the vector, verify its the same.
7971       if (V != ExtVec0->getOperand(0).getNode() ||
7972           V != ExtVec1->getOperand(0).getNode())
7973         return SDValue();
7974
7975       // Second is the constant, verify its correct.
7976       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7977       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7978
7979       // For the constant, we want to see all the even or all the odd.
7980       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7981           || C1->getZExtValue() != nextIndex+1)
7982         return SDValue();
7983
7984       // Increment index.
7985       nextIndex+=2;
7986     } else
7987       return SDValue();
7988   }
7989
7990   // Create VPADDL node.
7991   SelectionDAG &DAG = DCI.DAG;
7992   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7993
7994   SDLoc dl(N);
7995
7996   // Build operand list.
7997   SmallVector<SDValue, 8> Ops;
7998   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
7999                                 TLI.getPointerTy()));
8000
8001   // Input is the vector.
8002   Ops.push_back(Vec);
8003
8004   // Get widened type and narrowed type.
8005   MVT widenType;
8006   unsigned numElem = VT.getVectorNumElements();
8007   
8008   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8009   switch (inputLaneType.getSimpleVT().SimpleTy) {
8010     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8011     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8012     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8013     default:
8014       llvm_unreachable("Invalid vector element type for padd optimization.");
8015   }
8016
8017   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8018   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8019   return DAG.getNode(ExtOp, dl, VT, tmp);
8020 }
8021
8022 static SDValue findMUL_LOHI(SDValue V) {
8023   if (V->getOpcode() == ISD::UMUL_LOHI ||
8024       V->getOpcode() == ISD::SMUL_LOHI)
8025     return V;
8026   return SDValue();
8027 }
8028
8029 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8030                                      TargetLowering::DAGCombinerInfo &DCI,
8031                                      const ARMSubtarget *Subtarget) {
8032
8033   if (Subtarget->isThumb1Only()) return SDValue();
8034
8035   // Only perform the checks after legalize when the pattern is available.
8036   if (DCI.isBeforeLegalize()) return SDValue();
8037
8038   // Look for multiply add opportunities.
8039   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8040   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8041   // a glue link from the first add to the second add.
8042   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8043   // a S/UMLAL instruction.
8044   //                  UMUL_LOHI
8045   //                 / :lo    \ :hi
8046   //                /          \          [no multiline comment]
8047   //    loAdd ->  ADDE         |
8048   //                 \ :glue  /
8049   //                  \      /
8050   //                    ADDC   <- hiAdd
8051   //
8052   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8053   SDValue AddcOp0 = AddcNode->getOperand(0);
8054   SDValue AddcOp1 = AddcNode->getOperand(1);
8055
8056   // Check if the two operands are from the same mul_lohi node.
8057   if (AddcOp0.getNode() == AddcOp1.getNode())
8058     return SDValue();
8059
8060   assert(AddcNode->getNumValues() == 2 &&
8061          AddcNode->getValueType(0) == MVT::i32 &&
8062          "Expect ADDC with two result values. First: i32");
8063
8064   // Check that we have a glued ADDC node.
8065   if (AddcNode->getValueType(1) != MVT::Glue)
8066     return SDValue();
8067
8068   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8069   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8070       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8071       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8072       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8073     return SDValue();
8074
8075   // Look for the glued ADDE.
8076   SDNode* AddeNode = AddcNode->getGluedUser();
8077   if (!AddeNode)
8078     return SDValue();
8079
8080   // Make sure it is really an ADDE.
8081   if (AddeNode->getOpcode() != ISD::ADDE)
8082     return SDValue();
8083
8084   assert(AddeNode->getNumOperands() == 3 &&
8085          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8086          "ADDE node has the wrong inputs");
8087
8088   // Check for the triangle shape.
8089   SDValue AddeOp0 = AddeNode->getOperand(0);
8090   SDValue AddeOp1 = AddeNode->getOperand(1);
8091
8092   // Make sure that the ADDE operands are not coming from the same node.
8093   if (AddeOp0.getNode() == AddeOp1.getNode())
8094     return SDValue();
8095
8096   // Find the MUL_LOHI node walking up ADDE's operands.
8097   bool IsLeftOperandMUL = false;
8098   SDValue MULOp = findMUL_LOHI(AddeOp0);
8099   if (MULOp == SDValue())
8100    MULOp = findMUL_LOHI(AddeOp1);
8101   else
8102     IsLeftOperandMUL = true;
8103   if (MULOp == SDValue())
8104     return SDValue();
8105
8106   // Figure out the right opcode.
8107   unsigned Opc = MULOp->getOpcode();
8108   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8109
8110   // Figure out the high and low input values to the MLAL node.
8111   SDValue* HiAdd = nullptr;
8112   SDValue* LoMul = nullptr;
8113   SDValue* LowAdd = nullptr;
8114
8115   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8116   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8117     return SDValue();
8118
8119   if (IsLeftOperandMUL)
8120     HiAdd = &AddeOp1;
8121   else
8122     HiAdd = &AddeOp0;
8123
8124
8125   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8126   // whose low result is fed to the ADDC we are checking.
8127
8128   if (AddcOp0 == MULOp.getValue(0)) {
8129     LoMul = &AddcOp0;
8130     LowAdd = &AddcOp1;
8131   }
8132   if (AddcOp1 == MULOp.getValue(0)) {
8133     LoMul = &AddcOp1;
8134     LowAdd = &AddcOp0;
8135   }
8136
8137   if (!LoMul)
8138     return SDValue();
8139
8140   // Create the merged node.
8141   SelectionDAG &DAG = DCI.DAG;
8142
8143   // Build operand list.
8144   SmallVector<SDValue, 8> Ops;
8145   Ops.push_back(LoMul->getOperand(0));
8146   Ops.push_back(LoMul->getOperand(1));
8147   Ops.push_back(*LowAdd);
8148   Ops.push_back(*HiAdd);
8149
8150   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8151                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8152
8153   // Replace the ADDs' nodes uses by the MLA node's values.
8154   SDValue HiMLALResult(MLALNode.getNode(), 1);
8155   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8156
8157   SDValue LoMLALResult(MLALNode.getNode(), 0);
8158   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8159
8160   // Return original node to notify the driver to stop replacing.
8161   SDValue resNode(AddcNode, 0);
8162   return resNode;
8163 }
8164
8165 /// PerformADDCCombine - Target-specific dag combine transform from
8166 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8167 static SDValue PerformADDCCombine(SDNode *N,
8168                                  TargetLowering::DAGCombinerInfo &DCI,
8169                                  const ARMSubtarget *Subtarget) {
8170
8171   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8172
8173 }
8174
8175 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8176 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8177 /// called with the default operands, and if that fails, with commuted
8178 /// operands.
8179 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8180                                           TargetLowering::DAGCombinerInfo &DCI,
8181                                           const ARMSubtarget *Subtarget){
8182
8183   // Attempt to create vpaddl for this add.
8184   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8185   if (Result.getNode())
8186     return Result;
8187
8188   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8189   if (N0.getNode()->hasOneUse()) {
8190     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8191     if (Result.getNode()) return Result;
8192   }
8193   return SDValue();
8194 }
8195
8196 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8197 ///
8198 static SDValue PerformADDCombine(SDNode *N,
8199                                  TargetLowering::DAGCombinerInfo &DCI,
8200                                  const ARMSubtarget *Subtarget) {
8201   SDValue N0 = N->getOperand(0);
8202   SDValue N1 = N->getOperand(1);
8203
8204   // First try with the default operand order.
8205   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8206   if (Result.getNode())
8207     return Result;
8208
8209   // If that didn't work, try again with the operands commuted.
8210   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8211 }
8212
8213 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8214 ///
8215 static SDValue PerformSUBCombine(SDNode *N,
8216                                  TargetLowering::DAGCombinerInfo &DCI) {
8217   SDValue N0 = N->getOperand(0);
8218   SDValue N1 = N->getOperand(1);
8219
8220   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8221   if (N1.getNode()->hasOneUse()) {
8222     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8223     if (Result.getNode()) return Result;
8224   }
8225
8226   return SDValue();
8227 }
8228
8229 /// PerformVMULCombine
8230 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8231 /// special multiplier accumulator forwarding.
8232 ///   vmul d3, d0, d2
8233 ///   vmla d3, d1, d2
8234 /// is faster than
8235 ///   vadd d3, d0, d1
8236 ///   vmul d3, d3, d2
8237 //  However, for (A + B) * (A + B),
8238 //    vadd d2, d0, d1
8239 //    vmul d3, d0, d2
8240 //    vmla d3, d1, d2
8241 //  is slower than
8242 //    vadd d2, d0, d1
8243 //    vmul d3, d2, d2
8244 static SDValue PerformVMULCombine(SDNode *N,
8245                                   TargetLowering::DAGCombinerInfo &DCI,
8246                                   const ARMSubtarget *Subtarget) {
8247   if (!Subtarget->hasVMLxForwarding())
8248     return SDValue();
8249
8250   SelectionDAG &DAG = DCI.DAG;
8251   SDValue N0 = N->getOperand(0);
8252   SDValue N1 = N->getOperand(1);
8253   unsigned Opcode = N0.getOpcode();
8254   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8255       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8256     Opcode = N1.getOpcode();
8257     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8258         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8259       return SDValue();
8260     std::swap(N0, N1);
8261   }
8262
8263   if (N0 == N1)
8264     return SDValue();
8265
8266   EVT VT = N->getValueType(0);
8267   SDLoc DL(N);
8268   SDValue N00 = N0->getOperand(0);
8269   SDValue N01 = N0->getOperand(1);
8270   return DAG.getNode(Opcode, DL, VT,
8271                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8272                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8273 }
8274
8275 static SDValue PerformMULCombine(SDNode *N,
8276                                  TargetLowering::DAGCombinerInfo &DCI,
8277                                  const ARMSubtarget *Subtarget) {
8278   SelectionDAG &DAG = DCI.DAG;
8279
8280   if (Subtarget->isThumb1Only())
8281     return SDValue();
8282
8283   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8284     return SDValue();
8285
8286   EVT VT = N->getValueType(0);
8287   if (VT.is64BitVector() || VT.is128BitVector())
8288     return PerformVMULCombine(N, DCI, Subtarget);
8289   if (VT != MVT::i32)
8290     return SDValue();
8291
8292   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8293   if (!C)
8294     return SDValue();
8295
8296   int64_t MulAmt = C->getSExtValue();
8297   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8298
8299   ShiftAmt = ShiftAmt & (32 - 1);
8300   SDValue V = N->getOperand(0);
8301   SDLoc DL(N);
8302
8303   SDValue Res;
8304   MulAmt >>= ShiftAmt;
8305
8306   if (MulAmt >= 0) {
8307     if (isPowerOf2_32(MulAmt - 1)) {
8308       // (mul x, 2^N + 1) => (add (shl x, N), x)
8309       Res = DAG.getNode(ISD::ADD, DL, VT,
8310                         V,
8311                         DAG.getNode(ISD::SHL, DL, VT,
8312                                     V,
8313                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8314                                                     MVT::i32)));
8315     } else if (isPowerOf2_32(MulAmt + 1)) {
8316       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8317       Res = DAG.getNode(ISD::SUB, DL, VT,
8318                         DAG.getNode(ISD::SHL, DL, VT,
8319                                     V,
8320                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8321                                                     MVT::i32)),
8322                         V);
8323     } else
8324       return SDValue();
8325   } else {
8326     uint64_t MulAmtAbs = -MulAmt;
8327     if (isPowerOf2_32(MulAmtAbs + 1)) {
8328       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8329       Res = DAG.getNode(ISD::SUB, DL, VT,
8330                         V,
8331                         DAG.getNode(ISD::SHL, DL, VT,
8332                                     V,
8333                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8334                                                     MVT::i32)));
8335     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8336       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8337       Res = DAG.getNode(ISD::ADD, DL, VT,
8338                         V,
8339                         DAG.getNode(ISD::SHL, DL, VT,
8340                                     V,
8341                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8342                                                     MVT::i32)));
8343       Res = DAG.getNode(ISD::SUB, DL, VT,
8344                         DAG.getConstant(0, DL, MVT::i32), Res);
8345
8346     } else
8347       return SDValue();
8348   }
8349
8350   if (ShiftAmt != 0)
8351     Res = DAG.getNode(ISD::SHL, DL, VT,
8352                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8353
8354   // Do not add new nodes to DAG combiner worklist.
8355   DCI.CombineTo(N, Res, false);
8356   return SDValue();
8357 }
8358
8359 static SDValue PerformANDCombine(SDNode *N,
8360                                  TargetLowering::DAGCombinerInfo &DCI,
8361                                  const ARMSubtarget *Subtarget) {
8362
8363   // Attempt to use immediate-form VBIC
8364   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8365   SDLoc dl(N);
8366   EVT VT = N->getValueType(0);
8367   SelectionDAG &DAG = DCI.DAG;
8368
8369   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8370     return SDValue();
8371
8372   APInt SplatBits, SplatUndef;
8373   unsigned SplatBitSize;
8374   bool HasAnyUndefs;
8375   if (BVN &&
8376       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8377     if (SplatBitSize <= 64) {
8378       EVT VbicVT;
8379       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8380                                       SplatUndef.getZExtValue(), SplatBitSize,
8381                                       DAG, dl, VbicVT, VT.is128BitVector(),
8382                                       OtherModImm);
8383       if (Val.getNode()) {
8384         SDValue Input =
8385           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8386         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8387         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8388       }
8389     }
8390   }
8391
8392   if (!Subtarget->isThumb1Only()) {
8393     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8394     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8395     if (Result.getNode())
8396       return Result;
8397   }
8398
8399   return SDValue();
8400 }
8401
8402 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8403 static SDValue PerformORCombine(SDNode *N,
8404                                 TargetLowering::DAGCombinerInfo &DCI,
8405                                 const ARMSubtarget *Subtarget) {
8406   // Attempt to use immediate-form VORR
8407   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8408   SDLoc dl(N);
8409   EVT VT = N->getValueType(0);
8410   SelectionDAG &DAG = DCI.DAG;
8411
8412   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8413     return SDValue();
8414
8415   APInt SplatBits, SplatUndef;
8416   unsigned SplatBitSize;
8417   bool HasAnyUndefs;
8418   if (BVN && Subtarget->hasNEON() &&
8419       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8420     if (SplatBitSize <= 64) {
8421       EVT VorrVT;
8422       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8423                                       SplatUndef.getZExtValue(), SplatBitSize,
8424                                       DAG, dl, VorrVT, VT.is128BitVector(),
8425                                       OtherModImm);
8426       if (Val.getNode()) {
8427         SDValue Input =
8428           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8429         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8430         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8431       }
8432     }
8433   }
8434
8435   if (!Subtarget->isThumb1Only()) {
8436     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8437     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8438     if (Result.getNode())
8439       return Result;
8440   }
8441
8442   // The code below optimizes (or (and X, Y), Z).
8443   // The AND operand needs to have a single user to make these optimizations
8444   // profitable.
8445   SDValue N0 = N->getOperand(0);
8446   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8447     return SDValue();
8448   SDValue N1 = N->getOperand(1);
8449
8450   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8451   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8452       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8453     APInt SplatUndef;
8454     unsigned SplatBitSize;
8455     bool HasAnyUndefs;
8456
8457     APInt SplatBits0, SplatBits1;
8458     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8459     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8460     // Ensure that the second operand of both ands are constants
8461     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8462                                       HasAnyUndefs) && !HasAnyUndefs) {
8463         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8464                                           HasAnyUndefs) && !HasAnyUndefs) {
8465             // Ensure that the bit width of the constants are the same and that
8466             // the splat arguments are logical inverses as per the pattern we
8467             // are trying to simplify.
8468             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8469                 SplatBits0 == ~SplatBits1) {
8470                 // Canonicalize the vector type to make instruction selection
8471                 // simpler.
8472                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8473                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8474                                              N0->getOperand(1),
8475                                              N0->getOperand(0),
8476                                              N1->getOperand(0));
8477                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8478             }
8479         }
8480     }
8481   }
8482
8483   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8484   // reasonable.
8485
8486   // BFI is only available on V6T2+
8487   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8488     return SDValue();
8489
8490   SDLoc DL(N);
8491   // 1) or (and A, mask), val => ARMbfi A, val, mask
8492   //      iff (val & mask) == val
8493   //
8494   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8495   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8496   //          && mask == ~mask2
8497   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8498   //          && ~mask == mask2
8499   //  (i.e., copy a bitfield value into another bitfield of the same width)
8500
8501   if (VT != MVT::i32)
8502     return SDValue();
8503
8504   SDValue N00 = N0.getOperand(0);
8505
8506   // The value and the mask need to be constants so we can verify this is
8507   // actually a bitfield set. If the mask is 0xffff, we can do better
8508   // via a movt instruction, so don't use BFI in that case.
8509   SDValue MaskOp = N0.getOperand(1);
8510   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8511   if (!MaskC)
8512     return SDValue();
8513   unsigned Mask = MaskC->getZExtValue();
8514   if (Mask == 0xffff)
8515     return SDValue();
8516   SDValue Res;
8517   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8518   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8519   if (N1C) {
8520     unsigned Val = N1C->getZExtValue();
8521     if ((Val & ~Mask) != Val)
8522       return SDValue();
8523
8524     if (ARM::isBitFieldInvertedMask(Mask)) {
8525       Val >>= countTrailingZeros(~Mask);
8526
8527       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8528                         DAG.getConstant(Val, DL, MVT::i32),
8529                         DAG.getConstant(Mask, DL, MVT::i32));
8530
8531       // Do not add new nodes to DAG combiner worklist.
8532       DCI.CombineTo(N, Res, false);
8533       return SDValue();
8534     }
8535   } else if (N1.getOpcode() == ISD::AND) {
8536     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8537     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8538     if (!N11C)
8539       return SDValue();
8540     unsigned Mask2 = N11C->getZExtValue();
8541
8542     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8543     // as is to match.
8544     if (ARM::isBitFieldInvertedMask(Mask) &&
8545         (Mask == ~Mask2)) {
8546       // The pack halfword instruction works better for masks that fit it,
8547       // so use that when it's available.
8548       if (Subtarget->hasT2ExtractPack() &&
8549           (Mask == 0xffff || Mask == 0xffff0000))
8550         return SDValue();
8551       // 2a
8552       unsigned amt = countTrailingZeros(Mask2);
8553       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8554                         DAG.getConstant(amt, DL, MVT::i32));
8555       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8556                         DAG.getConstant(Mask, DL, MVT::i32));
8557       // Do not add new nodes to DAG combiner worklist.
8558       DCI.CombineTo(N, Res, false);
8559       return SDValue();
8560     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8561                (~Mask == Mask2)) {
8562       // The pack halfword instruction works better for masks that fit it,
8563       // so use that when it's available.
8564       if (Subtarget->hasT2ExtractPack() &&
8565           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8566         return SDValue();
8567       // 2b
8568       unsigned lsb = countTrailingZeros(Mask);
8569       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8570                         DAG.getConstant(lsb, DL, MVT::i32));
8571       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8572                         DAG.getConstant(Mask2, DL, MVT::i32));
8573       // Do not add new nodes to DAG combiner worklist.
8574       DCI.CombineTo(N, Res, false);
8575       return SDValue();
8576     }
8577   }
8578
8579   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8580       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8581       ARM::isBitFieldInvertedMask(~Mask)) {
8582     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8583     // where lsb(mask) == #shamt and masked bits of B are known zero.
8584     SDValue ShAmt = N00.getOperand(1);
8585     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8586     unsigned LSB = countTrailingZeros(Mask);
8587     if (ShAmtC != LSB)
8588       return SDValue();
8589
8590     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8591                       DAG.getConstant(~Mask, DL, MVT::i32));
8592
8593     // Do not add new nodes to DAG combiner worklist.
8594     DCI.CombineTo(N, Res, false);
8595   }
8596
8597   return SDValue();
8598 }
8599
8600 static SDValue PerformXORCombine(SDNode *N,
8601                                  TargetLowering::DAGCombinerInfo &DCI,
8602                                  const ARMSubtarget *Subtarget) {
8603   EVT VT = N->getValueType(0);
8604   SelectionDAG &DAG = DCI.DAG;
8605
8606   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8607     return SDValue();
8608
8609   if (!Subtarget->isThumb1Only()) {
8610     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8611     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8612     if (Result.getNode())
8613       return Result;
8614   }
8615
8616   return SDValue();
8617 }
8618
8619 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8620 /// the bits being cleared by the AND are not demanded by the BFI.
8621 static SDValue PerformBFICombine(SDNode *N,
8622                                  TargetLowering::DAGCombinerInfo &DCI) {
8623   SDValue N1 = N->getOperand(1);
8624   if (N1.getOpcode() == ISD::AND) {
8625     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8626     if (!N11C)
8627       return SDValue();
8628     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8629     unsigned LSB = countTrailingZeros(~InvMask);
8630     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8631     assert(Width <
8632                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8633            "undefined behavior");
8634     unsigned Mask = (1u << Width) - 1;
8635     unsigned Mask2 = N11C->getZExtValue();
8636     if ((Mask & (~Mask2)) == 0)
8637       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8638                              N->getOperand(0), N1.getOperand(0),
8639                              N->getOperand(2));
8640   }
8641   return SDValue();
8642 }
8643
8644 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8645 /// ARMISD::VMOVRRD.
8646 static SDValue PerformVMOVRRDCombine(SDNode *N,
8647                                      TargetLowering::DAGCombinerInfo &DCI,
8648                                      const ARMSubtarget *Subtarget) {
8649   // vmovrrd(vmovdrr x, y) -> x,y
8650   SDValue InDouble = N->getOperand(0);
8651   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8652     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8653
8654   // vmovrrd(load f64) -> (load i32), (load i32)
8655   SDNode *InNode = InDouble.getNode();
8656   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8657       InNode->getValueType(0) == MVT::f64 &&
8658       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8659       !cast<LoadSDNode>(InNode)->isVolatile()) {
8660     // TODO: Should this be done for non-FrameIndex operands?
8661     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8662
8663     SelectionDAG &DAG = DCI.DAG;
8664     SDLoc DL(LD);
8665     SDValue BasePtr = LD->getBasePtr();
8666     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8667                                  LD->getPointerInfo(), LD->isVolatile(),
8668                                  LD->isNonTemporal(), LD->isInvariant(),
8669                                  LD->getAlignment());
8670
8671     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8672                                     DAG.getConstant(4, DL, MVT::i32));
8673     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8674                                  LD->getPointerInfo(), LD->isVolatile(),
8675                                  LD->isNonTemporal(), LD->isInvariant(),
8676                                  std::min(4U, LD->getAlignment() / 2));
8677
8678     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8679     if (DCI.DAG.getDataLayout().isBigEndian())
8680       std::swap (NewLD1, NewLD2);
8681     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8682     return Result;
8683   }
8684
8685   return SDValue();
8686 }
8687
8688 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8689 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8690 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8691   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8692   SDValue Op0 = N->getOperand(0);
8693   SDValue Op1 = N->getOperand(1);
8694   if (Op0.getOpcode() == ISD::BITCAST)
8695     Op0 = Op0.getOperand(0);
8696   if (Op1.getOpcode() == ISD::BITCAST)
8697     Op1 = Op1.getOperand(0);
8698   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8699       Op0.getNode() == Op1.getNode() &&
8700       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8701     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8702                        N->getValueType(0), Op0.getOperand(0));
8703   return SDValue();
8704 }
8705
8706 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8707 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8708 /// i64 vector to have f64 elements, since the value can then be loaded
8709 /// directly into a VFP register.
8710 static bool hasNormalLoadOperand(SDNode *N) {
8711   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8712   for (unsigned i = 0; i < NumElts; ++i) {
8713     SDNode *Elt = N->getOperand(i).getNode();
8714     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8715       return true;
8716   }
8717   return false;
8718 }
8719
8720 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8721 /// ISD::BUILD_VECTOR.
8722 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8723                                           TargetLowering::DAGCombinerInfo &DCI,
8724                                           const ARMSubtarget *Subtarget) {
8725   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8726   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8727   // into a pair of GPRs, which is fine when the value is used as a scalar,
8728   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8729   SelectionDAG &DAG = DCI.DAG;
8730   if (N->getNumOperands() == 2) {
8731     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8732     if (RV.getNode())
8733       return RV;
8734   }
8735
8736   // Load i64 elements as f64 values so that type legalization does not split
8737   // them up into i32 values.
8738   EVT VT = N->getValueType(0);
8739   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8740     return SDValue();
8741   SDLoc dl(N);
8742   SmallVector<SDValue, 8> Ops;
8743   unsigned NumElts = VT.getVectorNumElements();
8744   for (unsigned i = 0; i < NumElts; ++i) {
8745     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8746     Ops.push_back(V);
8747     // Make the DAGCombiner fold the bitcast.
8748     DCI.AddToWorklist(V.getNode());
8749   }
8750   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8751   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8752   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8753 }
8754
8755 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8756 static SDValue
8757 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8758   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8759   // At that time, we may have inserted bitcasts from integer to float.
8760   // If these bitcasts have survived DAGCombine, change the lowering of this
8761   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8762   // force to use floating point types.
8763
8764   // Make sure we can change the type of the vector.
8765   // This is possible iff:
8766   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8767   //    1.1. Vector is used only once.
8768   //    1.2. Use is a bit convert to an integer type.
8769   // 2. The size of its operands are 32-bits (64-bits are not legal).
8770   EVT VT = N->getValueType(0);
8771   EVT EltVT = VT.getVectorElementType();
8772
8773   // Check 1.1. and 2.
8774   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8775     return SDValue();
8776
8777   // By construction, the input type must be float.
8778   assert(EltVT == MVT::f32 && "Unexpected type!");
8779
8780   // Check 1.2.
8781   SDNode *Use = *N->use_begin();
8782   if (Use->getOpcode() != ISD::BITCAST ||
8783       Use->getValueType(0).isFloatingPoint())
8784     return SDValue();
8785
8786   // Check profitability.
8787   // Model is, if more than half of the relevant operands are bitcast from
8788   // i32, turn the build_vector into a sequence of insert_vector_elt.
8789   // Relevant operands are everything that is not statically
8790   // (i.e., at compile time) bitcasted.
8791   unsigned NumOfBitCastedElts = 0;
8792   unsigned NumElts = VT.getVectorNumElements();
8793   unsigned NumOfRelevantElts = NumElts;
8794   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8795     SDValue Elt = N->getOperand(Idx);
8796     if (Elt->getOpcode() == ISD::BITCAST) {
8797       // Assume only bit cast to i32 will go away.
8798       if (Elt->getOperand(0).getValueType() == MVT::i32)
8799         ++NumOfBitCastedElts;
8800     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8801       // Constants are statically casted, thus do not count them as
8802       // relevant operands.
8803       --NumOfRelevantElts;
8804   }
8805
8806   // Check if more than half of the elements require a non-free bitcast.
8807   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8808     return SDValue();
8809
8810   SelectionDAG &DAG = DCI.DAG;
8811   // Create the new vector type.
8812   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8813   // Check if the type is legal.
8814   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8815   if (!TLI.isTypeLegal(VecVT))
8816     return SDValue();
8817
8818   // Combine:
8819   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8820   // => BITCAST INSERT_VECTOR_ELT
8821   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8822   //                      (BITCAST EN), N.
8823   SDValue Vec = DAG.getUNDEF(VecVT);
8824   SDLoc dl(N);
8825   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8826     SDValue V = N->getOperand(Idx);
8827     if (V.getOpcode() == ISD::UNDEF)
8828       continue;
8829     if (V.getOpcode() == ISD::BITCAST &&
8830         V->getOperand(0).getValueType() == MVT::i32)
8831       // Fold obvious case.
8832       V = V.getOperand(0);
8833     else {
8834       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8835       // Make the DAGCombiner fold the bitcasts.
8836       DCI.AddToWorklist(V.getNode());
8837     }
8838     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
8839     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8840   }
8841   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8842   // Make the DAGCombiner fold the bitcasts.
8843   DCI.AddToWorklist(Vec.getNode());
8844   return Vec;
8845 }
8846
8847 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8848 /// ISD::INSERT_VECTOR_ELT.
8849 static SDValue PerformInsertEltCombine(SDNode *N,
8850                                        TargetLowering::DAGCombinerInfo &DCI) {
8851   // Bitcast an i64 load inserted into a vector to f64.
8852   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8853   EVT VT = N->getValueType(0);
8854   SDNode *Elt = N->getOperand(1).getNode();
8855   if (VT.getVectorElementType() != MVT::i64 ||
8856       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8857     return SDValue();
8858
8859   SelectionDAG &DAG = DCI.DAG;
8860   SDLoc dl(N);
8861   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8862                                  VT.getVectorNumElements());
8863   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8864   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8865   // Make the DAGCombiner fold the bitcasts.
8866   DCI.AddToWorklist(Vec.getNode());
8867   DCI.AddToWorklist(V.getNode());
8868   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8869                                Vec, V, N->getOperand(2));
8870   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8871 }
8872
8873 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8874 /// ISD::VECTOR_SHUFFLE.
8875 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8876   // The LLVM shufflevector instruction does not require the shuffle mask
8877   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8878   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8879   // operands do not match the mask length, they are extended by concatenating
8880   // them with undef vectors.  That is probably the right thing for other
8881   // targets, but for NEON it is better to concatenate two double-register
8882   // size vector operands into a single quad-register size vector.  Do that
8883   // transformation here:
8884   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8885   //   shuffle(concat(v1, v2), undef)
8886   SDValue Op0 = N->getOperand(0);
8887   SDValue Op1 = N->getOperand(1);
8888   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8889       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8890       Op0.getNumOperands() != 2 ||
8891       Op1.getNumOperands() != 2)
8892     return SDValue();
8893   SDValue Concat0Op1 = Op0.getOperand(1);
8894   SDValue Concat1Op1 = Op1.getOperand(1);
8895   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8896       Concat1Op1.getOpcode() != ISD::UNDEF)
8897     return SDValue();
8898   // Skip the transformation if any of the types are illegal.
8899   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8900   EVT VT = N->getValueType(0);
8901   if (!TLI.isTypeLegal(VT) ||
8902       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8903       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8904     return SDValue();
8905
8906   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8907                                   Op0.getOperand(0), Op1.getOperand(0));
8908   // Translate the shuffle mask.
8909   SmallVector<int, 16> NewMask;
8910   unsigned NumElts = VT.getVectorNumElements();
8911   unsigned HalfElts = NumElts/2;
8912   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8913   for (unsigned n = 0; n < NumElts; ++n) {
8914     int MaskElt = SVN->getMaskElt(n);
8915     int NewElt = -1;
8916     if (MaskElt < (int)HalfElts)
8917       NewElt = MaskElt;
8918     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8919       NewElt = HalfElts + MaskElt - NumElts;
8920     NewMask.push_back(NewElt);
8921   }
8922   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8923                               DAG.getUNDEF(VT), NewMask.data());
8924 }
8925
8926 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8927 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8928 /// base address updates.
8929 /// For generic load/stores, the memory type is assumed to be a vector.
8930 /// The caller is assumed to have checked legality.
8931 static SDValue CombineBaseUpdate(SDNode *N,
8932                                  TargetLowering::DAGCombinerInfo &DCI) {
8933   SelectionDAG &DAG = DCI.DAG;
8934   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8935                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8936   const bool isStore = N->getOpcode() == ISD::STORE;
8937   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8938   SDValue Addr = N->getOperand(AddrOpIdx);
8939   MemSDNode *MemN = cast<MemSDNode>(N);
8940   SDLoc dl(N);
8941
8942   // Search for a use of the address operand that is an increment.
8943   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8944          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8945     SDNode *User = *UI;
8946     if (User->getOpcode() != ISD::ADD ||
8947         UI.getUse().getResNo() != Addr.getResNo())
8948       continue;
8949
8950     // Check that the add is independent of the load/store.  Otherwise, folding
8951     // it would create a cycle.
8952     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8953       continue;
8954
8955     // Find the new opcode for the updating load/store.
8956     bool isLoadOp = true;
8957     bool isLaneOp = false;
8958     unsigned NewOpc = 0;
8959     unsigned NumVecs = 0;
8960     if (isIntrinsic) {
8961       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8962       switch (IntNo) {
8963       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8964       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8965         NumVecs = 1; break;
8966       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8967         NumVecs = 2; break;
8968       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8969         NumVecs = 3; break;
8970       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8971         NumVecs = 4; break;
8972       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8973         NumVecs = 2; isLaneOp = true; break;
8974       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8975         NumVecs = 3; isLaneOp = true; break;
8976       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8977         NumVecs = 4; isLaneOp = true; break;
8978       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8979         NumVecs = 1; isLoadOp = false; break;
8980       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8981         NumVecs = 2; isLoadOp = false; break;
8982       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8983         NumVecs = 3; isLoadOp = false; break;
8984       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8985         NumVecs = 4; isLoadOp = false; break;
8986       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8987         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8988       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8989         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8990       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8991         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8992       }
8993     } else {
8994       isLaneOp = true;
8995       switch (N->getOpcode()) {
8996       default: llvm_unreachable("unexpected opcode for Neon base update");
8997       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8998       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8999       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9000       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9001         NumVecs = 1; isLaneOp = false; break;
9002       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9003         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9004       }
9005     }
9006
9007     // Find the size of memory referenced by the load/store.
9008     EVT VecTy;
9009     if (isLoadOp) {
9010       VecTy = N->getValueType(0);
9011     } else if (isIntrinsic) {
9012       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9013     } else {
9014       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9015       VecTy = N->getOperand(1).getValueType();
9016     }
9017
9018     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9019     if (isLaneOp)
9020       NumBytes /= VecTy.getVectorNumElements();
9021
9022     // If the increment is a constant, it must match the memory ref size.
9023     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9024     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9025       uint64_t IncVal = CInc->getZExtValue();
9026       if (IncVal != NumBytes)
9027         continue;
9028     } else if (NumBytes >= 3 * 16) {
9029       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9030       // separate instructions that make it harder to use a non-constant update.
9031       continue;
9032     }
9033
9034     // OK, we found an ADD we can fold into the base update.
9035     // Now, create a _UPD node, taking care of not breaking alignment.
9036
9037     EVT AlignedVecTy = VecTy;
9038     unsigned Alignment = MemN->getAlignment();
9039
9040     // If this is a less-than-standard-aligned load/store, change the type to
9041     // match the standard alignment.
9042     // The alignment is overlooked when selecting _UPD variants; and it's
9043     // easier to introduce bitcasts here than fix that.
9044     // There are 3 ways to get to this base-update combine:
9045     // - intrinsics: they are assumed to be properly aligned (to the standard
9046     //   alignment of the memory type), so we don't need to do anything.
9047     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9048     //   intrinsics, so, likewise, there's nothing to do.
9049     // - generic load/store instructions: the alignment is specified as an
9050     //   explicit operand, rather than implicitly as the standard alignment
9051     //   of the memory type (like the intrisics).  We need to change the
9052     //   memory type to match the explicit alignment.  That way, we don't
9053     //   generate non-standard-aligned ARMISD::VLDx nodes.
9054     if (isa<LSBaseSDNode>(N)) {
9055       if (Alignment == 0)
9056         Alignment = 1;
9057       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9058         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9059         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9060         assert(!isLaneOp && "Unexpected generic load/store lane.");
9061         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9062         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9063       }
9064       // Don't set an explicit alignment on regular load/stores that we want
9065       // to transform to VLD/VST 1_UPD nodes.
9066       // This matches the behavior of regular load/stores, which only get an
9067       // explicit alignment if the MMO alignment is larger than the standard
9068       // alignment of the memory type.
9069       // Intrinsics, however, always get an explicit alignment, set to the
9070       // alignment of the MMO.
9071       Alignment = 1;
9072     }
9073
9074     // Create the new updating load/store node.
9075     // First, create an SDVTList for the new updating node's results.
9076     EVT Tys[6];
9077     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9078     unsigned n;
9079     for (n = 0; n < NumResultVecs; ++n)
9080       Tys[n] = AlignedVecTy;
9081     Tys[n++] = MVT::i32;
9082     Tys[n] = MVT::Other;
9083     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9084
9085     // Then, gather the new node's operands.
9086     SmallVector<SDValue, 8> Ops;
9087     Ops.push_back(N->getOperand(0)); // incoming chain
9088     Ops.push_back(N->getOperand(AddrOpIdx));
9089     Ops.push_back(Inc);
9090
9091     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9092       // Try to match the intrinsic's signature
9093       Ops.push_back(StN->getValue());
9094     } else {
9095       // Loads (and of course intrinsics) match the intrinsics' signature,
9096       // so just add all but the alignment operand.
9097       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9098         Ops.push_back(N->getOperand(i));
9099     }
9100
9101     // For all node types, the alignment operand is always the last one.
9102     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9103
9104     // If this is a non-standard-aligned STORE, the penultimate operand is the
9105     // stored value.  Bitcast it to the aligned type.
9106     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9107       SDValue &StVal = Ops[Ops.size()-2];
9108       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9109     }
9110
9111     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9112                                            Ops, AlignedVecTy,
9113                                            MemN->getMemOperand());
9114
9115     // Update the uses.
9116     SmallVector<SDValue, 5> NewResults;
9117     for (unsigned i = 0; i < NumResultVecs; ++i)
9118       NewResults.push_back(SDValue(UpdN.getNode(), i));
9119
9120     // If this is an non-standard-aligned LOAD, the first result is the loaded
9121     // value.  Bitcast it to the expected result type.
9122     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9123       SDValue &LdVal = NewResults[0];
9124       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9125     }
9126
9127     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9128     DCI.CombineTo(N, NewResults);
9129     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9130
9131     break;
9132   }
9133   return SDValue();
9134 }
9135
9136 static SDValue PerformVLDCombine(SDNode *N,
9137                                  TargetLowering::DAGCombinerInfo &DCI) {
9138   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9139     return SDValue();
9140
9141   return CombineBaseUpdate(N, DCI);
9142 }
9143
9144 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9145 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9146 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9147 /// return true.
9148 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9149   SelectionDAG &DAG = DCI.DAG;
9150   EVT VT = N->getValueType(0);
9151   // vldN-dup instructions only support 64-bit vectors for N > 1.
9152   if (!VT.is64BitVector())
9153     return false;
9154
9155   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9156   SDNode *VLD = N->getOperand(0).getNode();
9157   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9158     return false;
9159   unsigned NumVecs = 0;
9160   unsigned NewOpc = 0;
9161   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9162   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9163     NumVecs = 2;
9164     NewOpc = ARMISD::VLD2DUP;
9165   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9166     NumVecs = 3;
9167     NewOpc = ARMISD::VLD3DUP;
9168   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9169     NumVecs = 4;
9170     NewOpc = ARMISD::VLD4DUP;
9171   } else {
9172     return false;
9173   }
9174
9175   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9176   // numbers match the load.
9177   unsigned VLDLaneNo =
9178     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9179   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9180        UI != UE; ++UI) {
9181     // Ignore uses of the chain result.
9182     if (UI.getUse().getResNo() == NumVecs)
9183       continue;
9184     SDNode *User = *UI;
9185     if (User->getOpcode() != ARMISD::VDUPLANE ||
9186         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9187       return false;
9188   }
9189
9190   // Create the vldN-dup node.
9191   EVT Tys[5];
9192   unsigned n;
9193   for (n = 0; n < NumVecs; ++n)
9194     Tys[n] = VT;
9195   Tys[n] = MVT::Other;
9196   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9197   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9198   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9199   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9200                                            Ops, VLDMemInt->getMemoryVT(),
9201                                            VLDMemInt->getMemOperand());
9202
9203   // Update the uses.
9204   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9205        UI != UE; ++UI) {
9206     unsigned ResNo = UI.getUse().getResNo();
9207     // Ignore uses of the chain result.
9208     if (ResNo == NumVecs)
9209       continue;
9210     SDNode *User = *UI;
9211     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9212   }
9213
9214   // Now the vldN-lane intrinsic is dead except for its chain result.
9215   // Update uses of the chain.
9216   std::vector<SDValue> VLDDupResults;
9217   for (unsigned n = 0; n < NumVecs; ++n)
9218     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9219   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9220   DCI.CombineTo(VLD, VLDDupResults);
9221
9222   return true;
9223 }
9224
9225 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9226 /// ARMISD::VDUPLANE.
9227 static SDValue PerformVDUPLANECombine(SDNode *N,
9228                                       TargetLowering::DAGCombinerInfo &DCI) {
9229   SDValue Op = N->getOperand(0);
9230
9231   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9232   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9233   if (CombineVLDDUP(N, DCI))
9234     return SDValue(N, 0);
9235
9236   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9237   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9238   while (Op.getOpcode() == ISD::BITCAST)
9239     Op = Op.getOperand(0);
9240   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9241     return SDValue();
9242
9243   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9244   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9245   // The canonical VMOV for a zero vector uses a 32-bit element size.
9246   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9247   unsigned EltBits;
9248   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9249     EltSize = 8;
9250   EVT VT = N->getValueType(0);
9251   if (EltSize > VT.getVectorElementType().getSizeInBits())
9252     return SDValue();
9253
9254   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9255 }
9256
9257 static SDValue PerformLOADCombine(SDNode *N,
9258                                   TargetLowering::DAGCombinerInfo &DCI) {
9259   EVT VT = N->getValueType(0);
9260
9261   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9262   if (ISD::isNormalLoad(N) && VT.isVector() &&
9263       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9264     return CombineBaseUpdate(N, DCI);
9265
9266   return SDValue();
9267 }
9268
9269 /// PerformSTORECombine - Target-specific dag combine xforms for
9270 /// ISD::STORE.
9271 static SDValue PerformSTORECombine(SDNode *N,
9272                                    TargetLowering::DAGCombinerInfo &DCI) {
9273   StoreSDNode *St = cast<StoreSDNode>(N);
9274   if (St->isVolatile())
9275     return SDValue();
9276
9277   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9278   // pack all of the elements in one place.  Next, store to memory in fewer
9279   // chunks.
9280   SDValue StVal = St->getValue();
9281   EVT VT = StVal.getValueType();
9282   if (St->isTruncatingStore() && VT.isVector()) {
9283     SelectionDAG &DAG = DCI.DAG;
9284     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9285     EVT StVT = St->getMemoryVT();
9286     unsigned NumElems = VT.getVectorNumElements();
9287     assert(StVT != VT && "Cannot truncate to the same type");
9288     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9289     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9290
9291     // From, To sizes and ElemCount must be pow of two
9292     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9293
9294     // We are going to use the original vector elt for storing.
9295     // Accumulated smaller vector elements must be a multiple of the store size.
9296     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9297
9298     unsigned SizeRatio  = FromEltSz / ToEltSz;
9299     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9300
9301     // Create a type on which we perform the shuffle.
9302     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9303                                      NumElems*SizeRatio);
9304     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9305
9306     SDLoc DL(St);
9307     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9308     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9309     for (unsigned i = 0; i < NumElems; ++i)
9310       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9311                           ? (i + 1) * SizeRatio - 1
9312                           : i * SizeRatio;
9313
9314     // Can't shuffle using an illegal type.
9315     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9316
9317     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9318                                 DAG.getUNDEF(WideVec.getValueType()),
9319                                 ShuffleVec.data());
9320     // At this point all of the data is stored at the bottom of the
9321     // register. We now need to save it to mem.
9322
9323     // Find the largest store unit
9324     MVT StoreType = MVT::i8;
9325     for (MVT Tp : MVT::integer_valuetypes()) {
9326       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9327         StoreType = Tp;
9328     }
9329     // Didn't find a legal store type.
9330     if (!TLI.isTypeLegal(StoreType))
9331       return SDValue();
9332
9333     // Bitcast the original vector into a vector of store-size units
9334     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9335             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9336     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9337     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9338     SmallVector<SDValue, 8> Chains;
9339     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, DL,
9340                                         TLI.getPointerTy());
9341     SDValue BasePtr = St->getBasePtr();
9342
9343     // Perform one or more big stores into memory.
9344     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9345     for (unsigned I = 0; I < E; I++) {
9346       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9347                                    StoreType, ShuffWide,
9348                                    DAG.getIntPtrConstant(I, DL));
9349       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9350                                 St->getPointerInfo(), St->isVolatile(),
9351                                 St->isNonTemporal(), St->getAlignment());
9352       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9353                             Increment);
9354       Chains.push_back(Ch);
9355     }
9356     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9357   }
9358
9359   if (!ISD::isNormalStore(St))
9360     return SDValue();
9361
9362   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9363   // ARM stores of arguments in the same cache line.
9364   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9365       StVal.getNode()->hasOneUse()) {
9366     SelectionDAG  &DAG = DCI.DAG;
9367     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9368     SDLoc DL(St);
9369     SDValue BasePtr = St->getBasePtr();
9370     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9371                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9372                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9373                                   St->isNonTemporal(), St->getAlignment());
9374
9375     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9376                                     DAG.getConstant(4, DL, MVT::i32));
9377     return DAG.getStore(NewST1.getValue(0), DL,
9378                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9379                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9380                         St->isNonTemporal(),
9381                         std::min(4U, St->getAlignment() / 2));
9382   }
9383
9384   if (StVal.getValueType() == MVT::i64 &&
9385       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9386
9387     // Bitcast an i64 store extracted from a vector to f64.
9388     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9389     SelectionDAG &DAG = DCI.DAG;
9390     SDLoc dl(StVal);
9391     SDValue IntVec = StVal.getOperand(0);
9392     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9393                                    IntVec.getValueType().getVectorNumElements());
9394     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9395     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9396                                  Vec, StVal.getOperand(1));
9397     dl = SDLoc(N);
9398     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9399     // Make the DAGCombiner fold the bitcasts.
9400     DCI.AddToWorklist(Vec.getNode());
9401     DCI.AddToWorklist(ExtElt.getNode());
9402     DCI.AddToWorklist(V.getNode());
9403     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9404                         St->getPointerInfo(), St->isVolatile(),
9405                         St->isNonTemporal(), St->getAlignment(),
9406                         St->getAAInfo());
9407   }
9408
9409   // If this is a legal vector store, try to combine it into a VST1_UPD.
9410   if (ISD::isNormalStore(N) && VT.isVector() &&
9411       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9412     return CombineBaseUpdate(N, DCI);
9413
9414   return SDValue();
9415 }
9416
9417 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9418 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9419 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9420 {
9421   integerPart cN;
9422   integerPart c0 = 0;
9423   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9424        I != E; I++) {
9425     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9426     if (!C)
9427       return false;
9428
9429     bool isExact;
9430     APFloat APF = C->getValueAPF();
9431     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9432         != APFloat::opOK || !isExact)
9433       return false;
9434
9435     c0 = (I == 0) ? cN : c0;
9436     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9437       return false;
9438   }
9439   C = c0;
9440   return true;
9441 }
9442
9443 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9444 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9445 /// when the VMUL has a constant operand that is a power of 2.
9446 ///
9447 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9448 ///  vmul.f32        d16, d17, d16
9449 ///  vcvt.s32.f32    d16, d16
9450 /// becomes:
9451 ///  vcvt.s32.f32    d16, d16, #3
9452 static SDValue PerformVCVTCombine(SDNode *N,
9453                                   TargetLowering::DAGCombinerInfo &DCI,
9454                                   const ARMSubtarget *Subtarget) {
9455   SelectionDAG &DAG = DCI.DAG;
9456   SDValue Op = N->getOperand(0);
9457
9458   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9459       Op.getOpcode() != ISD::FMUL)
9460     return SDValue();
9461
9462   uint64_t C;
9463   SDValue N0 = Op->getOperand(0);
9464   SDValue ConstVec = Op->getOperand(1);
9465   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9466
9467   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9468       !isConstVecPow2(ConstVec, isSigned, C))
9469     return SDValue();
9470
9471   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9472   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9473   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9474   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9475       NumLanes > 4) {
9476     // These instructions only exist converting from f32 to i32. We can handle
9477     // smaller integers by generating an extra truncate, but larger ones would
9478     // be lossy. We also can't handle more then 4 lanes, since these intructions
9479     // only support v2i32/v4i32 types.
9480     return SDValue();
9481   }
9482
9483   SDLoc dl(N);
9484   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9485     Intrinsic::arm_neon_vcvtfp2fxu;
9486   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9487                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9488                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9489                                  N0,
9490                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9491
9492   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9493     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9494
9495   return FixConv;
9496 }
9497
9498 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9499 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9500 /// when the VDIV has a constant operand that is a power of 2.
9501 ///
9502 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9503 ///  vcvt.f32.s32    d16, d16
9504 ///  vdiv.f32        d16, d17, d16
9505 /// becomes:
9506 ///  vcvt.f32.s32    d16, d16, #3
9507 static SDValue PerformVDIVCombine(SDNode *N,
9508                                   TargetLowering::DAGCombinerInfo &DCI,
9509                                   const ARMSubtarget *Subtarget) {
9510   SelectionDAG &DAG = DCI.DAG;
9511   SDValue Op = N->getOperand(0);
9512   unsigned OpOpcode = Op.getNode()->getOpcode();
9513
9514   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9515       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9516     return SDValue();
9517
9518   uint64_t C;
9519   SDValue ConstVec = N->getOperand(1);
9520   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9521
9522   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9523       !isConstVecPow2(ConstVec, isSigned, C))
9524     return SDValue();
9525
9526   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9527   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9528   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9529     // These instructions only exist converting from i32 to f32. We can handle
9530     // smaller integers by generating an extra extend, but larger ones would
9531     // be lossy.
9532     return SDValue();
9533   }
9534
9535   SDLoc dl(N);
9536   SDValue ConvInput = Op.getOperand(0);
9537   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9538   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9539     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9540                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9541                             ConvInput);
9542
9543   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9544     Intrinsic::arm_neon_vcvtfxu2fp;
9545   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9546                      Op.getValueType(),
9547                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9548                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9549 }
9550
9551 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9552 /// operand of a vector shift operation, where all the elements of the
9553 /// build_vector must have the same constant integer value.
9554 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9555   // Ignore bit_converts.
9556   while (Op.getOpcode() == ISD::BITCAST)
9557     Op = Op.getOperand(0);
9558   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9559   APInt SplatBits, SplatUndef;
9560   unsigned SplatBitSize;
9561   bool HasAnyUndefs;
9562   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9563                                       HasAnyUndefs, ElementBits) ||
9564       SplatBitSize > ElementBits)
9565     return false;
9566   Cnt = SplatBits.getSExtValue();
9567   return true;
9568 }
9569
9570 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9571 /// operand of a vector shift left operation.  That value must be in the range:
9572 ///   0 <= Value < ElementBits for a left shift; or
9573 ///   0 <= Value <= ElementBits for a long left shift.
9574 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9575   assert(VT.isVector() && "vector shift count is not a vector type");
9576   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9577   if (! getVShiftImm(Op, ElementBits, Cnt))
9578     return false;
9579   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9580 }
9581
9582 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9583 /// operand of a vector shift right operation.  For a shift opcode, the value
9584 /// is positive, but for an intrinsic the value count must be negative. The
9585 /// absolute value must be in the range:
9586 ///   1 <= |Value| <= ElementBits for a right shift; or
9587 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9588 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9589                          int64_t &Cnt) {
9590   assert(VT.isVector() && "vector shift count is not a vector type");
9591   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9592   if (! getVShiftImm(Op, ElementBits, Cnt))
9593     return false;
9594   if (isIntrinsic)
9595     Cnt = -Cnt;
9596   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9597 }
9598
9599 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9600 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9601   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9602   switch (IntNo) {
9603   default:
9604     // Don't do anything for most intrinsics.
9605     break;
9606
9607   // Vector shifts: check for immediate versions and lower them.
9608   // Note: This is done during DAG combining instead of DAG legalizing because
9609   // the build_vectors for 64-bit vector element shift counts are generally
9610   // not legal, and it is hard to see their values after they get legalized to
9611   // loads from a constant pool.
9612   case Intrinsic::arm_neon_vshifts:
9613   case Intrinsic::arm_neon_vshiftu:
9614   case Intrinsic::arm_neon_vrshifts:
9615   case Intrinsic::arm_neon_vrshiftu:
9616   case Intrinsic::arm_neon_vrshiftn:
9617   case Intrinsic::arm_neon_vqshifts:
9618   case Intrinsic::arm_neon_vqshiftu:
9619   case Intrinsic::arm_neon_vqshiftsu:
9620   case Intrinsic::arm_neon_vqshiftns:
9621   case Intrinsic::arm_neon_vqshiftnu:
9622   case Intrinsic::arm_neon_vqshiftnsu:
9623   case Intrinsic::arm_neon_vqrshiftns:
9624   case Intrinsic::arm_neon_vqrshiftnu:
9625   case Intrinsic::arm_neon_vqrshiftnsu: {
9626     EVT VT = N->getOperand(1).getValueType();
9627     int64_t Cnt;
9628     unsigned VShiftOpc = 0;
9629
9630     switch (IntNo) {
9631     case Intrinsic::arm_neon_vshifts:
9632     case Intrinsic::arm_neon_vshiftu:
9633       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9634         VShiftOpc = ARMISD::VSHL;
9635         break;
9636       }
9637       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9638         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9639                      ARMISD::VSHRs : ARMISD::VSHRu);
9640         break;
9641       }
9642       return SDValue();
9643
9644     case Intrinsic::arm_neon_vrshifts:
9645     case Intrinsic::arm_neon_vrshiftu:
9646       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9647         break;
9648       return SDValue();
9649
9650     case Intrinsic::arm_neon_vqshifts:
9651     case Intrinsic::arm_neon_vqshiftu:
9652       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9653         break;
9654       return SDValue();
9655
9656     case Intrinsic::arm_neon_vqshiftsu:
9657       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9658         break;
9659       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9660
9661     case Intrinsic::arm_neon_vrshiftn:
9662     case Intrinsic::arm_neon_vqshiftns:
9663     case Intrinsic::arm_neon_vqshiftnu:
9664     case Intrinsic::arm_neon_vqshiftnsu:
9665     case Intrinsic::arm_neon_vqrshiftns:
9666     case Intrinsic::arm_neon_vqrshiftnu:
9667     case Intrinsic::arm_neon_vqrshiftnsu:
9668       // Narrowing shifts require an immediate right shift.
9669       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9670         break;
9671       llvm_unreachable("invalid shift count for narrowing vector shift "
9672                        "intrinsic");
9673
9674     default:
9675       llvm_unreachable("unhandled vector shift");
9676     }
9677
9678     switch (IntNo) {
9679     case Intrinsic::arm_neon_vshifts:
9680     case Intrinsic::arm_neon_vshiftu:
9681       // Opcode already set above.
9682       break;
9683     case Intrinsic::arm_neon_vrshifts:
9684       VShiftOpc = ARMISD::VRSHRs; break;
9685     case Intrinsic::arm_neon_vrshiftu:
9686       VShiftOpc = ARMISD::VRSHRu; break;
9687     case Intrinsic::arm_neon_vrshiftn:
9688       VShiftOpc = ARMISD::VRSHRN; break;
9689     case Intrinsic::arm_neon_vqshifts:
9690       VShiftOpc = ARMISD::VQSHLs; break;
9691     case Intrinsic::arm_neon_vqshiftu:
9692       VShiftOpc = ARMISD::VQSHLu; break;
9693     case Intrinsic::arm_neon_vqshiftsu:
9694       VShiftOpc = ARMISD::VQSHLsu; break;
9695     case Intrinsic::arm_neon_vqshiftns:
9696       VShiftOpc = ARMISD::VQSHRNs; break;
9697     case Intrinsic::arm_neon_vqshiftnu:
9698       VShiftOpc = ARMISD::VQSHRNu; break;
9699     case Intrinsic::arm_neon_vqshiftnsu:
9700       VShiftOpc = ARMISD::VQSHRNsu; break;
9701     case Intrinsic::arm_neon_vqrshiftns:
9702       VShiftOpc = ARMISD::VQRSHRNs; break;
9703     case Intrinsic::arm_neon_vqrshiftnu:
9704       VShiftOpc = ARMISD::VQRSHRNu; break;
9705     case Intrinsic::arm_neon_vqrshiftnsu:
9706       VShiftOpc = ARMISD::VQRSHRNsu; break;
9707     }
9708
9709     SDLoc dl(N);
9710     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9711                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9712   }
9713
9714   case Intrinsic::arm_neon_vshiftins: {
9715     EVT VT = N->getOperand(1).getValueType();
9716     int64_t Cnt;
9717     unsigned VShiftOpc = 0;
9718
9719     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9720       VShiftOpc = ARMISD::VSLI;
9721     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9722       VShiftOpc = ARMISD::VSRI;
9723     else {
9724       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9725     }
9726
9727     SDLoc dl(N);
9728     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9729                        N->getOperand(1), N->getOperand(2),
9730                        DAG.getConstant(Cnt, dl, MVT::i32));
9731   }
9732
9733   case Intrinsic::arm_neon_vqrshifts:
9734   case Intrinsic::arm_neon_vqrshiftu:
9735     // No immediate versions of these to check for.
9736     break;
9737   }
9738
9739   return SDValue();
9740 }
9741
9742 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9743 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9744 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9745 /// vector element shift counts are generally not legal, and it is hard to see
9746 /// their values after they get legalized to loads from a constant pool.
9747 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9748                                    const ARMSubtarget *ST) {
9749   EVT VT = N->getValueType(0);
9750   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9751     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9752     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9753     SDValue N1 = N->getOperand(1);
9754     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9755       SDValue N0 = N->getOperand(0);
9756       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9757           DAG.MaskedValueIsZero(N0.getOperand(0),
9758                                 APInt::getHighBitsSet(32, 16)))
9759         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9760     }
9761   }
9762
9763   // Nothing to be done for scalar shifts.
9764   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9765   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9766     return SDValue();
9767
9768   assert(ST->hasNEON() && "unexpected vector shift");
9769   int64_t Cnt;
9770
9771   switch (N->getOpcode()) {
9772   default: llvm_unreachable("unexpected shift opcode");
9773
9774   case ISD::SHL:
9775     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
9776       SDLoc dl(N);
9777       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
9778                          DAG.getConstant(Cnt, dl, MVT::i32));
9779     }
9780     break;
9781
9782   case ISD::SRA:
9783   case ISD::SRL:
9784     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9785       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9786                             ARMISD::VSHRs : ARMISD::VSHRu);
9787       SDLoc dl(N);
9788       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
9789                          DAG.getConstant(Cnt, dl, MVT::i32));
9790     }
9791   }
9792   return SDValue();
9793 }
9794
9795 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9796 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9797 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9798                                     const ARMSubtarget *ST) {
9799   SDValue N0 = N->getOperand(0);
9800
9801   // Check for sign- and zero-extensions of vector extract operations of 8-
9802   // and 16-bit vector elements.  NEON supports these directly.  They are
9803   // handled during DAG combining because type legalization will promote them
9804   // to 32-bit types and it is messy to recognize the operations after that.
9805   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9806     SDValue Vec = N0.getOperand(0);
9807     SDValue Lane = N0.getOperand(1);
9808     EVT VT = N->getValueType(0);
9809     EVT EltVT = N0.getValueType();
9810     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9811
9812     if (VT == MVT::i32 &&
9813         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9814         TLI.isTypeLegal(Vec.getValueType()) &&
9815         isa<ConstantSDNode>(Lane)) {
9816
9817       unsigned Opc = 0;
9818       switch (N->getOpcode()) {
9819       default: llvm_unreachable("unexpected opcode");
9820       case ISD::SIGN_EXTEND:
9821         Opc = ARMISD::VGETLANEs;
9822         break;
9823       case ISD::ZERO_EXTEND:
9824       case ISD::ANY_EXTEND:
9825         Opc = ARMISD::VGETLANEu;
9826         break;
9827       }
9828       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9829     }
9830   }
9831
9832   return SDValue();
9833 }
9834
9835 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9836 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9837 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9838                                        const ARMSubtarget *ST) {
9839   // If the target supports NEON, try to use vmax/vmin instructions for f32
9840   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9841   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9842   // a NaN; only do the transformation when it matches that behavior.
9843
9844   // For now only do this when using NEON for FP operations; if using VFP, it
9845   // is not obvious that the benefit outweighs the cost of switching to the
9846   // NEON pipeline.
9847   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9848       N->getValueType(0) != MVT::f32)
9849     return SDValue();
9850
9851   SDValue CondLHS = N->getOperand(0);
9852   SDValue CondRHS = N->getOperand(1);
9853   SDValue LHS = N->getOperand(2);
9854   SDValue RHS = N->getOperand(3);
9855   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9856
9857   unsigned Opcode = 0;
9858   bool IsReversed;
9859   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9860     IsReversed = false; // x CC y ? x : y
9861   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9862     IsReversed = true ; // x CC y ? y : x
9863   } else {
9864     return SDValue();
9865   }
9866
9867   bool IsUnordered;
9868   switch (CC) {
9869   default: break;
9870   case ISD::SETOLT:
9871   case ISD::SETOLE:
9872   case ISD::SETLT:
9873   case ISD::SETLE:
9874   case ISD::SETULT:
9875   case ISD::SETULE:
9876     // If LHS is NaN, an ordered comparison will be false and the result will
9877     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9878     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9879     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9880     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9881       break;
9882     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9883     // will return -0, so vmin can only be used for unsafe math or if one of
9884     // the operands is known to be nonzero.
9885     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9886         !DAG.getTarget().Options.UnsafeFPMath &&
9887         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9888       break;
9889     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9890     break;
9891
9892   case ISD::SETOGT:
9893   case ISD::SETOGE:
9894   case ISD::SETGT:
9895   case ISD::SETGE:
9896   case ISD::SETUGT:
9897   case ISD::SETUGE:
9898     // If LHS is NaN, an ordered comparison will be false and the result will
9899     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9900     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9901     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9902     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9903       break;
9904     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9905     // will return +0, so vmax can only be used for unsafe math or if one of
9906     // the operands is known to be nonzero.
9907     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9908         !DAG.getTarget().Options.UnsafeFPMath &&
9909         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9910       break;
9911     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9912     break;
9913   }
9914
9915   if (!Opcode)
9916     return SDValue();
9917   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9918 }
9919
9920 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9921 SDValue
9922 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9923   SDValue Cmp = N->getOperand(4);
9924   if (Cmp.getOpcode() != ARMISD::CMPZ)
9925     // Only looking at EQ and NE cases.
9926     return SDValue();
9927
9928   EVT VT = N->getValueType(0);
9929   SDLoc dl(N);
9930   SDValue LHS = Cmp.getOperand(0);
9931   SDValue RHS = Cmp.getOperand(1);
9932   SDValue FalseVal = N->getOperand(0);
9933   SDValue TrueVal = N->getOperand(1);
9934   SDValue ARMcc = N->getOperand(2);
9935   ARMCC::CondCodes CC =
9936     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9937
9938   // Simplify
9939   //   mov     r1, r0
9940   //   cmp     r1, x
9941   //   mov     r0, y
9942   //   moveq   r0, x
9943   // to
9944   //   cmp     r0, x
9945   //   movne   r0, y
9946   //
9947   //   mov     r1, r0
9948   //   cmp     r1, x
9949   //   mov     r0, x
9950   //   movne   r0, y
9951   // to
9952   //   cmp     r0, x
9953   //   movne   r0, y
9954   /// FIXME: Turn this into a target neutral optimization?
9955   SDValue Res;
9956   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9957     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9958                       N->getOperand(3), Cmp);
9959   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9960     SDValue ARMcc;
9961     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9962     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9963                       N->getOperand(3), NewCmp);
9964   }
9965
9966   if (Res.getNode()) {
9967     APInt KnownZero, KnownOne;
9968     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9969     // Capture demanded bits information that would be otherwise lost.
9970     if (KnownZero == 0xfffffffe)
9971       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9972                         DAG.getValueType(MVT::i1));
9973     else if (KnownZero == 0xffffff00)
9974       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9975                         DAG.getValueType(MVT::i8));
9976     else if (KnownZero == 0xffff0000)
9977       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9978                         DAG.getValueType(MVT::i16));
9979   }
9980
9981   return Res;
9982 }
9983
9984 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9985                                              DAGCombinerInfo &DCI) const {
9986   switch (N->getOpcode()) {
9987   default: break;
9988   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9989   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9990   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9991   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9992   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9993   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9994   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9995   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9996   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9997   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9998   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9999   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10000   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10001   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10002   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10003   case ISD::FP_TO_SINT:
10004   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10005   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10006   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10007   case ISD::SHL:
10008   case ISD::SRA:
10009   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10010   case ISD::SIGN_EXTEND:
10011   case ISD::ZERO_EXTEND:
10012   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10013   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10014   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10015   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10016   case ARMISD::VLD2DUP:
10017   case ARMISD::VLD3DUP:
10018   case ARMISD::VLD4DUP:
10019     return PerformVLDCombine(N, DCI);
10020   case ARMISD::BUILD_VECTOR:
10021     return PerformARMBUILD_VECTORCombine(N, DCI);
10022   case ISD::INTRINSIC_VOID:
10023   case ISD::INTRINSIC_W_CHAIN:
10024     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10025     case Intrinsic::arm_neon_vld1:
10026     case Intrinsic::arm_neon_vld2:
10027     case Intrinsic::arm_neon_vld3:
10028     case Intrinsic::arm_neon_vld4:
10029     case Intrinsic::arm_neon_vld2lane:
10030     case Intrinsic::arm_neon_vld3lane:
10031     case Intrinsic::arm_neon_vld4lane:
10032     case Intrinsic::arm_neon_vst1:
10033     case Intrinsic::arm_neon_vst2:
10034     case Intrinsic::arm_neon_vst3:
10035     case Intrinsic::arm_neon_vst4:
10036     case Intrinsic::arm_neon_vst2lane:
10037     case Intrinsic::arm_neon_vst3lane:
10038     case Intrinsic::arm_neon_vst4lane:
10039       return PerformVLDCombine(N, DCI);
10040     default: break;
10041     }
10042     break;
10043   }
10044   return SDValue();
10045 }
10046
10047 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10048                                                           EVT VT) const {
10049   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10050 }
10051
10052 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10053                                                        unsigned,
10054                                                        unsigned,
10055                                                        bool *Fast) const {
10056   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10057   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10058
10059   switch (VT.getSimpleVT().SimpleTy) {
10060   default:
10061     return false;
10062   case MVT::i8:
10063   case MVT::i16:
10064   case MVT::i32: {
10065     // Unaligned access can use (for example) LRDB, LRDH, LDR
10066     if (AllowsUnaligned) {
10067       if (Fast)
10068         *Fast = Subtarget->hasV7Ops();
10069       return true;
10070     }
10071     return false;
10072   }
10073   case MVT::f64:
10074   case MVT::v2f64: {
10075     // For any little-endian targets with neon, we can support unaligned ld/st
10076     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10077     // A big-endian target may also explicitly support unaligned accesses
10078     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10079       if (Fast)
10080         *Fast = true;
10081       return true;
10082     }
10083     return false;
10084   }
10085   }
10086 }
10087
10088 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10089                        unsigned AlignCheck) {
10090   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10091           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10092 }
10093
10094 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10095                                            unsigned DstAlign, unsigned SrcAlign,
10096                                            bool IsMemset, bool ZeroMemset,
10097                                            bool MemcpyStrSrc,
10098                                            MachineFunction &MF) const {
10099   const Function *F = MF.getFunction();
10100
10101   // See if we can use NEON instructions for this...
10102   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10103       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10104     bool Fast;
10105     if (Size >= 16 &&
10106         (memOpAlign(SrcAlign, DstAlign, 16) ||
10107          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10108       return MVT::v2f64;
10109     } else if (Size >= 8 &&
10110                (memOpAlign(SrcAlign, DstAlign, 8) ||
10111                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10112                  Fast))) {
10113       return MVT::f64;
10114     }
10115   }
10116
10117   // Lowering to i32/i16 if the size permits.
10118   if (Size >= 4)
10119     return MVT::i32;
10120   else if (Size >= 2)
10121     return MVT::i16;
10122
10123   // Let the target-independent logic figure it out.
10124   return MVT::Other;
10125 }
10126
10127 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10128   if (Val.getOpcode() != ISD::LOAD)
10129     return false;
10130
10131   EVT VT1 = Val.getValueType();
10132   if (!VT1.isSimple() || !VT1.isInteger() ||
10133       !VT2.isSimple() || !VT2.isInteger())
10134     return false;
10135
10136   switch (VT1.getSimpleVT().SimpleTy) {
10137   default: break;
10138   case MVT::i1:
10139   case MVT::i8:
10140   case MVT::i16:
10141     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10142     return true;
10143   }
10144
10145   return false;
10146 }
10147
10148 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10149   EVT VT = ExtVal.getValueType();
10150
10151   if (!isTypeLegal(VT))
10152     return false;
10153
10154   // Don't create a loadext if we can fold the extension into a wide/long
10155   // instruction.
10156   // If there's more than one user instruction, the loadext is desirable no
10157   // matter what.  There can be two uses by the same instruction.
10158   if (ExtVal->use_empty() ||
10159       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10160     return true;
10161
10162   SDNode *U = *ExtVal->use_begin();
10163   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10164        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10165     return false;
10166
10167   return true;
10168 }
10169
10170 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10171   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10172     return false;
10173
10174   if (!isTypeLegal(EVT::getEVT(Ty1)))
10175     return false;
10176
10177   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10178
10179   // Assuming the caller doesn't have a zeroext or signext return parameter,
10180   // truncation all the way down to i1 is valid.
10181   return true;
10182 }
10183
10184
10185 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10186   if (V < 0)
10187     return false;
10188
10189   unsigned Scale = 1;
10190   switch (VT.getSimpleVT().SimpleTy) {
10191   default: return false;
10192   case MVT::i1:
10193   case MVT::i8:
10194     // Scale == 1;
10195     break;
10196   case MVT::i16:
10197     // Scale == 2;
10198     Scale = 2;
10199     break;
10200   case MVT::i32:
10201     // Scale == 4;
10202     Scale = 4;
10203     break;
10204   }
10205
10206   if ((V & (Scale - 1)) != 0)
10207     return false;
10208   V /= Scale;
10209   return V == (V & ((1LL << 5) - 1));
10210 }
10211
10212 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10213                                       const ARMSubtarget *Subtarget) {
10214   bool isNeg = false;
10215   if (V < 0) {
10216     isNeg = true;
10217     V = - V;
10218   }
10219
10220   switch (VT.getSimpleVT().SimpleTy) {
10221   default: return false;
10222   case MVT::i1:
10223   case MVT::i8:
10224   case MVT::i16:
10225   case MVT::i32:
10226     // + imm12 or - imm8
10227     if (isNeg)
10228       return V == (V & ((1LL << 8) - 1));
10229     return V == (V & ((1LL << 12) - 1));
10230   case MVT::f32:
10231   case MVT::f64:
10232     // Same as ARM mode. FIXME: NEON?
10233     if (!Subtarget->hasVFP2())
10234       return false;
10235     if ((V & 3) != 0)
10236       return false;
10237     V >>= 2;
10238     return V == (V & ((1LL << 8) - 1));
10239   }
10240 }
10241
10242 /// isLegalAddressImmediate - Return true if the integer value can be used
10243 /// as the offset of the target addressing mode for load / store of the
10244 /// given type.
10245 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10246                                     const ARMSubtarget *Subtarget) {
10247   if (V == 0)
10248     return true;
10249
10250   if (!VT.isSimple())
10251     return false;
10252
10253   if (Subtarget->isThumb1Only())
10254     return isLegalT1AddressImmediate(V, VT);
10255   else if (Subtarget->isThumb2())
10256     return isLegalT2AddressImmediate(V, VT, Subtarget);
10257
10258   // ARM mode.
10259   if (V < 0)
10260     V = - V;
10261   switch (VT.getSimpleVT().SimpleTy) {
10262   default: return false;
10263   case MVT::i1:
10264   case MVT::i8:
10265   case MVT::i32:
10266     // +- imm12
10267     return V == (V & ((1LL << 12) - 1));
10268   case MVT::i16:
10269     // +- imm8
10270     return V == (V & ((1LL << 8) - 1));
10271   case MVT::f32:
10272   case MVT::f64:
10273     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10274       return false;
10275     if ((V & 3) != 0)
10276       return false;
10277     V >>= 2;
10278     return V == (V & ((1LL << 8) - 1));
10279   }
10280 }
10281
10282 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10283                                                       EVT VT) const {
10284   int Scale = AM.Scale;
10285   if (Scale < 0)
10286     return false;
10287
10288   switch (VT.getSimpleVT().SimpleTy) {
10289   default: return false;
10290   case MVT::i1:
10291   case MVT::i8:
10292   case MVT::i16:
10293   case MVT::i32:
10294     if (Scale == 1)
10295       return true;
10296     // r + r << imm
10297     Scale = Scale & ~1;
10298     return Scale == 2 || Scale == 4 || Scale == 8;
10299   case MVT::i64:
10300     // r + r
10301     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10302       return true;
10303     return false;
10304   case MVT::isVoid:
10305     // Note, we allow "void" uses (basically, uses that aren't loads or
10306     // stores), because arm allows folding a scale into many arithmetic
10307     // operations.  This should be made more precise and revisited later.
10308
10309     // Allow r << imm, but the imm has to be a multiple of two.
10310     if (Scale & 1) return false;
10311     return isPowerOf2_32(Scale);
10312   }
10313 }
10314
10315 /// isLegalAddressingMode - Return true if the addressing mode represented
10316 /// by AM is legal for this target, for a load/store of the specified type.
10317 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10318                                               Type *Ty,
10319                                               unsigned AS) const {
10320   EVT VT = getValueType(Ty, true);
10321   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10322     return false;
10323
10324   // Can never fold addr of global into load/store.
10325   if (AM.BaseGV)
10326     return false;
10327
10328   switch (AM.Scale) {
10329   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10330     break;
10331   case 1:
10332     if (Subtarget->isThumb1Only())
10333       return false;
10334     // FALL THROUGH.
10335   default:
10336     // ARM doesn't support any R+R*scale+imm addr modes.
10337     if (AM.BaseOffs)
10338       return false;
10339
10340     if (!VT.isSimple())
10341       return false;
10342
10343     if (Subtarget->isThumb2())
10344       return isLegalT2ScaledAddressingMode(AM, VT);
10345
10346     int Scale = AM.Scale;
10347     switch (VT.getSimpleVT().SimpleTy) {
10348     default: return false;
10349     case MVT::i1:
10350     case MVT::i8:
10351     case MVT::i32:
10352       if (Scale < 0) Scale = -Scale;
10353       if (Scale == 1)
10354         return true;
10355       // r + r << imm
10356       return isPowerOf2_32(Scale & ~1);
10357     case MVT::i16:
10358     case MVT::i64:
10359       // r + r
10360       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10361         return true;
10362       return false;
10363
10364     case MVT::isVoid:
10365       // Note, we allow "void" uses (basically, uses that aren't loads or
10366       // stores), because arm allows folding a scale into many arithmetic
10367       // operations.  This should be made more precise and revisited later.
10368
10369       // Allow r << imm, but the imm has to be a multiple of two.
10370       if (Scale & 1) return false;
10371       return isPowerOf2_32(Scale);
10372     }
10373   }
10374   return true;
10375 }
10376
10377 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10378 /// icmp immediate, that is the target has icmp instructions which can compare
10379 /// a register against the immediate without having to materialize the
10380 /// immediate into a register.
10381 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10382   // Thumb2 and ARM modes can use cmn for negative immediates.
10383   if (!Subtarget->isThumb())
10384     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10385   if (Subtarget->isThumb2())
10386     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10387   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10388   return Imm >= 0 && Imm <= 255;
10389 }
10390
10391 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10392 /// *or sub* immediate, that is the target has add or sub instructions which can
10393 /// add a register with the immediate without having to materialize the
10394 /// immediate into a register.
10395 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10396   // Same encoding for add/sub, just flip the sign.
10397   int64_t AbsImm = std::abs(Imm);
10398   if (!Subtarget->isThumb())
10399     return ARM_AM::getSOImmVal(AbsImm) != -1;
10400   if (Subtarget->isThumb2())
10401     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10402   // Thumb1 only has 8-bit unsigned immediate.
10403   return AbsImm >= 0 && AbsImm <= 255;
10404 }
10405
10406 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10407                                       bool isSEXTLoad, SDValue &Base,
10408                                       SDValue &Offset, bool &isInc,
10409                                       SelectionDAG &DAG) {
10410   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10411     return false;
10412
10413   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10414     // AddressingMode 3
10415     Base = Ptr->getOperand(0);
10416     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10417       int RHSC = (int)RHS->getZExtValue();
10418       if (RHSC < 0 && RHSC > -256) {
10419         assert(Ptr->getOpcode() == ISD::ADD);
10420         isInc = false;
10421         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10422         return true;
10423       }
10424     }
10425     isInc = (Ptr->getOpcode() == ISD::ADD);
10426     Offset = Ptr->getOperand(1);
10427     return true;
10428   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10429     // AddressingMode 2
10430     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10431       int RHSC = (int)RHS->getZExtValue();
10432       if (RHSC < 0 && RHSC > -0x1000) {
10433         assert(Ptr->getOpcode() == ISD::ADD);
10434         isInc = false;
10435         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10436         Base = Ptr->getOperand(0);
10437         return true;
10438       }
10439     }
10440
10441     if (Ptr->getOpcode() == ISD::ADD) {
10442       isInc = true;
10443       ARM_AM::ShiftOpc ShOpcVal=
10444         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10445       if (ShOpcVal != ARM_AM::no_shift) {
10446         Base = Ptr->getOperand(1);
10447         Offset = Ptr->getOperand(0);
10448       } else {
10449         Base = Ptr->getOperand(0);
10450         Offset = Ptr->getOperand(1);
10451       }
10452       return true;
10453     }
10454
10455     isInc = (Ptr->getOpcode() == ISD::ADD);
10456     Base = Ptr->getOperand(0);
10457     Offset = Ptr->getOperand(1);
10458     return true;
10459   }
10460
10461   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10462   return false;
10463 }
10464
10465 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10466                                      bool isSEXTLoad, SDValue &Base,
10467                                      SDValue &Offset, bool &isInc,
10468                                      SelectionDAG &DAG) {
10469   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10470     return false;
10471
10472   Base = Ptr->getOperand(0);
10473   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10474     int RHSC = (int)RHS->getZExtValue();
10475     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10476       assert(Ptr->getOpcode() == ISD::ADD);
10477       isInc = false;
10478       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10479       return true;
10480     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10481       isInc = Ptr->getOpcode() == ISD::ADD;
10482       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10483       return true;
10484     }
10485   }
10486
10487   return false;
10488 }
10489
10490 /// getPreIndexedAddressParts - returns true by value, base pointer and
10491 /// offset pointer and addressing mode by reference if the node's address
10492 /// can be legally represented as pre-indexed load / store address.
10493 bool
10494 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10495                                              SDValue &Offset,
10496                                              ISD::MemIndexedMode &AM,
10497                                              SelectionDAG &DAG) const {
10498   if (Subtarget->isThumb1Only())
10499     return false;
10500
10501   EVT VT;
10502   SDValue Ptr;
10503   bool isSEXTLoad = false;
10504   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10505     Ptr = LD->getBasePtr();
10506     VT  = LD->getMemoryVT();
10507     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10508   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10509     Ptr = ST->getBasePtr();
10510     VT  = ST->getMemoryVT();
10511   } else
10512     return false;
10513
10514   bool isInc;
10515   bool isLegal = false;
10516   if (Subtarget->isThumb2())
10517     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10518                                        Offset, isInc, DAG);
10519   else
10520     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10521                                         Offset, isInc, DAG);
10522   if (!isLegal)
10523     return false;
10524
10525   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10526   return true;
10527 }
10528
10529 /// getPostIndexedAddressParts - returns true by value, base pointer and
10530 /// offset pointer and addressing mode by reference if this node can be
10531 /// combined with a load / store to form a post-indexed load / store.
10532 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10533                                                    SDValue &Base,
10534                                                    SDValue &Offset,
10535                                                    ISD::MemIndexedMode &AM,
10536                                                    SelectionDAG &DAG) const {
10537   if (Subtarget->isThumb1Only())
10538     return false;
10539
10540   EVT VT;
10541   SDValue Ptr;
10542   bool isSEXTLoad = false;
10543   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10544     VT  = LD->getMemoryVT();
10545     Ptr = LD->getBasePtr();
10546     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10547   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10548     VT  = ST->getMemoryVT();
10549     Ptr = ST->getBasePtr();
10550   } else
10551     return false;
10552
10553   bool isInc;
10554   bool isLegal = false;
10555   if (Subtarget->isThumb2())
10556     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10557                                        isInc, DAG);
10558   else
10559     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10560                                         isInc, DAG);
10561   if (!isLegal)
10562     return false;
10563
10564   if (Ptr != Base) {
10565     // Swap base ptr and offset to catch more post-index load / store when
10566     // it's legal. In Thumb2 mode, offset must be an immediate.
10567     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10568         !Subtarget->isThumb2())
10569       std::swap(Base, Offset);
10570
10571     // Post-indexed load / store update the base pointer.
10572     if (Ptr != Base)
10573       return false;
10574   }
10575
10576   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10577   return true;
10578 }
10579
10580 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10581                                                       APInt &KnownZero,
10582                                                       APInt &KnownOne,
10583                                                       const SelectionDAG &DAG,
10584                                                       unsigned Depth) const {
10585   unsigned BitWidth = KnownOne.getBitWidth();
10586   KnownZero = KnownOne = APInt(BitWidth, 0);
10587   switch (Op.getOpcode()) {
10588   default: break;
10589   case ARMISD::ADDC:
10590   case ARMISD::ADDE:
10591   case ARMISD::SUBC:
10592   case ARMISD::SUBE:
10593     // These nodes' second result is a boolean
10594     if (Op.getResNo() == 0)
10595       break;
10596     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10597     break;
10598   case ARMISD::CMOV: {
10599     // Bits are known zero/one if known on the LHS and RHS.
10600     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10601     if (KnownZero == 0 && KnownOne == 0) return;
10602
10603     APInt KnownZeroRHS, KnownOneRHS;
10604     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10605     KnownZero &= KnownZeroRHS;
10606     KnownOne  &= KnownOneRHS;
10607     return;
10608   }
10609   case ISD::INTRINSIC_W_CHAIN: {
10610     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10611     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10612     switch (IntID) {
10613     default: return;
10614     case Intrinsic::arm_ldaex:
10615     case Intrinsic::arm_ldrex: {
10616       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10617       unsigned MemBits = VT.getScalarType().getSizeInBits();
10618       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10619       return;
10620     }
10621     }
10622   }
10623   }
10624 }
10625
10626 //===----------------------------------------------------------------------===//
10627 //                           ARM Inline Assembly Support
10628 //===----------------------------------------------------------------------===//
10629
10630 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10631   // Looking for "rev" which is V6+.
10632   if (!Subtarget->hasV6Ops())
10633     return false;
10634
10635   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10636   std::string AsmStr = IA->getAsmString();
10637   SmallVector<StringRef, 4> AsmPieces;
10638   SplitString(AsmStr, AsmPieces, ";\n");
10639
10640   switch (AsmPieces.size()) {
10641   default: return false;
10642   case 1:
10643     AsmStr = AsmPieces[0];
10644     AsmPieces.clear();
10645     SplitString(AsmStr, AsmPieces, " \t,");
10646
10647     // rev $0, $1
10648     if (AsmPieces.size() == 3 &&
10649         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10650         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10651       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10652       if (Ty && Ty->getBitWidth() == 32)
10653         return IntrinsicLowering::LowerToByteSwap(CI);
10654     }
10655     break;
10656   }
10657
10658   return false;
10659 }
10660
10661 /// getConstraintType - Given a constraint letter, return the type of
10662 /// constraint it is for this target.
10663 ARMTargetLowering::ConstraintType
10664 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10665   if (Constraint.size() == 1) {
10666     switch (Constraint[0]) {
10667     default:  break;
10668     case 'l': return C_RegisterClass;
10669     case 'w': return C_RegisterClass;
10670     case 'h': return C_RegisterClass;
10671     case 'x': return C_RegisterClass;
10672     case 't': return C_RegisterClass;
10673     case 'j': return C_Other; // Constant for movw.
10674       // An address with a single base register. Due to the way we
10675       // currently handle addresses it is the same as an 'r' memory constraint.
10676     case 'Q': return C_Memory;
10677     }
10678   } else if (Constraint.size() == 2) {
10679     switch (Constraint[0]) {
10680     default: break;
10681     // All 'U+' constraints are addresses.
10682     case 'U': return C_Memory;
10683     }
10684   }
10685   return TargetLowering::getConstraintType(Constraint);
10686 }
10687
10688 /// Examine constraint type and operand type and determine a weight value.
10689 /// This object must already have been set up with the operand type
10690 /// and the current alternative constraint selected.
10691 TargetLowering::ConstraintWeight
10692 ARMTargetLowering::getSingleConstraintMatchWeight(
10693     AsmOperandInfo &info, const char *constraint) const {
10694   ConstraintWeight weight = CW_Invalid;
10695   Value *CallOperandVal = info.CallOperandVal;
10696     // If we don't have a value, we can't do a match,
10697     // but allow it at the lowest weight.
10698   if (!CallOperandVal)
10699     return CW_Default;
10700   Type *type = CallOperandVal->getType();
10701   // Look at the constraint type.
10702   switch (*constraint) {
10703   default:
10704     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10705     break;
10706   case 'l':
10707     if (type->isIntegerTy()) {
10708       if (Subtarget->isThumb())
10709         weight = CW_SpecificReg;
10710       else
10711         weight = CW_Register;
10712     }
10713     break;
10714   case 'w':
10715     if (type->isFloatingPointTy())
10716       weight = CW_Register;
10717     break;
10718   }
10719   return weight;
10720 }
10721
10722 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10723 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
10724     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
10725   if (Constraint.size() == 1) {
10726     // GCC ARM Constraint Letters
10727     switch (Constraint[0]) {
10728     case 'l': // Low regs or general regs.
10729       if (Subtarget->isThumb())
10730         return RCPair(0U, &ARM::tGPRRegClass);
10731       return RCPair(0U, &ARM::GPRRegClass);
10732     case 'h': // High regs or no regs.
10733       if (Subtarget->isThumb())
10734         return RCPair(0U, &ARM::hGPRRegClass);
10735       break;
10736     case 'r':
10737       if (Subtarget->isThumb1Only())
10738         return RCPair(0U, &ARM::tGPRRegClass);
10739       return RCPair(0U, &ARM::GPRRegClass);
10740     case 'w':
10741       if (VT == MVT::Other)
10742         break;
10743       if (VT == MVT::f32)
10744         return RCPair(0U, &ARM::SPRRegClass);
10745       if (VT.getSizeInBits() == 64)
10746         return RCPair(0U, &ARM::DPRRegClass);
10747       if (VT.getSizeInBits() == 128)
10748         return RCPair(0U, &ARM::QPRRegClass);
10749       break;
10750     case 'x':
10751       if (VT == MVT::Other)
10752         break;
10753       if (VT == MVT::f32)
10754         return RCPair(0U, &ARM::SPR_8RegClass);
10755       if (VT.getSizeInBits() == 64)
10756         return RCPair(0U, &ARM::DPR_8RegClass);
10757       if (VT.getSizeInBits() == 128)
10758         return RCPair(0U, &ARM::QPR_8RegClass);
10759       break;
10760     case 't':
10761       if (VT == MVT::f32)
10762         return RCPair(0U, &ARM::SPRRegClass);
10763       break;
10764     }
10765   }
10766   if (StringRef("{cc}").equals_lower(Constraint))
10767     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10768
10769   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10770 }
10771
10772 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10773 /// vector.  If it is invalid, don't add anything to Ops.
10774 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10775                                                      std::string &Constraint,
10776                                                      std::vector<SDValue>&Ops,
10777                                                      SelectionDAG &DAG) const {
10778   SDValue Result;
10779
10780   // Currently only support length 1 constraints.
10781   if (Constraint.length() != 1) return;
10782
10783   char ConstraintLetter = Constraint[0];
10784   switch (ConstraintLetter) {
10785   default: break;
10786   case 'j':
10787   case 'I': case 'J': case 'K': case 'L':
10788   case 'M': case 'N': case 'O':
10789     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10790     if (!C)
10791       return;
10792
10793     int64_t CVal64 = C->getSExtValue();
10794     int CVal = (int) CVal64;
10795     // None of these constraints allow values larger than 32 bits.  Check
10796     // that the value fits in an int.
10797     if (CVal != CVal64)
10798       return;
10799
10800     switch (ConstraintLetter) {
10801       case 'j':
10802         // Constant suitable for movw, must be between 0 and
10803         // 65535.
10804         if (Subtarget->hasV6T2Ops())
10805           if (CVal >= 0 && CVal <= 65535)
10806             break;
10807         return;
10808       case 'I':
10809         if (Subtarget->isThumb1Only()) {
10810           // This must be a constant between 0 and 255, for ADD
10811           // immediates.
10812           if (CVal >= 0 && CVal <= 255)
10813             break;
10814         } else if (Subtarget->isThumb2()) {
10815           // A constant that can be used as an immediate value in a
10816           // data-processing instruction.
10817           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10818             break;
10819         } else {
10820           // A constant that can be used as an immediate value in a
10821           // data-processing instruction.
10822           if (ARM_AM::getSOImmVal(CVal) != -1)
10823             break;
10824         }
10825         return;
10826
10827       case 'J':
10828         if (Subtarget->isThumb()) {  // FIXME thumb2
10829           // This must be a constant between -255 and -1, for negated ADD
10830           // immediates. This can be used in GCC with an "n" modifier that
10831           // prints the negated value, for use with SUB instructions. It is
10832           // not useful otherwise but is implemented for compatibility.
10833           if (CVal >= -255 && CVal <= -1)
10834             break;
10835         } else {
10836           // This must be a constant between -4095 and 4095. It is not clear
10837           // what this constraint is intended for. Implemented for
10838           // compatibility with GCC.
10839           if (CVal >= -4095 && CVal <= 4095)
10840             break;
10841         }
10842         return;
10843
10844       case 'K':
10845         if (Subtarget->isThumb1Only()) {
10846           // A 32-bit value where only one byte has a nonzero value. Exclude
10847           // zero to match GCC. This constraint is used by GCC internally for
10848           // constants that can be loaded with a move/shift combination.
10849           // It is not useful otherwise but is implemented for compatibility.
10850           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10851             break;
10852         } else if (Subtarget->isThumb2()) {
10853           // A constant whose bitwise inverse can be used as an immediate
10854           // value in a data-processing instruction. This can be used in GCC
10855           // with a "B" modifier that prints the inverted value, for use with
10856           // BIC and MVN instructions. It is not useful otherwise but is
10857           // implemented for compatibility.
10858           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10859             break;
10860         } else {
10861           // A constant whose bitwise inverse can be used as an immediate
10862           // value in a data-processing instruction. This can be used in GCC
10863           // with a "B" modifier that prints the inverted value, for use with
10864           // BIC and MVN instructions. It is not useful otherwise but is
10865           // implemented for compatibility.
10866           if (ARM_AM::getSOImmVal(~CVal) != -1)
10867             break;
10868         }
10869         return;
10870
10871       case 'L':
10872         if (Subtarget->isThumb1Only()) {
10873           // This must be a constant between -7 and 7,
10874           // for 3-operand ADD/SUB immediate instructions.
10875           if (CVal >= -7 && CVal < 7)
10876             break;
10877         } else if (Subtarget->isThumb2()) {
10878           // A constant whose negation can be used as an immediate value in a
10879           // data-processing instruction. This can be used in GCC with an "n"
10880           // modifier that prints the negated value, for use with SUB
10881           // instructions. It is not useful otherwise but is implemented for
10882           // compatibility.
10883           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10884             break;
10885         } else {
10886           // A constant whose negation can be used as an immediate value in a
10887           // data-processing instruction. This can be used in GCC with an "n"
10888           // modifier that prints the negated value, for use with SUB
10889           // instructions. It is not useful otherwise but is implemented for
10890           // compatibility.
10891           if (ARM_AM::getSOImmVal(-CVal) != -1)
10892             break;
10893         }
10894         return;
10895
10896       case 'M':
10897         if (Subtarget->isThumb()) { // FIXME thumb2
10898           // This must be a multiple of 4 between 0 and 1020, for
10899           // ADD sp + immediate.
10900           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10901             break;
10902         } else {
10903           // A power of two or a constant between 0 and 32.  This is used in
10904           // GCC for the shift amount on shifted register operands, but it is
10905           // useful in general for any shift amounts.
10906           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10907             break;
10908         }
10909         return;
10910
10911       case 'N':
10912         if (Subtarget->isThumb()) {  // FIXME thumb2
10913           // This must be a constant between 0 and 31, for shift amounts.
10914           if (CVal >= 0 && CVal <= 31)
10915             break;
10916         }
10917         return;
10918
10919       case 'O':
10920         if (Subtarget->isThumb()) {  // FIXME thumb2
10921           // This must be a multiple of 4 between -508 and 508, for
10922           // ADD/SUB sp = sp + immediate.
10923           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10924             break;
10925         }
10926         return;
10927     }
10928     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
10929     break;
10930   }
10931
10932   if (Result.getNode()) {
10933     Ops.push_back(Result);
10934     return;
10935   }
10936   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10937 }
10938
10939 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10940   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10941   unsigned Opcode = Op->getOpcode();
10942   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10943          "Invalid opcode for Div/Rem lowering");
10944   bool isSigned = (Opcode == ISD::SDIVREM);
10945   EVT VT = Op->getValueType(0);
10946   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10947
10948   RTLIB::Libcall LC;
10949   switch (VT.getSimpleVT().SimpleTy) {
10950   default: llvm_unreachable("Unexpected request for libcall!");
10951   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10952   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10953   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10954   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10955   }
10956
10957   SDValue InChain = DAG.getEntryNode();
10958
10959   TargetLowering::ArgListTy Args;
10960   TargetLowering::ArgListEntry Entry;
10961   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10962     EVT ArgVT = Op->getOperand(i).getValueType();
10963     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10964     Entry.Node = Op->getOperand(i);
10965     Entry.Ty = ArgTy;
10966     Entry.isSExt = isSigned;
10967     Entry.isZExt = !isSigned;
10968     Args.push_back(Entry);
10969   }
10970
10971   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10972                                          getPointerTy());
10973
10974   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10975
10976   SDLoc dl(Op);
10977   TargetLowering::CallLoweringInfo CLI(DAG);
10978   CLI.setDebugLoc(dl).setChain(InChain)
10979     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10980     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10981
10982   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10983   return CallInfo.first;
10984 }
10985
10986 SDValue
10987 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10988   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10989   SDLoc DL(Op);
10990
10991   // Get the inputs.
10992   SDValue Chain = Op.getOperand(0);
10993   SDValue Size  = Op.getOperand(1);
10994
10995   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10996                               DAG.getConstant(2, DL, MVT::i32));
10997
10998   SDValue Flag;
10999   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11000   Flag = Chain.getValue(1);
11001
11002   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11003   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11004
11005   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11006   Chain = NewSP.getValue(1);
11007
11008   SDValue Ops[2] = { NewSP, Chain };
11009   return DAG.getMergeValues(Ops, DL);
11010 }
11011
11012 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11013   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11014          "Unexpected type for custom-lowering FP_EXTEND");
11015
11016   RTLIB::Libcall LC;
11017   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11018
11019   SDValue SrcVal = Op.getOperand(0);
11020   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11021                      /*isSigned*/ false, SDLoc(Op)).first;
11022 }
11023
11024 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11025   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11026          Subtarget->isFPOnlySP() &&
11027          "Unexpected type for custom-lowering FP_ROUND");
11028
11029   RTLIB::Libcall LC;
11030   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11031
11032   SDValue SrcVal = Op.getOperand(0);
11033   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11034                      /*isSigned*/ false, SDLoc(Op)).first;
11035 }
11036
11037 bool
11038 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11039   // The ARM target isn't yet aware of offsets.
11040   return false;
11041 }
11042
11043 bool ARM::isBitFieldInvertedMask(unsigned v) {
11044   if (v == 0xffffffff)
11045     return false;
11046
11047   // there can be 1's on either or both "outsides", all the "inside"
11048   // bits must be 0's
11049   return isShiftedMask_32(~v);
11050 }
11051
11052 /// isFPImmLegal - Returns true if the target can instruction select the
11053 /// specified FP immediate natively. If false, the legalizer will
11054 /// materialize the FP immediate as a load from a constant pool.
11055 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11056   if (!Subtarget->hasVFP3())
11057     return false;
11058   if (VT == MVT::f32)
11059     return ARM_AM::getFP32Imm(Imm) != -1;
11060   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11061     return ARM_AM::getFP64Imm(Imm) != -1;
11062   return false;
11063 }
11064
11065 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11066 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11067 /// specified in the intrinsic calls.
11068 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11069                                            const CallInst &I,
11070                                            unsigned Intrinsic) const {
11071   switch (Intrinsic) {
11072   case Intrinsic::arm_neon_vld1:
11073   case Intrinsic::arm_neon_vld2:
11074   case Intrinsic::arm_neon_vld3:
11075   case Intrinsic::arm_neon_vld4:
11076   case Intrinsic::arm_neon_vld2lane:
11077   case Intrinsic::arm_neon_vld3lane:
11078   case Intrinsic::arm_neon_vld4lane: {
11079     Info.opc = ISD::INTRINSIC_W_CHAIN;
11080     // Conservatively set memVT to the entire set of vectors loaded.
11081     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11082     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11083     Info.ptrVal = I.getArgOperand(0);
11084     Info.offset = 0;
11085     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11086     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11087     Info.vol = false; // volatile loads with NEON intrinsics not supported
11088     Info.readMem = true;
11089     Info.writeMem = false;
11090     return true;
11091   }
11092   case Intrinsic::arm_neon_vst1:
11093   case Intrinsic::arm_neon_vst2:
11094   case Intrinsic::arm_neon_vst3:
11095   case Intrinsic::arm_neon_vst4:
11096   case Intrinsic::arm_neon_vst2lane:
11097   case Intrinsic::arm_neon_vst3lane:
11098   case Intrinsic::arm_neon_vst4lane: {
11099     Info.opc = ISD::INTRINSIC_VOID;
11100     // Conservatively set memVT to the entire set of vectors stored.
11101     unsigned NumElts = 0;
11102     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11103       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11104       if (!ArgTy->isVectorTy())
11105         break;
11106       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11107     }
11108     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11109     Info.ptrVal = I.getArgOperand(0);
11110     Info.offset = 0;
11111     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11112     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11113     Info.vol = false; // volatile stores with NEON intrinsics not supported
11114     Info.readMem = false;
11115     Info.writeMem = true;
11116     return true;
11117   }
11118   case Intrinsic::arm_ldaex:
11119   case Intrinsic::arm_ldrex: {
11120     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11121     Info.opc = ISD::INTRINSIC_W_CHAIN;
11122     Info.memVT = MVT::getVT(PtrTy->getElementType());
11123     Info.ptrVal = I.getArgOperand(0);
11124     Info.offset = 0;
11125     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11126     Info.vol = true;
11127     Info.readMem = true;
11128     Info.writeMem = false;
11129     return true;
11130   }
11131   case Intrinsic::arm_stlex:
11132   case Intrinsic::arm_strex: {
11133     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11134     Info.opc = ISD::INTRINSIC_W_CHAIN;
11135     Info.memVT = MVT::getVT(PtrTy->getElementType());
11136     Info.ptrVal = I.getArgOperand(1);
11137     Info.offset = 0;
11138     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11139     Info.vol = true;
11140     Info.readMem = false;
11141     Info.writeMem = true;
11142     return true;
11143   }
11144   case Intrinsic::arm_stlexd:
11145   case Intrinsic::arm_strexd: {
11146     Info.opc = ISD::INTRINSIC_W_CHAIN;
11147     Info.memVT = MVT::i64;
11148     Info.ptrVal = I.getArgOperand(2);
11149     Info.offset = 0;
11150     Info.align = 8;
11151     Info.vol = true;
11152     Info.readMem = false;
11153     Info.writeMem = true;
11154     return true;
11155   }
11156   case Intrinsic::arm_ldaexd:
11157   case Intrinsic::arm_ldrexd: {
11158     Info.opc = ISD::INTRINSIC_W_CHAIN;
11159     Info.memVT = MVT::i64;
11160     Info.ptrVal = I.getArgOperand(0);
11161     Info.offset = 0;
11162     Info.align = 8;
11163     Info.vol = true;
11164     Info.readMem = true;
11165     Info.writeMem = false;
11166     return true;
11167   }
11168   default:
11169     break;
11170   }
11171
11172   return false;
11173 }
11174
11175 /// \brief Returns true if it is beneficial to convert a load of a constant
11176 /// to just the constant itself.
11177 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11178                                                           Type *Ty) const {
11179   assert(Ty->isIntegerTy());
11180
11181   unsigned Bits = Ty->getPrimitiveSizeInBits();
11182   if (Bits == 0 || Bits > 32)
11183     return false;
11184   return true;
11185 }
11186
11187 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11188
11189 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11190                                         ARM_MB::MemBOpt Domain) const {
11191   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11192
11193   // First, if the target has no DMB, see what fallback we can use.
11194   if (!Subtarget->hasDataBarrier()) {
11195     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11196     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11197     // here.
11198     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11199       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11200       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11201                         Builder.getInt32(0), Builder.getInt32(7),
11202                         Builder.getInt32(10), Builder.getInt32(5)};
11203       return Builder.CreateCall(MCR, args);
11204     } else {
11205       // Instead of using barriers, atomic accesses on these subtargets use
11206       // libcalls.
11207       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11208     }
11209   } else {
11210     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11211     // Only a full system barrier exists in the M-class architectures.
11212     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11213     Constant *CDomain = Builder.getInt32(Domain);
11214     return Builder.CreateCall(DMB, CDomain);
11215   }
11216 }
11217
11218 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11219 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11220                                          AtomicOrdering Ord, bool IsStore,
11221                                          bool IsLoad) const {
11222   if (!getInsertFencesForAtomic())
11223     return nullptr;
11224
11225   switch (Ord) {
11226   case NotAtomic:
11227   case Unordered:
11228     llvm_unreachable("Invalid fence: unordered/non-atomic");
11229   case Monotonic:
11230   case Acquire:
11231     return nullptr; // Nothing to do
11232   case SequentiallyConsistent:
11233     if (!IsStore)
11234       return nullptr; // Nothing to do
11235     /*FALLTHROUGH*/
11236   case Release:
11237   case AcquireRelease:
11238     if (Subtarget->isSwift())
11239       return makeDMB(Builder, ARM_MB::ISHST);
11240     // FIXME: add a comment with a link to documentation justifying this.
11241     else
11242       return makeDMB(Builder, ARM_MB::ISH);
11243   }
11244   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11245 }
11246
11247 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11248                                           AtomicOrdering Ord, bool IsStore,
11249                                           bool IsLoad) const {
11250   if (!getInsertFencesForAtomic())
11251     return nullptr;
11252
11253   switch (Ord) {
11254   case NotAtomic:
11255   case Unordered:
11256     llvm_unreachable("Invalid fence: unordered/not-atomic");
11257   case Monotonic:
11258   case Release:
11259     return nullptr; // Nothing to do
11260   case Acquire:
11261   case AcquireRelease:
11262   case SequentiallyConsistent:
11263     return makeDMB(Builder, ARM_MB::ISH);
11264   }
11265   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11266 }
11267
11268 // Loads and stores less than 64-bits are already atomic; ones above that
11269 // are doomed anyway, so defer to the default libcall and blame the OS when
11270 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11271 // anything for those.
11272 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11273   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11274   return (Size == 64) && !Subtarget->isMClass();
11275 }
11276
11277 // Loads and stores less than 64-bits are already atomic; ones above that
11278 // are doomed anyway, so defer to the default libcall and blame the OS when
11279 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11280 // anything for those.
11281 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11282 // guarantee, see DDI0406C ARM architecture reference manual,
11283 // sections A8.8.72-74 LDRD)
11284 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11285   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11286   return (Size == 64) && !Subtarget->isMClass();
11287 }
11288
11289 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11290 // and up to 64 bits on the non-M profiles
11291 TargetLoweringBase::AtomicRMWExpansionKind
11292 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11293   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11294   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11295              ? AtomicRMWExpansionKind::LLSC
11296              : AtomicRMWExpansionKind::None;
11297 }
11298
11299 // This has so far only been implemented for MachO.
11300 bool ARMTargetLowering::useLoadStackGuardNode() const {
11301   return Subtarget->isTargetMachO();
11302 }
11303
11304 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11305                                                   unsigned &Cost) const {
11306   // If we do not have NEON, vector types are not natively supported.
11307   if (!Subtarget->hasNEON())
11308     return false;
11309
11310   // Floating point values and vector values map to the same register file.
11311   // Therefore, althought we could do a store extract of a vector type, this is
11312   // better to leave at float as we have more freedom in the addressing mode for
11313   // those.
11314   if (VectorTy->isFPOrFPVectorTy())
11315     return false;
11316
11317   // If the index is unknown at compile time, this is very expensive to lower
11318   // and it is not possible to combine the store with the extract.
11319   if (!isa<ConstantInt>(Idx))
11320     return false;
11321
11322   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11323   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11324   // We can do a store + vector extract on any vector that fits perfectly in a D
11325   // or Q register.
11326   if (BitWidth == 64 || BitWidth == 128) {
11327     Cost = 0;
11328     return true;
11329   }
11330   return false;
11331 }
11332
11333 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11334                                          AtomicOrdering Ord) const {
11335   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11336   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11337   bool IsAcquire = isAtLeastAcquire(Ord);
11338
11339   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11340   // intrinsic must return {i32, i32} and we have to recombine them into a
11341   // single i64 here.
11342   if (ValTy->getPrimitiveSizeInBits() == 64) {
11343     Intrinsic::ID Int =
11344         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11345     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11346
11347     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11348     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11349
11350     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11351     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11352     if (!Subtarget->isLittle())
11353       std::swap (Lo, Hi);
11354     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11355     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11356     return Builder.CreateOr(
11357         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11358   }
11359
11360   Type *Tys[] = { Addr->getType() };
11361   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11362   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11363
11364   return Builder.CreateTruncOrBitCast(
11365       Builder.CreateCall(Ldrex, Addr),
11366       cast<PointerType>(Addr->getType())->getElementType());
11367 }
11368
11369 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11370                                                Value *Addr,
11371                                                AtomicOrdering Ord) const {
11372   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11373   bool IsRelease = isAtLeastRelease(Ord);
11374
11375   // Since the intrinsics must have legal type, the i64 intrinsics take two
11376   // parameters: "i32, i32". We must marshal Val into the appropriate form
11377   // before the call.
11378   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11379     Intrinsic::ID Int =
11380         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11381     Function *Strex = Intrinsic::getDeclaration(M, Int);
11382     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11383
11384     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11385     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11386     if (!Subtarget->isLittle())
11387       std::swap (Lo, Hi);
11388     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11389     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11390   }
11391
11392   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11393   Type *Tys[] = { Addr->getType() };
11394   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11395
11396   return Builder.CreateCall(
11397       Strex, {Builder.CreateZExtOrBitCast(
11398                   Val, Strex->getFunctionType()->getParamType(0)),
11399               Addr});
11400 }
11401
11402 /// \brief Lower an interleaved load into a vldN intrinsic.
11403 ///
11404 /// E.g. Lower an interleaved load (Factor = 2):
11405 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11406 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11407 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11408 ///
11409 ///      Into:
11410 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11411 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11412 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11413 bool ARMTargetLowering::lowerInterleavedLoad(
11414     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11415     ArrayRef<unsigned> Indices, unsigned Factor) const {
11416   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11417          "Invalid interleave factor");
11418   assert(!Shuffles.empty() && "Empty shufflevector input");
11419   assert(Shuffles.size() == Indices.size() &&
11420          "Unmatched number of shufflevectors and indices");
11421
11422   VectorType *VecTy = Shuffles[0]->getType();
11423   Type *EltTy = VecTy->getVectorElementType();
11424
11425   const DataLayout *DL = getDataLayout();
11426   unsigned VecSize = DL->getTypeAllocSizeInBits(VecTy);
11427   bool EltIs64Bits = DL->getTypeAllocSizeInBits(EltTy) == 64;
11428
11429   // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11430   // support i64/f64 element).
11431   if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11432     return false;
11433
11434   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11435   // load integer vectors first and then convert to pointer vectors.
11436   if (EltTy->isPointerTy())
11437     VecTy = VectorType::get(DL->getIntPtrType(EltTy),
11438                             VecTy->getVectorNumElements());
11439
11440   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11441                                             Intrinsic::arm_neon_vld3,
11442                                             Intrinsic::arm_neon_vld4};
11443
11444   Function *VldnFunc =
11445       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11446
11447   IRBuilder<> Builder(LI);
11448   SmallVector<Value *, 2> Ops;
11449
11450   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11451   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11452   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11453
11454   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11455
11456   // Replace uses of each shufflevector with the corresponding vector loaded
11457   // by ldN.
11458   for (unsigned i = 0; i < Shuffles.size(); i++) {
11459     ShuffleVectorInst *SV = Shuffles[i];
11460     unsigned Index = Indices[i];
11461
11462     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11463
11464     // Convert the integer vector to pointer vector if the element is pointer.
11465     if (EltTy->isPointerTy())
11466       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11467
11468     SV->replaceAllUsesWith(SubVec);
11469   }
11470
11471   return true;
11472 }
11473
11474 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11475 ///
11476 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11477 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11478                                    unsigned NumElts) {
11479   SmallVector<Constant *, 16> Mask;
11480   for (unsigned i = 0; i < NumElts; i++)
11481     Mask.push_back(Builder.getInt32(Start + i));
11482
11483   return ConstantVector::get(Mask);
11484 }
11485
11486 /// \brief Lower an interleaved store into a vstN intrinsic.
11487 ///
11488 /// E.g. Lower an interleaved store (Factor = 3):
11489 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11490 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11491 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11492 ///
11493 ///      Into:
11494 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11495 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11496 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11497 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11498 ///
11499 /// Note that the new shufflevectors will be removed and we'll only generate one
11500 /// vst3 instruction in CodeGen.
11501 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11502                                               ShuffleVectorInst *SVI,
11503                                               unsigned Factor) const {
11504   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11505          "Invalid interleave factor");
11506
11507   VectorType *VecTy = SVI->getType();
11508   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11509          "Invalid interleaved store");
11510
11511   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11512   Type *EltTy = VecTy->getVectorElementType();
11513   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11514
11515   const DataLayout *DL = getDataLayout();
11516   unsigned SubVecSize = DL->getTypeAllocSizeInBits(SubVecTy);
11517   bool EltIs64Bits = DL->getTypeAllocSizeInBits(EltTy) == 64;
11518
11519   // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11520   // doesn't support i64/f64 element).
11521   if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11522     return false;
11523
11524   Value *Op0 = SVI->getOperand(0);
11525   Value *Op1 = SVI->getOperand(1);
11526   IRBuilder<> Builder(SI);
11527
11528   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11529   // vectors to integer vectors.
11530   if (EltTy->isPointerTy()) {
11531     Type *IntTy = DL->getIntPtrType(EltTy);
11532
11533     // Convert to the corresponding integer vector.
11534     Type *IntVecTy =
11535         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11536     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11537     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11538
11539     SubVecTy = VectorType::get(IntTy, NumSubElts);
11540   }
11541
11542   static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11543                                        Intrinsic::arm_neon_vst3,
11544                                        Intrinsic::arm_neon_vst4};
11545   Function *VstNFunc = Intrinsic::getDeclaration(
11546       SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11547
11548   SmallVector<Value *, 6> Ops;
11549
11550   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11551   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11552
11553   // Split the shufflevector operands into sub vectors for the new vstN call.
11554   for (unsigned i = 0; i < Factor; i++)
11555     Ops.push_back(Builder.CreateShuffleVector(
11556         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11557
11558   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11559   Builder.CreateCall(VstNFunc, Ops);
11560   return true;
11561 }
11562
11563 enum HABaseType {
11564   HA_UNKNOWN = 0,
11565   HA_FLOAT,
11566   HA_DOUBLE,
11567   HA_VECT64,
11568   HA_VECT128
11569 };
11570
11571 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11572                                    uint64_t &Members) {
11573   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11574     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11575       uint64_t SubMembers = 0;
11576       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11577         return false;
11578       Members += SubMembers;
11579     }
11580   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11581     uint64_t SubMembers = 0;
11582     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11583       return false;
11584     Members += SubMembers * AT->getNumElements();
11585   } else if (Ty->isFloatTy()) {
11586     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11587       return false;
11588     Members = 1;
11589     Base = HA_FLOAT;
11590   } else if (Ty->isDoubleTy()) {
11591     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11592       return false;
11593     Members = 1;
11594     Base = HA_DOUBLE;
11595   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11596     Members = 1;
11597     switch (Base) {
11598     case HA_FLOAT:
11599     case HA_DOUBLE:
11600       return false;
11601     case HA_VECT64:
11602       return VT->getBitWidth() == 64;
11603     case HA_VECT128:
11604       return VT->getBitWidth() == 128;
11605     case HA_UNKNOWN:
11606       switch (VT->getBitWidth()) {
11607       case 64:
11608         Base = HA_VECT64;
11609         return true;
11610       case 128:
11611         Base = HA_VECT128;
11612         return true;
11613       default:
11614         return false;
11615       }
11616     }
11617   }
11618
11619   return (Members > 0 && Members <= 4);
11620 }
11621
11622 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11623 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11624 /// passing according to AAPCS rules.
11625 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11626     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11627   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11628       CallingConv::ARM_AAPCS_VFP)
11629     return false;
11630
11631   HABaseType Base = HA_UNKNOWN;
11632   uint64_t Members = 0;
11633   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11634   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11635
11636   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11637   return IsHA || IsIntArray;
11638 }