Fix __builtin_setjmp in combination with sjlj exception handling.
[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 does not have single instruction CTTZ for vectors.
547     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
548     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
549     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
550     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
551
552     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
553     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
554     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
555     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
556
557     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
558     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
559     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
560     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
561
562     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
563     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
564     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
565     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
566
567     // NEON only has FMA instructions as of VFP4.
568     if (!Subtarget->hasVFP4()) {
569       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
570       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
571     }
572
573     setTargetDAGCombine(ISD::INTRINSIC_VOID);
574     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
575     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
576     setTargetDAGCombine(ISD::SHL);
577     setTargetDAGCombine(ISD::SRL);
578     setTargetDAGCombine(ISD::SRA);
579     setTargetDAGCombine(ISD::SIGN_EXTEND);
580     setTargetDAGCombine(ISD::ZERO_EXTEND);
581     setTargetDAGCombine(ISD::ANY_EXTEND);
582     setTargetDAGCombine(ISD::SELECT_CC);
583     setTargetDAGCombine(ISD::BUILD_VECTOR);
584     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
585     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
586     setTargetDAGCombine(ISD::STORE);
587     setTargetDAGCombine(ISD::FP_TO_SINT);
588     setTargetDAGCombine(ISD::FP_TO_UINT);
589     setTargetDAGCombine(ISD::FDIV);
590     setTargetDAGCombine(ISD::LOAD);
591
592     // It is legal to extload from v4i8 to v4i16 or v4i32.
593     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
594                    MVT::v2i32}) {
595       for (MVT VT : MVT::integer_vector_valuetypes()) {
596         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
597         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
598         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
599       }
600     }
601   }
602
603   // ARM and Thumb2 support UMLAL/SMLAL.
604   if (!Subtarget->isThumb1Only())
605     setTargetDAGCombine(ISD::ADDC);
606
607   if (Subtarget->isFPOnlySP()) {
608     // When targetting a floating-point unit with only single-precision
609     // operations, f64 is legal for the few double-precision instructions which
610     // are present However, no double-precision operations other than moves,
611     // loads and stores are provided by the hardware.
612     setOperationAction(ISD::FADD,       MVT::f64, Expand);
613     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
614     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
615     setOperationAction(ISD::FMA,        MVT::f64, Expand);
616     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
617     setOperationAction(ISD::FREM,       MVT::f64, Expand);
618     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
619     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
620     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
621     setOperationAction(ISD::FABS,       MVT::f64, Expand);
622     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
623     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
624     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
625     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
626     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
627     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
628     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
629     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
630     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
631     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
632     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
633     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
634     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
635     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
636     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
637     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
638     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
639     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
640     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
641     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
642     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
643     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
644     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
645   }
646
647   computeRegisterProperties(Subtarget->getRegisterInfo());
648
649   // ARM does not have floating-point extending loads.
650   for (MVT VT : MVT::fp_valuetypes()) {
651     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
652     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
653   }
654
655   // ... or truncating stores
656   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
657   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
658   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
659
660   // ARM does not have i1 sign extending load.
661   for (MVT VT : MVT::integer_valuetypes())
662     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
663
664   // ARM supports all 4 flavors of integer indexed load / store.
665   if (!Subtarget->isThumb1Only()) {
666     for (unsigned im = (unsigned)ISD::PRE_INC;
667          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
668       setIndexedLoadAction(im,  MVT::i1,  Legal);
669       setIndexedLoadAction(im,  MVT::i8,  Legal);
670       setIndexedLoadAction(im,  MVT::i16, Legal);
671       setIndexedLoadAction(im,  MVT::i32, Legal);
672       setIndexedStoreAction(im, MVT::i1,  Legal);
673       setIndexedStoreAction(im, MVT::i8,  Legal);
674       setIndexedStoreAction(im, MVT::i16, Legal);
675       setIndexedStoreAction(im, MVT::i32, Legal);
676     }
677   }
678
679   setOperationAction(ISD::SADDO, MVT::i32, Custom);
680   setOperationAction(ISD::UADDO, MVT::i32, Custom);
681   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
682   setOperationAction(ISD::USUBO, MVT::i32, Custom);
683
684   // i64 operation support.
685   setOperationAction(ISD::MUL,     MVT::i64, Expand);
686   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
687   if (Subtarget->isThumb1Only()) {
688     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
689     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
690   }
691   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
692       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
693     setOperationAction(ISD::MULHS, MVT::i32, Expand);
694
695   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
696   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
697   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
698   setOperationAction(ISD::SRL,       MVT::i64, Custom);
699   setOperationAction(ISD::SRA,       MVT::i64, Custom);
700
701   if (!Subtarget->isThumb1Only()) {
702     // FIXME: We should do this for Thumb1 as well.
703     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
704     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
705     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
706     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
707   }
708
709   // ARM does not have ROTL.
710   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
711   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
712   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
713   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
714     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
715
716   // These just redirect to CTTZ and CTLZ on ARM.
717   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
718   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
719
720   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
721
722   // Only ARMv6 has BSWAP.
723   if (!Subtarget->hasV6Ops())
724     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
725
726   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
727       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
728     // These are expanded into libcalls if the cpu doesn't have HW divider.
729     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
730     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
731   }
732
733   // FIXME: Also set divmod for SREM on EABI
734   setOperationAction(ISD::SREM,  MVT::i32, Expand);
735   setOperationAction(ISD::UREM,  MVT::i32, Expand);
736   // Register based DivRem for AEABI (RTABI 4.2)
737   if (Subtarget->isTargetAEABI()) {
738     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
739     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
740     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
741     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
742     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
743     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
744     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
745     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
746
747     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
748     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
749     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
750     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
751     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
752     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
753     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
754     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
755
756     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
757     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
758   } else {
759     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
760     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
761   }
762
763   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
764   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
765   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
766   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
767   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
768
769   setOperationAction(ISD::TRAP, MVT::Other, Legal);
770
771   // Use the default implementation.
772   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
773   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
774   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
775   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
776   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
777   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
778
779   if (!Subtarget->isTargetMachO()) {
780     // Non-MachO platforms may return values in these registers via the
781     // personality function.
782     setExceptionPointerRegister(ARM::R0);
783     setExceptionSelectorRegister(ARM::R1);
784   }
785
786   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
787     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
788   else
789     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
790
791   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
792   // the default expansion. If we are targeting a single threaded system,
793   // then set them all for expand so we can lower them later into their
794   // non-atomic form.
795   if (TM.Options.ThreadModel == ThreadModel::Single)
796     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
797   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
798     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
799     // to ldrex/strex loops already.
800     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
801
802     // On v8, we have particularly efficient implementations of atomic fences
803     // if they can be combined with nearby atomic loads and stores.
804     if (!Subtarget->hasV8Ops()) {
805       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
806       setInsertFencesForAtomic(true);
807     }
808   } else {
809     // If there's anything we can use as a barrier, go through custom lowering
810     // for ATOMIC_FENCE.
811     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
812                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
813
814     // Set them all for expansion, which will force libcalls.
815     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
816     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
817     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
818     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
819     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
820     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
821     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
822     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
823     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
824     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
825     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
826     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
827     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
828     // Unordered/Monotonic case.
829     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
830     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
831   }
832
833   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
834
835   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
836   if (!Subtarget->hasV6Ops()) {
837     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
838     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
839   }
840   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
841
842   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
843       !Subtarget->isThumb1Only()) {
844     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
845     // iff target supports vfp2.
846     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
847     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
848   }
849
850   // We want to custom lower some of our intrinsics.
851   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
852   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
853   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
854   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
855   if (Subtarget->isTargetDarwin())
856     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
857
858   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
859   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
860   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
861   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
862   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
863   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
864   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
865   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
866   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
867
868   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
869   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
870   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
871   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
872   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
873
874   // We don't support sin/cos/fmod/copysign/pow
875   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
876   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
877   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
878   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
879   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
880   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
881   setOperationAction(ISD::FREM,      MVT::f64, Expand);
882   setOperationAction(ISD::FREM,      MVT::f32, Expand);
883   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
884       !Subtarget->isThumb1Only()) {
885     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
886     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
887   }
888   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
889   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
890
891   if (!Subtarget->hasVFP4()) {
892     setOperationAction(ISD::FMA, MVT::f64, Expand);
893     setOperationAction(ISD::FMA, MVT::f32, Expand);
894   }
895
896   // Various VFP goodness
897   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
898     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
899     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
900       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
901       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
902     }
903
904     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
905     if (!Subtarget->hasFP16()) {
906       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
907       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
908     }
909   }
910
911   // Combine sin / cos into one node or libcall if possible.
912   if (Subtarget->hasSinCos()) {
913     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
914     setLibcallName(RTLIB::SINCOS_F64, "sincos");
915     if (Subtarget->getTargetTriple().isiOS()) {
916       // For iOS, we don't want to the normal expansion of a libcall to
917       // sincos. We want to issue a libcall to __sincos_stret.
918       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
919       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
920     }
921   }
922
923   // FP-ARMv8 implements a lot of rounding-like FP operations.
924   if (Subtarget->hasFPARMv8()) {
925     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
926     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
927     setOperationAction(ISD::FROUND, MVT::f32, Legal);
928     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
929     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
930     setOperationAction(ISD::FRINT, MVT::f32, Legal);
931     if (!Subtarget->isFPOnlySP()) {
932       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
933       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
934       setOperationAction(ISD::FROUND, MVT::f64, Legal);
935       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
936       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
937       setOperationAction(ISD::FRINT, MVT::f64, Legal);
938     }
939   }
940   // We have target-specific dag combine patterns for the following nodes:
941   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
942   setTargetDAGCombine(ISD::ADD);
943   setTargetDAGCombine(ISD::SUB);
944   setTargetDAGCombine(ISD::MUL);
945   setTargetDAGCombine(ISD::AND);
946   setTargetDAGCombine(ISD::OR);
947   setTargetDAGCombine(ISD::XOR);
948
949   if (Subtarget->hasV6Ops())
950     setTargetDAGCombine(ISD::SRL);
951
952   setStackPointerRegisterToSaveRestore(ARM::SP);
953
954   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
955       !Subtarget->hasVFP2())
956     setSchedulingPreference(Sched::RegPressure);
957   else
958     setSchedulingPreference(Sched::Hybrid);
959
960   //// temporary - rewrite interface to use type
961   MaxStoresPerMemset = 8;
962   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
963   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
964   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
965   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
966   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
967
968   // On ARM arguments smaller than 4 bytes are extended, so all arguments
969   // are at least 4 bytes aligned.
970   setMinStackArgumentAlignment(4);
971
972   // Prefer likely predicted branches to selects on out-of-order cores.
973   PredictableSelectIsExpensive = Subtarget->isLikeA9();
974
975   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
976 }
977
978 bool ARMTargetLowering::useSoftFloat() const {
979   return Subtarget->useSoftFloat();
980 }
981
982 // FIXME: It might make sense to define the representative register class as the
983 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
984 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
985 // SPR's representative would be DPR_VFP2. This should work well if register
986 // pressure tracking were modified such that a register use would increment the
987 // pressure of the register class's representative and all of it's super
988 // classes' representatives transitively. We have not implemented this because
989 // of the difficulty prior to coalescing of modeling operand register classes
990 // due to the common occurrence of cross class copies and subregister insertions
991 // and extractions.
992 std::pair<const TargetRegisterClass *, uint8_t>
993 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
994                                            MVT VT) const {
995   const TargetRegisterClass *RRC = nullptr;
996   uint8_t Cost = 1;
997   switch (VT.SimpleTy) {
998   default:
999     return TargetLowering::findRepresentativeClass(TRI, VT);
1000   // Use DPR as representative register class for all floating point
1001   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1002   // the cost is 1 for both f32 and f64.
1003   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1004   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1005     RRC = &ARM::DPRRegClass;
1006     // When NEON is used for SP, only half of the register file is available
1007     // because operations that define both SP and DP results will be constrained
1008     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1009     // coalescing by double-counting the SP regs. See the FIXME above.
1010     if (Subtarget->useNEONForSinglePrecisionFP())
1011       Cost = 2;
1012     break;
1013   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1014   case MVT::v4f32: case MVT::v2f64:
1015     RRC = &ARM::DPRRegClass;
1016     Cost = 2;
1017     break;
1018   case MVT::v4i64:
1019     RRC = &ARM::DPRRegClass;
1020     Cost = 4;
1021     break;
1022   case MVT::v8i64:
1023     RRC = &ARM::DPRRegClass;
1024     Cost = 8;
1025     break;
1026   }
1027   return std::make_pair(RRC, Cost);
1028 }
1029
1030 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1031   switch ((ARMISD::NodeType)Opcode) {
1032   case ARMISD::FIRST_NUMBER:  break;
1033   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1034   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1035   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1036   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1037   case ARMISD::CALL:          return "ARMISD::CALL";
1038   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1039   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1040   case ARMISD::tCALL:         return "ARMISD::tCALL";
1041   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1042   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1043   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1044   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1045   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1046   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1047   case ARMISD::CMP:           return "ARMISD::CMP";
1048   case ARMISD::CMN:           return "ARMISD::CMN";
1049   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1050   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1051   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1052   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1053   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1054
1055   case ARMISD::CMOV:          return "ARMISD::CMOV";
1056
1057   case ARMISD::RBIT:          return "ARMISD::RBIT";
1058
1059   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1060   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1061   case ARMISD::RRX:           return "ARMISD::RRX";
1062
1063   case ARMISD::ADDC:          return "ARMISD::ADDC";
1064   case ARMISD::ADDE:          return "ARMISD::ADDE";
1065   case ARMISD::SUBC:          return "ARMISD::SUBC";
1066   case ARMISD::SUBE:          return "ARMISD::SUBE";
1067
1068   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1069   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1070
1071   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1072   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1073   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1074
1075   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1076
1077   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1078
1079   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1080
1081   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1082
1083   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1084
1085   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1086
1087   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1088   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1089   case ARMISD::VCGE:          return "ARMISD::VCGE";
1090   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1091   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1092   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1093   case ARMISD::VCGT:          return "ARMISD::VCGT";
1094   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1095   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1096   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1097   case ARMISD::VTST:          return "ARMISD::VTST";
1098
1099   case ARMISD::VSHL:          return "ARMISD::VSHL";
1100   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1101   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1102   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1103   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1104   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1105   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1106   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1107   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1108   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1109   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1110   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1111   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1112   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1113   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1114   case ARMISD::VSLI:          return "ARMISD::VSLI";
1115   case ARMISD::VSRI:          return "ARMISD::VSRI";
1116   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1117   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1118   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1119   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1120   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1121   case ARMISD::VDUP:          return "ARMISD::VDUP";
1122   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1123   case ARMISD::VEXT:          return "ARMISD::VEXT";
1124   case ARMISD::VREV64:        return "ARMISD::VREV64";
1125   case ARMISD::VREV32:        return "ARMISD::VREV32";
1126   case ARMISD::VREV16:        return "ARMISD::VREV16";
1127   case ARMISD::VZIP:          return "ARMISD::VZIP";
1128   case ARMISD::VUZP:          return "ARMISD::VUZP";
1129   case ARMISD::VTRN:          return "ARMISD::VTRN";
1130   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1131   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1132   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1133   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1134   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1135   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1136   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1137   case ARMISD::FMAX:          return "ARMISD::FMAX";
1138   case ARMISD::FMIN:          return "ARMISD::FMIN";
1139   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1140   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1141   case ARMISD::BFI:           return "ARMISD::BFI";
1142   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1143   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1144   case ARMISD::VBSL:          return "ARMISD::VBSL";
1145   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1146   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1147   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1148   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1149   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1150   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1151   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1152   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1153   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1154   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1155   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1156   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1157   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1158   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1159   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1160   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1161   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1162   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1163   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1164   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1165   }
1166   return nullptr;
1167 }
1168
1169 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1170                                           EVT VT) const {
1171   if (!VT.isVector())
1172     return getPointerTy(DL);
1173   return VT.changeVectorElementTypeToInteger();
1174 }
1175
1176 /// getRegClassFor - Return the register class that should be used for the
1177 /// specified value type.
1178 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1179   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1180   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1181   // load / store 4 to 8 consecutive D registers.
1182   if (Subtarget->hasNEON()) {
1183     if (VT == MVT::v4i64)
1184       return &ARM::QQPRRegClass;
1185     if (VT == MVT::v8i64)
1186       return &ARM::QQQQPRRegClass;
1187   }
1188   return TargetLowering::getRegClassFor(VT);
1189 }
1190
1191 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1192 // source/dest is aligned and the copy size is large enough. We therefore want
1193 // to align such objects passed to memory intrinsics.
1194 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1195                                                unsigned &PrefAlign) const {
1196   if (!isa<MemIntrinsic>(CI))
1197     return false;
1198   MinSize = 8;
1199   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1200   // cycle faster than 4-byte aligned LDM.
1201   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1202   return true;
1203 }
1204
1205 // Create a fast isel object.
1206 FastISel *
1207 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1208                                   const TargetLibraryInfo *libInfo) const {
1209   return ARM::createFastISel(funcInfo, libInfo);
1210 }
1211
1212 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1213   unsigned NumVals = N->getNumValues();
1214   if (!NumVals)
1215     return Sched::RegPressure;
1216
1217   for (unsigned i = 0; i != NumVals; ++i) {
1218     EVT VT = N->getValueType(i);
1219     if (VT == MVT::Glue || VT == MVT::Other)
1220       continue;
1221     if (VT.isFloatingPoint() || VT.isVector())
1222       return Sched::ILP;
1223   }
1224
1225   if (!N->isMachineOpcode())
1226     return Sched::RegPressure;
1227
1228   // Load are scheduled for latency even if there instruction itinerary
1229   // is not available.
1230   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1231   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1232
1233   if (MCID.getNumDefs() == 0)
1234     return Sched::RegPressure;
1235   if (!Itins->isEmpty() &&
1236       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1237     return Sched::ILP;
1238
1239   return Sched::RegPressure;
1240 }
1241
1242 //===----------------------------------------------------------------------===//
1243 // Lowering Code
1244 //===----------------------------------------------------------------------===//
1245
1246 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1247 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1248   switch (CC) {
1249   default: llvm_unreachable("Unknown condition code!");
1250   case ISD::SETNE:  return ARMCC::NE;
1251   case ISD::SETEQ:  return ARMCC::EQ;
1252   case ISD::SETGT:  return ARMCC::GT;
1253   case ISD::SETGE:  return ARMCC::GE;
1254   case ISD::SETLT:  return ARMCC::LT;
1255   case ISD::SETLE:  return ARMCC::LE;
1256   case ISD::SETUGT: return ARMCC::HI;
1257   case ISD::SETUGE: return ARMCC::HS;
1258   case ISD::SETULT: return ARMCC::LO;
1259   case ISD::SETULE: return ARMCC::LS;
1260   }
1261 }
1262
1263 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1264 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1265                         ARMCC::CondCodes &CondCode2) {
1266   CondCode2 = ARMCC::AL;
1267   switch (CC) {
1268   default: llvm_unreachable("Unknown FP condition!");
1269   case ISD::SETEQ:
1270   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1271   case ISD::SETGT:
1272   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1273   case ISD::SETGE:
1274   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1275   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1276   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1277   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1278   case ISD::SETO:   CondCode = ARMCC::VC; break;
1279   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1280   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1281   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1282   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1283   case ISD::SETLT:
1284   case ISD::SETULT: CondCode = ARMCC::LT; break;
1285   case ISD::SETLE:
1286   case ISD::SETULE: CondCode = ARMCC::LE; break;
1287   case ISD::SETNE:
1288   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1289   }
1290 }
1291
1292 //===----------------------------------------------------------------------===//
1293 //                      Calling Convention Implementation
1294 //===----------------------------------------------------------------------===//
1295
1296 #include "ARMGenCallingConv.inc"
1297
1298 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1299 /// account presence of floating point hardware and calling convention
1300 /// limitations, such as support for variadic functions.
1301 CallingConv::ID
1302 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1303                                            bool isVarArg) const {
1304   switch (CC) {
1305   default:
1306     llvm_unreachable("Unsupported calling convention");
1307   case CallingConv::ARM_AAPCS:
1308   case CallingConv::ARM_APCS:
1309   case CallingConv::GHC:
1310     return CC;
1311   case CallingConv::ARM_AAPCS_VFP:
1312     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1313   case CallingConv::C:
1314     if (!Subtarget->isAAPCS_ABI())
1315       return CallingConv::ARM_APCS;
1316     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1317              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1318              !isVarArg)
1319       return CallingConv::ARM_AAPCS_VFP;
1320     else
1321       return CallingConv::ARM_AAPCS;
1322   case CallingConv::Fast:
1323     if (!Subtarget->isAAPCS_ABI()) {
1324       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1325         return CallingConv::Fast;
1326       return CallingConv::ARM_APCS;
1327     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1328       return CallingConv::ARM_AAPCS_VFP;
1329     else
1330       return CallingConv::ARM_AAPCS;
1331   }
1332 }
1333
1334 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1335 /// CallingConvention.
1336 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1337                                                  bool Return,
1338                                                  bool isVarArg) const {
1339   switch (getEffectiveCallingConv(CC, isVarArg)) {
1340   default:
1341     llvm_unreachable("Unsupported calling convention");
1342   case CallingConv::ARM_APCS:
1343     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1344   case CallingConv::ARM_AAPCS:
1345     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1346   case CallingConv::ARM_AAPCS_VFP:
1347     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1348   case CallingConv::Fast:
1349     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1350   case CallingConv::GHC:
1351     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1352   }
1353 }
1354
1355 /// LowerCallResult - Lower the result values of a call into the
1356 /// appropriate copies out of appropriate physical registers.
1357 SDValue
1358 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1359                                    CallingConv::ID CallConv, bool isVarArg,
1360                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1361                                    SDLoc dl, SelectionDAG &DAG,
1362                                    SmallVectorImpl<SDValue> &InVals,
1363                                    bool isThisReturn, SDValue ThisVal) const {
1364
1365   // Assign locations to each value returned by this call.
1366   SmallVector<CCValAssign, 16> RVLocs;
1367   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1368                     *DAG.getContext(), Call);
1369   CCInfo.AnalyzeCallResult(Ins,
1370                            CCAssignFnForNode(CallConv, /* Return*/ true,
1371                                              isVarArg));
1372
1373   // Copy all of the result registers out of their specified physreg.
1374   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1375     CCValAssign VA = RVLocs[i];
1376
1377     // Pass 'this' value directly from the argument to return value, to avoid
1378     // reg unit interference
1379     if (i == 0 && isThisReturn) {
1380       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1381              "unexpected return calling convention register assignment");
1382       InVals.push_back(ThisVal);
1383       continue;
1384     }
1385
1386     SDValue Val;
1387     if (VA.needsCustom()) {
1388       // Handle f64 or half of a v2f64.
1389       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1390                                       InFlag);
1391       Chain = Lo.getValue(1);
1392       InFlag = Lo.getValue(2);
1393       VA = RVLocs[++i]; // skip ahead to next loc
1394       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1395                                       InFlag);
1396       Chain = Hi.getValue(1);
1397       InFlag = Hi.getValue(2);
1398       if (!Subtarget->isLittle())
1399         std::swap (Lo, Hi);
1400       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1401
1402       if (VA.getLocVT() == MVT::v2f64) {
1403         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1404         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1405                           DAG.getConstant(0, dl, MVT::i32));
1406
1407         VA = RVLocs[++i]; // skip ahead to next loc
1408         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1409         Chain = Lo.getValue(1);
1410         InFlag = Lo.getValue(2);
1411         VA = RVLocs[++i]; // skip ahead to next loc
1412         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1413         Chain = Hi.getValue(1);
1414         InFlag = Hi.getValue(2);
1415         if (!Subtarget->isLittle())
1416           std::swap (Lo, Hi);
1417         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1418         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1419                           DAG.getConstant(1, dl, MVT::i32));
1420       }
1421     } else {
1422       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1423                                InFlag);
1424       Chain = Val.getValue(1);
1425       InFlag = Val.getValue(2);
1426     }
1427
1428     switch (VA.getLocInfo()) {
1429     default: llvm_unreachable("Unknown loc info!");
1430     case CCValAssign::Full: break;
1431     case CCValAssign::BCvt:
1432       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1433       break;
1434     }
1435
1436     InVals.push_back(Val);
1437   }
1438
1439   return Chain;
1440 }
1441
1442 /// LowerMemOpCallTo - Store the argument to the stack.
1443 SDValue
1444 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1445                                     SDValue StackPtr, SDValue Arg,
1446                                     SDLoc dl, SelectionDAG &DAG,
1447                                     const CCValAssign &VA,
1448                                     ISD::ArgFlagsTy Flags) const {
1449   unsigned LocMemOffset = VA.getLocMemOffset();
1450   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1451   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1452                        StackPtr, PtrOff);
1453   return DAG.getStore(Chain, dl, Arg, PtrOff,
1454                       MachinePointerInfo::getStack(LocMemOffset),
1455                       false, false, 0);
1456 }
1457
1458 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1459                                          SDValue Chain, SDValue &Arg,
1460                                          RegsToPassVector &RegsToPass,
1461                                          CCValAssign &VA, CCValAssign &NextVA,
1462                                          SDValue &StackPtr,
1463                                          SmallVectorImpl<SDValue> &MemOpChains,
1464                                          ISD::ArgFlagsTy Flags) const {
1465
1466   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1467                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1468   unsigned id = Subtarget->isLittle() ? 0 : 1;
1469   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1470
1471   if (NextVA.isRegLoc())
1472     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1473   else {
1474     assert(NextVA.isMemLoc());
1475     if (!StackPtr.getNode())
1476       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1477                                     getPointerTy(DAG.getDataLayout()));
1478
1479     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1480                                            dl, DAG, NextVA,
1481                                            Flags));
1482   }
1483 }
1484
1485 /// LowerCall - Lowering a call into a callseq_start <-
1486 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1487 /// nodes.
1488 SDValue
1489 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1490                              SmallVectorImpl<SDValue> &InVals) const {
1491   SelectionDAG &DAG                     = CLI.DAG;
1492   SDLoc &dl                             = CLI.DL;
1493   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1494   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1495   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1496   SDValue Chain                         = CLI.Chain;
1497   SDValue Callee                        = CLI.Callee;
1498   bool &isTailCall                      = CLI.IsTailCall;
1499   CallingConv::ID CallConv              = CLI.CallConv;
1500   bool doesNotRet                       = CLI.DoesNotReturn;
1501   bool isVarArg                         = CLI.IsVarArg;
1502
1503   MachineFunction &MF = DAG.getMachineFunction();
1504   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1505   bool isThisReturn   = false;
1506   bool isSibCall      = false;
1507   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1508
1509   // Disable tail calls if they're not supported.
1510   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1511     isTailCall = false;
1512
1513   if (isTailCall) {
1514     // Check if it's really possible to do a tail call.
1515     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1516                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1517                                                    Outs, OutVals, Ins, DAG);
1518     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1519       report_fatal_error("failed to perform tail call elimination on a call "
1520                          "site marked musttail");
1521     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1522     // detected sibcalls.
1523     if (isTailCall) {
1524       ++NumTailCalls;
1525       isSibCall = true;
1526     }
1527   }
1528
1529   // Analyze operands of the call, assigning locations to each operand.
1530   SmallVector<CCValAssign, 16> ArgLocs;
1531   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1532                     *DAG.getContext(), Call);
1533   CCInfo.AnalyzeCallOperands(Outs,
1534                              CCAssignFnForNode(CallConv, /* Return*/ false,
1535                                                isVarArg));
1536
1537   // Get a count of how many bytes are to be pushed on the stack.
1538   unsigned NumBytes = CCInfo.getNextStackOffset();
1539
1540   // For tail calls, memory operands are available in our caller's stack.
1541   if (isSibCall)
1542     NumBytes = 0;
1543
1544   // Adjust the stack pointer for the new arguments...
1545   // These operations are automatically eliminated by the prolog/epilog pass
1546   if (!isSibCall)
1547     Chain = DAG.getCALLSEQ_START(Chain,
1548                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1549
1550   SDValue StackPtr =
1551       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1552
1553   RegsToPassVector RegsToPass;
1554   SmallVector<SDValue, 8> MemOpChains;
1555
1556   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1557   // of tail call optimization, arguments are handled later.
1558   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1559        i != e;
1560        ++i, ++realArgIdx) {
1561     CCValAssign &VA = ArgLocs[i];
1562     SDValue Arg = OutVals[realArgIdx];
1563     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1564     bool isByVal = Flags.isByVal();
1565
1566     // Promote the value if needed.
1567     switch (VA.getLocInfo()) {
1568     default: llvm_unreachable("Unknown loc info!");
1569     case CCValAssign::Full: break;
1570     case CCValAssign::SExt:
1571       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1572       break;
1573     case CCValAssign::ZExt:
1574       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1575       break;
1576     case CCValAssign::AExt:
1577       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1578       break;
1579     case CCValAssign::BCvt:
1580       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1581       break;
1582     }
1583
1584     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1585     if (VA.needsCustom()) {
1586       if (VA.getLocVT() == MVT::v2f64) {
1587         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1588                                   DAG.getConstant(0, dl, MVT::i32));
1589         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1590                                   DAG.getConstant(1, dl, MVT::i32));
1591
1592         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1593                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1594
1595         VA = ArgLocs[++i]; // skip ahead to next loc
1596         if (VA.isRegLoc()) {
1597           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1598                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1599         } else {
1600           assert(VA.isMemLoc());
1601
1602           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1603                                                  dl, DAG, VA, Flags));
1604         }
1605       } else {
1606         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1607                          StackPtr, MemOpChains, Flags);
1608       }
1609     } else if (VA.isRegLoc()) {
1610       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1611         assert(VA.getLocVT() == MVT::i32 &&
1612                "unexpected calling convention register assignment");
1613         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1614                "unexpected use of 'returned'");
1615         isThisReturn = true;
1616       }
1617       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1618     } else if (isByVal) {
1619       assert(VA.isMemLoc());
1620       unsigned offset = 0;
1621
1622       // True if this byval aggregate will be split between registers
1623       // and memory.
1624       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1625       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1626
1627       if (CurByValIdx < ByValArgsCount) {
1628
1629         unsigned RegBegin, RegEnd;
1630         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1631
1632         EVT PtrVT =
1633             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1634         unsigned int i, j;
1635         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1636           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1637           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1638           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1639                                      MachinePointerInfo(),
1640                                      false, false, false,
1641                                      DAG.InferPtrAlignment(AddArg));
1642           MemOpChains.push_back(Load.getValue(1));
1643           RegsToPass.push_back(std::make_pair(j, Load));
1644         }
1645
1646         // If parameter size outsides register area, "offset" value
1647         // helps us to calculate stack slot for remained part properly.
1648         offset = RegEnd - RegBegin;
1649
1650         CCInfo.nextInRegsParam();
1651       }
1652
1653       if (Flags.getByValSize() > 4*offset) {
1654         auto PtrVT = getPointerTy(DAG.getDataLayout());
1655         unsigned LocMemOffset = VA.getLocMemOffset();
1656         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1657         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1658         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1659         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1660         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1661                                            MVT::i32);
1662         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1663                                             MVT::i32);
1664
1665         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1666         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1667         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1668                                           Ops));
1669       }
1670     } else if (!isSibCall) {
1671       assert(VA.isMemLoc());
1672
1673       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1674                                              dl, DAG, VA, Flags));
1675     }
1676   }
1677
1678   if (!MemOpChains.empty())
1679     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1680
1681   // Build a sequence of copy-to-reg nodes chained together with token chain
1682   // and flag operands which copy the outgoing args into the appropriate regs.
1683   SDValue InFlag;
1684   // Tail call byval lowering might overwrite argument registers so in case of
1685   // tail call optimization the copies to registers are lowered later.
1686   if (!isTailCall)
1687     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1688       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1689                                RegsToPass[i].second, InFlag);
1690       InFlag = Chain.getValue(1);
1691     }
1692
1693   // For tail calls lower the arguments to the 'real' stack slot.
1694   if (isTailCall) {
1695     // Force all the incoming stack arguments to be loaded from the stack
1696     // before any new outgoing arguments are stored to the stack, because the
1697     // outgoing stack slots may alias the incoming argument stack slots, and
1698     // the alias isn't otherwise explicit. This is slightly more conservative
1699     // than necessary, because it means that each store effectively depends
1700     // on every argument instead of just those arguments it would clobber.
1701
1702     // Do not flag preceding copytoreg stuff together with the following stuff.
1703     InFlag = SDValue();
1704     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1705       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1706                                RegsToPass[i].second, InFlag);
1707       InFlag = Chain.getValue(1);
1708     }
1709     InFlag = SDValue();
1710   }
1711
1712   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1713   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1714   // node so that legalize doesn't hack it.
1715   bool isDirect = false;
1716   bool isARMFunc = false;
1717   bool isLocalARMFunc = false;
1718   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1719   auto PtrVt = getPointerTy(DAG.getDataLayout());
1720
1721   if (Subtarget->genLongCalls()) {
1722     assert((Subtarget->isTargetWindows() ||
1723             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1724            "long-calls with non-static relocation model!");
1725     // Handle a global address or an external symbol. If it's not one of
1726     // those, the target's already in a register, so we don't need to do
1727     // anything extra.
1728     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1729       const GlobalValue *GV = G->getGlobal();
1730       // Create a constant pool entry for the callee address
1731       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1732       ARMConstantPoolValue *CPV =
1733         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1734
1735       // Get the address of the callee into a register
1736       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1737       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1738       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1739                            MachinePointerInfo::getConstantPool(), false, false,
1740                            false, 0);
1741     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1742       const char *Sym = S->getSymbol();
1743
1744       // Create a constant pool entry for the callee address
1745       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1746       ARMConstantPoolValue *CPV =
1747         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1748                                       ARMPCLabelIndex, 0);
1749       // Get the address of the callee into a register
1750       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1751       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1752       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1753                            MachinePointerInfo::getConstantPool(), false, false,
1754                            false, 0);
1755     }
1756   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1757     const GlobalValue *GV = G->getGlobal();
1758     isDirect = true;
1759     bool isDef = GV->isStrongDefinitionForLinker();
1760     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1761                    getTargetMachine().getRelocationModel() != Reloc::Static;
1762     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1763     // ARM call to a local ARM function is predicable.
1764     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1765     // tBX takes a register source operand.
1766     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1767       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1768       Callee = DAG.getNode(
1769           ARMISD::WrapperPIC, dl, PtrVt,
1770           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1771       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1772                            MachinePointerInfo::getGOT(), false, false, true, 0);
1773     } else if (Subtarget->isTargetCOFF()) {
1774       assert(Subtarget->isTargetWindows() &&
1775              "Windows is the only supported COFF target");
1776       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1777                                  ? ARMII::MO_DLLIMPORT
1778                                  : ARMII::MO_NO_FLAG;
1779       Callee =
1780           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1781       if (GV->hasDLLImportStorageClass())
1782         Callee =
1783             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1784                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1785                         MachinePointerInfo::getGOT(), false, false, false, 0);
1786     } else {
1787       // On ELF targets for PIC code, direct calls should go through the PLT
1788       unsigned OpFlags = 0;
1789       if (Subtarget->isTargetELF() &&
1790           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1791         OpFlags = ARMII::MO_PLT;
1792       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1793     }
1794   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1795     isDirect = true;
1796     bool isStub = Subtarget->isTargetMachO() &&
1797                   getTargetMachine().getRelocationModel() != Reloc::Static;
1798     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1799     // tBX takes a register source operand.
1800     const char *Sym = S->getSymbol();
1801     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1802       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1803       ARMConstantPoolValue *CPV =
1804         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1805                                       ARMPCLabelIndex, 4);
1806       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1807       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1808       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1809                            MachinePointerInfo::getConstantPool(), false, false,
1810                            false, 0);
1811       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1812       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1813     } else {
1814       unsigned OpFlags = 0;
1815       // On ELF targets for PIC code, direct calls should go through the PLT
1816       if (Subtarget->isTargetELF() &&
1817                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1818         OpFlags = ARMII::MO_PLT;
1819       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1820     }
1821   }
1822
1823   // FIXME: handle tail calls differently.
1824   unsigned CallOpc;
1825   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1826   if (Subtarget->isThumb()) {
1827     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1828       CallOpc = ARMISD::CALL_NOLINK;
1829     else
1830       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1831   } else {
1832     if (!isDirect && !Subtarget->hasV5TOps())
1833       CallOpc = ARMISD::CALL_NOLINK;
1834     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1835                // Emit regular call when code size is the priority
1836                !HasMinSizeAttr)
1837       // "mov lr, pc; b _foo" to avoid confusing the RSP
1838       CallOpc = ARMISD::CALL_NOLINK;
1839     else
1840       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1841   }
1842
1843   std::vector<SDValue> Ops;
1844   Ops.push_back(Chain);
1845   Ops.push_back(Callee);
1846
1847   // Add argument registers to the end of the list so that they are known live
1848   // into the call.
1849   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1850     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1851                                   RegsToPass[i].second.getValueType()));
1852
1853   // Add a register mask operand representing the call-preserved registers.
1854   if (!isTailCall) {
1855     const uint32_t *Mask;
1856     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1857     if (isThisReturn) {
1858       // For 'this' returns, use the R0-preserving mask if applicable
1859       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1860       if (!Mask) {
1861         // Set isThisReturn to false if the calling convention is not one that
1862         // allows 'returned' to be modeled in this way, so LowerCallResult does
1863         // not try to pass 'this' straight through
1864         isThisReturn = false;
1865         Mask = ARI->getCallPreservedMask(MF, CallConv);
1866       }
1867     } else
1868       Mask = ARI->getCallPreservedMask(MF, CallConv);
1869
1870     assert(Mask && "Missing call preserved mask for calling convention");
1871     Ops.push_back(DAG.getRegisterMask(Mask));
1872   }
1873
1874   if (InFlag.getNode())
1875     Ops.push_back(InFlag);
1876
1877   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1878   if (isTailCall) {
1879     MF.getFrameInfo()->setHasTailCall();
1880     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1881   }
1882
1883   // Returns a chain and a flag for retval copy to use.
1884   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1885   InFlag = Chain.getValue(1);
1886
1887   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1888                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1889   if (!Ins.empty())
1890     InFlag = Chain.getValue(1);
1891
1892   // Handle result values, copying them out of physregs into vregs that we
1893   // return.
1894   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1895                          InVals, isThisReturn,
1896                          isThisReturn ? OutVals[0] : SDValue());
1897 }
1898
1899 /// HandleByVal - Every parameter *after* a byval parameter is passed
1900 /// on the stack.  Remember the next parameter register to allocate,
1901 /// and then confiscate the rest of the parameter registers to insure
1902 /// this.
1903 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1904                                     unsigned Align) const {
1905   assert((State->getCallOrPrologue() == Prologue ||
1906           State->getCallOrPrologue() == Call) &&
1907          "unhandled ParmContext");
1908
1909   // Byval (as with any stack) slots are always at least 4 byte aligned.
1910   Align = std::max(Align, 4U);
1911
1912   unsigned Reg = State->AllocateReg(GPRArgRegs);
1913   if (!Reg)
1914     return;
1915
1916   unsigned AlignInRegs = Align / 4;
1917   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1918   for (unsigned i = 0; i < Waste; ++i)
1919     Reg = State->AllocateReg(GPRArgRegs);
1920
1921   if (!Reg)
1922     return;
1923
1924   unsigned Excess = 4 * (ARM::R4 - Reg);
1925
1926   // Special case when NSAA != SP and parameter size greater than size of
1927   // all remained GPR regs. In that case we can't split parameter, we must
1928   // send it to stack. We also must set NCRN to R4, so waste all
1929   // remained registers.
1930   const unsigned NSAAOffset = State->getNextStackOffset();
1931   if (NSAAOffset != 0 && Size > Excess) {
1932     while (State->AllocateReg(GPRArgRegs))
1933       ;
1934     return;
1935   }
1936
1937   // First register for byval parameter is the first register that wasn't
1938   // allocated before this method call, so it would be "reg".
1939   // If parameter is small enough to be saved in range [reg, r4), then
1940   // the end (first after last) register would be reg + param-size-in-regs,
1941   // else parameter would be splitted between registers and stack,
1942   // end register would be r4 in this case.
1943   unsigned ByValRegBegin = Reg;
1944   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1945   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1946   // Note, first register is allocated in the beginning of function already,
1947   // allocate remained amount of registers we need.
1948   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1949     State->AllocateReg(GPRArgRegs);
1950   // A byval parameter that is split between registers and memory needs its
1951   // size truncated here.
1952   // In the case where the entire structure fits in registers, we set the
1953   // size in memory to zero.
1954   Size = std::max<int>(Size - Excess, 0);
1955 }
1956
1957 /// MatchingStackOffset - Return true if the given stack call argument is
1958 /// already available in the same position (relatively) of the caller's
1959 /// incoming argument stack.
1960 static
1961 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1962                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1963                          const TargetInstrInfo *TII) {
1964   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1965   int FI = INT_MAX;
1966   if (Arg.getOpcode() == ISD::CopyFromReg) {
1967     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1968     if (!TargetRegisterInfo::isVirtualRegister(VR))
1969       return false;
1970     MachineInstr *Def = MRI->getVRegDef(VR);
1971     if (!Def)
1972       return false;
1973     if (!Flags.isByVal()) {
1974       if (!TII->isLoadFromStackSlot(Def, FI))
1975         return false;
1976     } else {
1977       return false;
1978     }
1979   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1980     if (Flags.isByVal())
1981       // ByVal argument is passed in as a pointer but it's now being
1982       // dereferenced. e.g.
1983       // define @foo(%struct.X* %A) {
1984       //   tail call @bar(%struct.X* byval %A)
1985       // }
1986       return false;
1987     SDValue Ptr = Ld->getBasePtr();
1988     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1989     if (!FINode)
1990       return false;
1991     FI = FINode->getIndex();
1992   } else
1993     return false;
1994
1995   assert(FI != INT_MAX);
1996   if (!MFI->isFixedObjectIndex(FI))
1997     return false;
1998   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1999 }
2000
2001 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2002 /// for tail call optimization. Targets which want to do tail call
2003 /// optimization should implement this function.
2004 bool
2005 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2006                                                      CallingConv::ID CalleeCC,
2007                                                      bool isVarArg,
2008                                                      bool isCalleeStructRet,
2009                                                      bool isCallerStructRet,
2010                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2011                                     const SmallVectorImpl<SDValue> &OutVals,
2012                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2013                                                      SelectionDAG& DAG) const {
2014   const Function *CallerF = DAG.getMachineFunction().getFunction();
2015   CallingConv::ID CallerCC = CallerF->getCallingConv();
2016   bool CCMatch = CallerCC == CalleeCC;
2017
2018   // Look for obvious safe cases to perform tail call optimization that do not
2019   // require ABI changes. This is what gcc calls sibcall.
2020
2021   // Do not sibcall optimize vararg calls unless the call site is not passing
2022   // any arguments.
2023   if (isVarArg && !Outs.empty())
2024     return false;
2025
2026   // Exception-handling functions need a special set of instructions to indicate
2027   // a return to the hardware. Tail-calling another function would probably
2028   // break this.
2029   if (CallerF->hasFnAttribute("interrupt"))
2030     return false;
2031
2032   // Also avoid sibcall optimization if either caller or callee uses struct
2033   // return semantics.
2034   if (isCalleeStructRet || isCallerStructRet)
2035     return false;
2036
2037   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2038   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2039   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2040   // support in the assembler and linker to be used. This would need to be
2041   // fixed to fully support tail calls in Thumb1.
2042   //
2043   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2044   // LR.  This means if we need to reload LR, it takes an extra instructions,
2045   // which outweighs the value of the tail call; but here we don't know yet
2046   // whether LR is going to be used.  Probably the right approach is to
2047   // generate the tail call here and turn it back into CALL/RET in
2048   // emitEpilogue if LR is used.
2049
2050   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2051   // but we need to make sure there are enough registers; the only valid
2052   // registers are the 4 used for parameters.  We don't currently do this
2053   // case.
2054   if (Subtarget->isThumb1Only())
2055     return false;
2056
2057   // Externally-defined functions with weak linkage should not be
2058   // tail-called on ARM when the OS does not support dynamic
2059   // pre-emption of symbols, as the AAELF spec requires normal calls
2060   // to undefined weak functions to be replaced with a NOP or jump to the
2061   // next instruction. The behaviour of branch instructions in this
2062   // situation (as used for tail calls) is implementation-defined, so we
2063   // cannot rely on the linker replacing the tail call with a return.
2064   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2065     const GlobalValue *GV = G->getGlobal();
2066     const Triple &TT = getTargetMachine().getTargetTriple();
2067     if (GV->hasExternalWeakLinkage() &&
2068         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2069       return false;
2070   }
2071
2072   // If the calling conventions do not match, then we'd better make sure the
2073   // results are returned in the same way as what the caller expects.
2074   if (!CCMatch) {
2075     SmallVector<CCValAssign, 16> RVLocs1;
2076     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2077                        *DAG.getContext(), Call);
2078     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2079
2080     SmallVector<CCValAssign, 16> RVLocs2;
2081     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2082                        *DAG.getContext(), Call);
2083     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2084
2085     if (RVLocs1.size() != RVLocs2.size())
2086       return false;
2087     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2088       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2089         return false;
2090       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2091         return false;
2092       if (RVLocs1[i].isRegLoc()) {
2093         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2094           return false;
2095       } else {
2096         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2097           return false;
2098       }
2099     }
2100   }
2101
2102   // If Caller's vararg or byval argument has been split between registers and
2103   // stack, do not perform tail call, since part of the argument is in caller's
2104   // local frame.
2105   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2106                                       getInfo<ARMFunctionInfo>();
2107   if (AFI_Caller->getArgRegsSaveSize())
2108     return false;
2109
2110   // If the callee takes no arguments then go on to check the results of the
2111   // call.
2112   if (!Outs.empty()) {
2113     // Check if stack adjustment is needed. For now, do not do this if any
2114     // argument is passed on the stack.
2115     SmallVector<CCValAssign, 16> ArgLocs;
2116     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2117                       *DAG.getContext(), Call);
2118     CCInfo.AnalyzeCallOperands(Outs,
2119                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2120     if (CCInfo.getNextStackOffset()) {
2121       MachineFunction &MF = DAG.getMachineFunction();
2122
2123       // Check if the arguments are already laid out in the right way as
2124       // the caller's fixed stack objects.
2125       MachineFrameInfo *MFI = MF.getFrameInfo();
2126       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2127       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2128       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2129            i != e;
2130            ++i, ++realArgIdx) {
2131         CCValAssign &VA = ArgLocs[i];
2132         EVT RegVT = VA.getLocVT();
2133         SDValue Arg = OutVals[realArgIdx];
2134         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2135         if (VA.getLocInfo() == CCValAssign::Indirect)
2136           return false;
2137         if (VA.needsCustom()) {
2138           // f64 and vector types are split into multiple registers or
2139           // register/stack-slot combinations.  The types will not match
2140           // the registers; give up on memory f64 refs until we figure
2141           // out what to do about this.
2142           if (!VA.isRegLoc())
2143             return false;
2144           if (!ArgLocs[++i].isRegLoc())
2145             return false;
2146           if (RegVT == MVT::v2f64) {
2147             if (!ArgLocs[++i].isRegLoc())
2148               return false;
2149             if (!ArgLocs[++i].isRegLoc())
2150               return false;
2151           }
2152         } else if (!VA.isRegLoc()) {
2153           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2154                                    MFI, MRI, TII))
2155             return false;
2156         }
2157       }
2158     }
2159   }
2160
2161   return true;
2162 }
2163
2164 bool
2165 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2166                                   MachineFunction &MF, bool isVarArg,
2167                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2168                                   LLVMContext &Context) const {
2169   SmallVector<CCValAssign, 16> RVLocs;
2170   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2171   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2172                                                     isVarArg));
2173 }
2174
2175 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2176                                     SDLoc DL, SelectionDAG &DAG) {
2177   const MachineFunction &MF = DAG.getMachineFunction();
2178   const Function *F = MF.getFunction();
2179
2180   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2181
2182   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2183   // version of the "preferred return address". These offsets affect the return
2184   // instruction if this is a return from PL1 without hypervisor extensions.
2185   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2186   //    SWI:     0      "subs pc, lr, #0"
2187   //    ABORT:   +4     "subs pc, lr, #4"
2188   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2189   // UNDEF varies depending on where the exception came from ARM or Thumb
2190   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2191
2192   int64_t LROffset;
2193   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2194       IntKind == "ABORT")
2195     LROffset = 4;
2196   else if (IntKind == "SWI" || IntKind == "UNDEF")
2197     LROffset = 0;
2198   else
2199     report_fatal_error("Unsupported interrupt attribute. If present, value "
2200                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2201
2202   RetOps.insert(RetOps.begin() + 1,
2203                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2204
2205   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2206 }
2207
2208 SDValue
2209 ARMTargetLowering::LowerReturn(SDValue Chain,
2210                                CallingConv::ID CallConv, bool isVarArg,
2211                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2212                                const SmallVectorImpl<SDValue> &OutVals,
2213                                SDLoc dl, SelectionDAG &DAG) const {
2214
2215   // CCValAssign - represent the assignment of the return value to a location.
2216   SmallVector<CCValAssign, 16> RVLocs;
2217
2218   // CCState - Info about the registers and stack slots.
2219   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2220                     *DAG.getContext(), Call);
2221
2222   // Analyze outgoing return values.
2223   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2224                                                isVarArg));
2225
2226   SDValue Flag;
2227   SmallVector<SDValue, 4> RetOps;
2228   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2229   bool isLittleEndian = Subtarget->isLittle();
2230
2231   MachineFunction &MF = DAG.getMachineFunction();
2232   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2233   AFI->setReturnRegsCount(RVLocs.size());
2234
2235   // Copy the result values into the output registers.
2236   for (unsigned i = 0, realRVLocIdx = 0;
2237        i != RVLocs.size();
2238        ++i, ++realRVLocIdx) {
2239     CCValAssign &VA = RVLocs[i];
2240     assert(VA.isRegLoc() && "Can only return in registers!");
2241
2242     SDValue Arg = OutVals[realRVLocIdx];
2243
2244     switch (VA.getLocInfo()) {
2245     default: llvm_unreachable("Unknown loc info!");
2246     case CCValAssign::Full: break;
2247     case CCValAssign::BCvt:
2248       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2249       break;
2250     }
2251
2252     if (VA.needsCustom()) {
2253       if (VA.getLocVT() == MVT::v2f64) {
2254         // Extract the first half and return it in two registers.
2255         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2256                                    DAG.getConstant(0, dl, MVT::i32));
2257         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2258                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2259
2260         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2261                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2262                                  Flag);
2263         Flag = Chain.getValue(1);
2264         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2265         VA = RVLocs[++i]; // skip ahead to next loc
2266         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2267                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2268                                  Flag);
2269         Flag = Chain.getValue(1);
2270         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2271         VA = RVLocs[++i]; // skip ahead to next loc
2272
2273         // Extract the 2nd half and fall through to handle it as an f64 value.
2274         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2275                           DAG.getConstant(1, dl, MVT::i32));
2276       }
2277       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2278       // available.
2279       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2280                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2281       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2282                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2283                                Flag);
2284       Flag = Chain.getValue(1);
2285       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2286       VA = RVLocs[++i]; // skip ahead to next loc
2287       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2288                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2289                                Flag);
2290     } else
2291       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2292
2293     // Guarantee that all emitted copies are
2294     // stuck together, avoiding something bad.
2295     Flag = Chain.getValue(1);
2296     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2297   }
2298
2299   // Update chain and glue.
2300   RetOps[0] = Chain;
2301   if (Flag.getNode())
2302     RetOps.push_back(Flag);
2303
2304   // CPUs which aren't M-class use a special sequence to return from
2305   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2306   // though we use "subs pc, lr, #N").
2307   //
2308   // M-class CPUs actually use a normal return sequence with a special
2309   // (hardware-provided) value in LR, so the normal code path works.
2310   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2311       !Subtarget->isMClass()) {
2312     if (Subtarget->isThumb1Only())
2313       report_fatal_error("interrupt attribute is not supported in Thumb1");
2314     return LowerInterruptReturn(RetOps, dl, DAG);
2315   }
2316
2317   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2318 }
2319
2320 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2321   if (N->getNumValues() != 1)
2322     return false;
2323   if (!N->hasNUsesOfValue(1, 0))
2324     return false;
2325
2326   SDValue TCChain = Chain;
2327   SDNode *Copy = *N->use_begin();
2328   if (Copy->getOpcode() == ISD::CopyToReg) {
2329     // If the copy has a glue operand, we conservatively assume it isn't safe to
2330     // perform a tail call.
2331     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2332       return false;
2333     TCChain = Copy->getOperand(0);
2334   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2335     SDNode *VMov = Copy;
2336     // f64 returned in a pair of GPRs.
2337     SmallPtrSet<SDNode*, 2> Copies;
2338     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2339          UI != UE; ++UI) {
2340       if (UI->getOpcode() != ISD::CopyToReg)
2341         return false;
2342       Copies.insert(*UI);
2343     }
2344     if (Copies.size() > 2)
2345       return false;
2346
2347     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2348          UI != UE; ++UI) {
2349       SDValue UseChain = UI->getOperand(0);
2350       if (Copies.count(UseChain.getNode()))
2351         // Second CopyToReg
2352         Copy = *UI;
2353       else {
2354         // We are at the top of this chain.
2355         // If the copy has a glue operand, we conservatively assume it
2356         // isn't safe to perform a tail call.
2357         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2358           return false;
2359         // First CopyToReg
2360         TCChain = UseChain;
2361       }
2362     }
2363   } else if (Copy->getOpcode() == ISD::BITCAST) {
2364     // f32 returned in a single GPR.
2365     if (!Copy->hasOneUse())
2366       return false;
2367     Copy = *Copy->use_begin();
2368     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2369       return false;
2370     // If the copy has a glue operand, we conservatively assume it isn't safe to
2371     // perform a tail call.
2372     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2373       return false;
2374     TCChain = Copy->getOperand(0);
2375   } else {
2376     return false;
2377   }
2378
2379   bool HasRet = false;
2380   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2381        UI != UE; ++UI) {
2382     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2383         UI->getOpcode() != ARMISD::INTRET_FLAG)
2384       return false;
2385     HasRet = true;
2386   }
2387
2388   if (!HasRet)
2389     return false;
2390
2391   Chain = TCChain;
2392   return true;
2393 }
2394
2395 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2396   if (!Subtarget->supportsTailCall())
2397     return false;
2398
2399   auto Attr =
2400       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2401   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2402     return false;
2403
2404   return !Subtarget->isThumb1Only();
2405 }
2406
2407 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2408 // and pass the lower and high parts through.
2409 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2410   SDLoc DL(Op);
2411   SDValue WriteValue = Op->getOperand(2);
2412
2413   // This function is only supposed to be called for i64 type argument.
2414   assert(WriteValue.getValueType() == MVT::i64
2415           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2416
2417   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2418                            DAG.getConstant(0, DL, MVT::i32));
2419   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2420                            DAG.getConstant(1, DL, MVT::i32));
2421   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2422   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2423 }
2424
2425 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2426 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2427 // one of the above mentioned nodes. It has to be wrapped because otherwise
2428 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2429 // be used to form addressing mode. These wrapped nodes will be selected
2430 // into MOVi.
2431 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2432   EVT PtrVT = Op.getValueType();
2433   // FIXME there is no actual debug info here
2434   SDLoc dl(Op);
2435   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2436   SDValue Res;
2437   if (CP->isMachineConstantPoolEntry())
2438     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2439                                     CP->getAlignment());
2440   else
2441     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2442                                     CP->getAlignment());
2443   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2444 }
2445
2446 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2447   return MachineJumpTableInfo::EK_Inline;
2448 }
2449
2450 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2451                                              SelectionDAG &DAG) const {
2452   MachineFunction &MF = DAG.getMachineFunction();
2453   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2454   unsigned ARMPCLabelIndex = 0;
2455   SDLoc DL(Op);
2456   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2457   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2458   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2459   SDValue CPAddr;
2460   if (RelocM == Reloc::Static) {
2461     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2462   } else {
2463     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2464     ARMPCLabelIndex = AFI->createPICLabelUId();
2465     ARMConstantPoolValue *CPV =
2466       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2467                                       ARMCP::CPBlockAddress, PCAdj);
2468     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2469   }
2470   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2471   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2472                                MachinePointerInfo::getConstantPool(),
2473                                false, false, false, 0);
2474   if (RelocM == Reloc::Static)
2475     return Result;
2476   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2477   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2478 }
2479
2480 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2481 SDValue
2482 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2483                                                  SelectionDAG &DAG) const {
2484   SDLoc dl(GA);
2485   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2486   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2487   MachineFunction &MF = DAG.getMachineFunction();
2488   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2489   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2490   ARMConstantPoolValue *CPV =
2491     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2492                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2493   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2494   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2495   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2496                          MachinePointerInfo::getConstantPool(),
2497                          false, false, false, 0);
2498   SDValue Chain = Argument.getValue(1);
2499
2500   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2501   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2502
2503   // call __tls_get_addr.
2504   ArgListTy Args;
2505   ArgListEntry Entry;
2506   Entry.Node = Argument;
2507   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2508   Args.push_back(Entry);
2509
2510   // FIXME: is there useful debug info available here?
2511   TargetLowering::CallLoweringInfo CLI(DAG);
2512   CLI.setDebugLoc(dl).setChain(Chain)
2513     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2514                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2515                0);
2516
2517   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2518   return CallResult.first;
2519 }
2520
2521 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2522 // "local exec" model.
2523 SDValue
2524 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2525                                         SelectionDAG &DAG,
2526                                         TLSModel::Model model) const {
2527   const GlobalValue *GV = GA->getGlobal();
2528   SDLoc dl(GA);
2529   SDValue Offset;
2530   SDValue Chain = DAG.getEntryNode();
2531   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2532   // Get the Thread Pointer
2533   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2534
2535   if (model == TLSModel::InitialExec) {
2536     MachineFunction &MF = DAG.getMachineFunction();
2537     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2538     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2539     // Initial exec model.
2540     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2541     ARMConstantPoolValue *CPV =
2542       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2543                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2544                                       true);
2545     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2546     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2547     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2548                          MachinePointerInfo::getConstantPool(),
2549                          false, false, false, 0);
2550     Chain = Offset.getValue(1);
2551
2552     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2553     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2554
2555     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2556                          MachinePointerInfo::getConstantPool(),
2557                          false, false, false, 0);
2558   } else {
2559     // local exec model
2560     assert(model == TLSModel::LocalExec);
2561     ARMConstantPoolValue *CPV =
2562       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2563     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2564     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2565     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2566                          MachinePointerInfo::getConstantPool(),
2567                          false, false, false, 0);
2568   }
2569
2570   // The address of the thread local variable is the add of the thread
2571   // pointer with the offset of the variable.
2572   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2573 }
2574
2575 SDValue
2576 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2577   // TODO: implement the "local dynamic" model
2578   assert(Subtarget->isTargetELF() &&
2579          "TLS not implemented for non-ELF targets");
2580   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2581
2582   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2583
2584   switch (model) {
2585     case TLSModel::GeneralDynamic:
2586     case TLSModel::LocalDynamic:
2587       return LowerToTLSGeneralDynamicModel(GA, DAG);
2588     case TLSModel::InitialExec:
2589     case TLSModel::LocalExec:
2590       return LowerToTLSExecModels(GA, DAG, model);
2591   }
2592   llvm_unreachable("bogus TLS model");
2593 }
2594
2595 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2596                                                  SelectionDAG &DAG) const {
2597   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2598   SDLoc dl(Op);
2599   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2600   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2601     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2602     ARMConstantPoolValue *CPV =
2603       ARMConstantPoolConstant::Create(GV,
2604                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2605     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2606     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2607     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2608                                  CPAddr,
2609                                  MachinePointerInfo::getConstantPool(),
2610                                  false, false, false, 0);
2611     SDValue Chain = Result.getValue(1);
2612     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2613     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2614     if (!UseGOTOFF)
2615       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2616                            MachinePointerInfo::getGOT(),
2617                            false, false, false, 0);
2618     return Result;
2619   }
2620
2621   // If we have T2 ops, we can materialize the address directly via movt/movw
2622   // pair. This is always cheaper.
2623   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2624     ++NumMovwMovt;
2625     // FIXME: Once remat is capable of dealing with instructions with register
2626     // operands, expand this into two nodes.
2627     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2628                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2629   } else {
2630     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2631     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2632     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2633                        MachinePointerInfo::getConstantPool(),
2634                        false, false, false, 0);
2635   }
2636 }
2637
2638 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2639                                                     SelectionDAG &DAG) const {
2640   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2641   SDLoc dl(Op);
2642   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2643   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2644
2645   if (Subtarget->useMovt(DAG.getMachineFunction()))
2646     ++NumMovwMovt;
2647
2648   // FIXME: Once remat is capable of dealing with instructions with register
2649   // operands, expand this into multiple nodes
2650   unsigned Wrapper =
2651       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2652
2653   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2654   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2655
2656   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2657     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2658                          MachinePointerInfo::getGOT(), false, false, false, 0);
2659   return Result;
2660 }
2661
2662 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2663                                                      SelectionDAG &DAG) const {
2664   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2665   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2666          "Windows on ARM expects to use movw/movt");
2667
2668   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2669   const ARMII::TOF TargetFlags =
2670     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2671   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2672   SDValue Result;
2673   SDLoc DL(Op);
2674
2675   ++NumMovwMovt;
2676
2677   // FIXME: Once remat is capable of dealing with instructions with register
2678   // operands, expand this into two nodes.
2679   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2680                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2681                                                   TargetFlags));
2682   if (GV->hasDLLImportStorageClass())
2683     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2684                          MachinePointerInfo::getGOT(), false, false, false, 0);
2685   return Result;
2686 }
2687
2688 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2689                                                     SelectionDAG &DAG) const {
2690   assert(Subtarget->isTargetELF() &&
2691          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2692   MachineFunction &MF = DAG.getMachineFunction();
2693   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2694   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2695   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2696   SDLoc dl(Op);
2697   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2698   ARMConstantPoolValue *CPV =
2699     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2700                                   ARMPCLabelIndex, PCAdj);
2701   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2702   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2703   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2704                                MachinePointerInfo::getConstantPool(),
2705                                false, false, false, 0);
2706   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2707   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2708 }
2709
2710 SDValue
2711 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2712   SDLoc dl(Op);
2713   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2714   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2715                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2716                      Op.getOperand(1), Val);
2717 }
2718
2719 SDValue
2720 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2721   SDLoc dl(Op);
2722   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2723                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2724 }
2725
2726 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2727                                                       SelectionDAG &DAG) const {
2728   SDLoc dl(Op);
2729   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2730                      Op.getOperand(0));
2731 }
2732
2733 SDValue
2734 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2735                                           const ARMSubtarget *Subtarget) const {
2736   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2737   SDLoc dl(Op);
2738   switch (IntNo) {
2739   default: return SDValue();    // Don't custom lower most intrinsics.
2740   case Intrinsic::arm_rbit: {
2741     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2742            "RBIT intrinsic must have i32 type!");
2743     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2744   }
2745   case Intrinsic::arm_thread_pointer: {
2746     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2747     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2748   }
2749   case Intrinsic::eh_sjlj_lsda: {
2750     MachineFunction &MF = DAG.getMachineFunction();
2751     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2752     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2753     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2754     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2755     SDValue CPAddr;
2756     unsigned PCAdj = (RelocM != Reloc::PIC_)
2757       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2758     ARMConstantPoolValue *CPV =
2759       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2760                                       ARMCP::CPLSDA, PCAdj);
2761     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2762     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2763     SDValue Result =
2764       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2765                   MachinePointerInfo::getConstantPool(),
2766                   false, false, false, 0);
2767
2768     if (RelocM == Reloc::PIC_) {
2769       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2770       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2771     }
2772     return Result;
2773   }
2774   case Intrinsic::arm_neon_vmulls:
2775   case Intrinsic::arm_neon_vmullu: {
2776     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2777       ? ARMISD::VMULLs : ARMISD::VMULLu;
2778     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2779                        Op.getOperand(1), Op.getOperand(2));
2780   }
2781   }
2782 }
2783
2784 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2785                                  const ARMSubtarget *Subtarget) {
2786   // FIXME: handle "fence singlethread" more efficiently.
2787   SDLoc dl(Op);
2788   if (!Subtarget->hasDataBarrier()) {
2789     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2790     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2791     // here.
2792     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2793            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2794     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2795                        DAG.getConstant(0, dl, MVT::i32));
2796   }
2797
2798   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2799   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2800   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2801   if (Subtarget->isMClass()) {
2802     // Only a full system barrier exists in the M-class architectures.
2803     Domain = ARM_MB::SY;
2804   } else if (Subtarget->isSwift() && Ord == Release) {
2805     // Swift happens to implement ISHST barriers in a way that's compatible with
2806     // Release semantics but weaker than ISH so we'd be fools not to use
2807     // it. Beware: other processors probably don't!
2808     Domain = ARM_MB::ISHST;
2809   }
2810
2811   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2812                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2813                      DAG.getConstant(Domain, dl, MVT::i32));
2814 }
2815
2816 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2817                              const ARMSubtarget *Subtarget) {
2818   // ARM pre v5TE and Thumb1 does not have preload instructions.
2819   if (!(Subtarget->isThumb2() ||
2820         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2821     // Just preserve the chain.
2822     return Op.getOperand(0);
2823
2824   SDLoc dl(Op);
2825   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2826   if (!isRead &&
2827       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2828     // ARMv7 with MP extension has PLDW.
2829     return Op.getOperand(0);
2830
2831   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2832   if (Subtarget->isThumb()) {
2833     // Invert the bits.
2834     isRead = ~isRead & 1;
2835     isData = ~isData & 1;
2836   }
2837
2838   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2839                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2840                      DAG.getConstant(isData, dl, MVT::i32));
2841 }
2842
2843 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2844   MachineFunction &MF = DAG.getMachineFunction();
2845   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2846
2847   // vastart just stores the address of the VarArgsFrameIndex slot into the
2848   // memory location argument.
2849   SDLoc dl(Op);
2850   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2851   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2852   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2853   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2854                       MachinePointerInfo(SV), false, false, 0);
2855 }
2856
2857 SDValue
2858 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2859                                         SDValue &Root, SelectionDAG &DAG,
2860                                         SDLoc dl) const {
2861   MachineFunction &MF = DAG.getMachineFunction();
2862   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2863
2864   const TargetRegisterClass *RC;
2865   if (AFI->isThumb1OnlyFunction())
2866     RC = &ARM::tGPRRegClass;
2867   else
2868     RC = &ARM::GPRRegClass;
2869
2870   // Transform the arguments stored in physical registers into virtual ones.
2871   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2872   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2873
2874   SDValue ArgValue2;
2875   if (NextVA.isMemLoc()) {
2876     MachineFrameInfo *MFI = MF.getFrameInfo();
2877     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2878
2879     // Create load node to retrieve arguments from the stack.
2880     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2881     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2882                             MachinePointerInfo::getFixedStack(FI),
2883                             false, false, false, 0);
2884   } else {
2885     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2886     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2887   }
2888   if (!Subtarget->isLittle())
2889     std::swap (ArgValue, ArgValue2);
2890   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2891 }
2892
2893 // The remaining GPRs hold either the beginning of variable-argument
2894 // data, or the beginning of an aggregate passed by value (usually
2895 // byval).  Either way, we allocate stack slots adjacent to the data
2896 // provided by our caller, and store the unallocated registers there.
2897 // If this is a variadic function, the va_list pointer will begin with
2898 // these values; otherwise, this reassembles a (byval) structure that
2899 // was split between registers and memory.
2900 // Return: The frame index registers were stored into.
2901 int
2902 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2903                                   SDLoc dl, SDValue &Chain,
2904                                   const Value *OrigArg,
2905                                   unsigned InRegsParamRecordIdx,
2906                                   int ArgOffset,
2907                                   unsigned ArgSize) const {
2908   // Currently, two use-cases possible:
2909   // Case #1. Non-var-args function, and we meet first byval parameter.
2910   //          Setup first unallocated register as first byval register;
2911   //          eat all remained registers
2912   //          (these two actions are performed by HandleByVal method).
2913   //          Then, here, we initialize stack frame with
2914   //          "store-reg" instructions.
2915   // Case #2. Var-args function, that doesn't contain byval parameters.
2916   //          The same: eat all remained unallocated registers,
2917   //          initialize stack frame.
2918
2919   MachineFunction &MF = DAG.getMachineFunction();
2920   MachineFrameInfo *MFI = MF.getFrameInfo();
2921   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2922   unsigned RBegin, REnd;
2923   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2924     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2925   } else {
2926     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2927     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2928     REnd = ARM::R4;
2929   }
2930
2931   if (REnd != RBegin)
2932     ArgOffset = -4 * (ARM::R4 - RBegin);
2933
2934   auto PtrVT = getPointerTy(DAG.getDataLayout());
2935   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2936   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
2937
2938   SmallVector<SDValue, 4> MemOps;
2939   const TargetRegisterClass *RC =
2940       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2941
2942   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2943     unsigned VReg = MF.addLiveIn(Reg, RC);
2944     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2945     SDValue Store =
2946         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2947                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2948     MemOps.push_back(Store);
2949     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
2950   }
2951
2952   if (!MemOps.empty())
2953     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2954   return FrameIndex;
2955 }
2956
2957 // Setup stack frame, the va_list pointer will start from.
2958 void
2959 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2960                                         SDLoc dl, SDValue &Chain,
2961                                         unsigned ArgOffset,
2962                                         unsigned TotalArgRegsSaveSize,
2963                                         bool ForceMutable) const {
2964   MachineFunction &MF = DAG.getMachineFunction();
2965   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2966
2967   // Try to store any remaining integer argument regs
2968   // to their spots on the stack so that they may be loaded by deferencing
2969   // the result of va_next.
2970   // If there is no regs to be stored, just point address after last
2971   // argument passed via stack.
2972   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2973                                   CCInfo.getInRegsParamsCount(),
2974                                   CCInfo.getNextStackOffset(), 4);
2975   AFI->setVarArgsFrameIndex(FrameIndex);
2976 }
2977
2978 SDValue
2979 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2980                                         CallingConv::ID CallConv, bool isVarArg,
2981                                         const SmallVectorImpl<ISD::InputArg>
2982                                           &Ins,
2983                                         SDLoc dl, SelectionDAG &DAG,
2984                                         SmallVectorImpl<SDValue> &InVals)
2985                                           const {
2986   MachineFunction &MF = DAG.getMachineFunction();
2987   MachineFrameInfo *MFI = MF.getFrameInfo();
2988
2989   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2990
2991   // Assign locations to all of the incoming arguments.
2992   SmallVector<CCValAssign, 16> ArgLocs;
2993   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2994                     *DAG.getContext(), Prologue);
2995   CCInfo.AnalyzeFormalArguments(Ins,
2996                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2997                                                   isVarArg));
2998
2999   SmallVector<SDValue, 16> ArgValues;
3000   SDValue ArgValue;
3001   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3002   unsigned CurArgIdx = 0;
3003
3004   // Initially ArgRegsSaveSize is zero.
3005   // Then we increase this value each time we meet byval parameter.
3006   // We also increase this value in case of varargs function.
3007   AFI->setArgRegsSaveSize(0);
3008
3009   // Calculate the amount of stack space that we need to allocate to store
3010   // byval and variadic arguments that are passed in registers.
3011   // We need to know this before we allocate the first byval or variadic
3012   // argument, as they will be allocated a stack slot below the CFA (Canonical
3013   // Frame Address, the stack pointer at entry to the function).
3014   unsigned ArgRegBegin = ARM::R4;
3015   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3016     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3017       break;
3018
3019     CCValAssign &VA = ArgLocs[i];
3020     unsigned Index = VA.getValNo();
3021     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3022     if (!Flags.isByVal())
3023       continue;
3024
3025     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3026     unsigned RBegin, REnd;
3027     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3028     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3029
3030     CCInfo.nextInRegsParam();
3031   }
3032   CCInfo.rewindByValRegsInfo();
3033
3034   int lastInsIndex = -1;
3035   if (isVarArg && MFI->hasVAStart()) {
3036     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3037     if (RegIdx != array_lengthof(GPRArgRegs))
3038       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3039   }
3040
3041   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3042   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3043   auto PtrVT = getPointerTy(DAG.getDataLayout());
3044
3045   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3046     CCValAssign &VA = ArgLocs[i];
3047     if (Ins[VA.getValNo()].isOrigArg()) {
3048       std::advance(CurOrigArg,
3049                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3050       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3051     }
3052     // Arguments stored in registers.
3053     if (VA.isRegLoc()) {
3054       EVT RegVT = VA.getLocVT();
3055
3056       if (VA.needsCustom()) {
3057         // f64 and vector types are split up into multiple registers or
3058         // combinations of registers and stack slots.
3059         if (VA.getLocVT() == MVT::v2f64) {
3060           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3061                                                    Chain, DAG, dl);
3062           VA = ArgLocs[++i]; // skip ahead to next loc
3063           SDValue ArgValue2;
3064           if (VA.isMemLoc()) {
3065             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3066             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3067             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3068                                     MachinePointerInfo::getFixedStack(FI),
3069                                     false, false, false, 0);
3070           } else {
3071             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3072                                              Chain, DAG, dl);
3073           }
3074           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3075           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3076                                  ArgValue, ArgValue1,
3077                                  DAG.getIntPtrConstant(0, dl));
3078           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3079                                  ArgValue, ArgValue2,
3080                                  DAG.getIntPtrConstant(1, dl));
3081         } else
3082           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3083
3084       } else {
3085         const TargetRegisterClass *RC;
3086
3087         if (RegVT == MVT::f32)
3088           RC = &ARM::SPRRegClass;
3089         else if (RegVT == MVT::f64)
3090           RC = &ARM::DPRRegClass;
3091         else if (RegVT == MVT::v2f64)
3092           RC = &ARM::QPRRegClass;
3093         else if (RegVT == MVT::i32)
3094           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3095                                            : &ARM::GPRRegClass;
3096         else
3097           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3098
3099         // Transform the arguments in physical registers into virtual ones.
3100         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3101         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3102       }
3103
3104       // If this is an 8 or 16-bit value, it is really passed promoted
3105       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3106       // truncate to the right size.
3107       switch (VA.getLocInfo()) {
3108       default: llvm_unreachable("Unknown loc info!");
3109       case CCValAssign::Full: break;
3110       case CCValAssign::BCvt:
3111         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3112         break;
3113       case CCValAssign::SExt:
3114         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3115                                DAG.getValueType(VA.getValVT()));
3116         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3117         break;
3118       case CCValAssign::ZExt:
3119         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3120                                DAG.getValueType(VA.getValVT()));
3121         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3122         break;
3123       }
3124
3125       InVals.push_back(ArgValue);
3126
3127     } else { // VA.isRegLoc()
3128
3129       // sanity check
3130       assert(VA.isMemLoc());
3131       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3132
3133       int index = VA.getValNo();
3134
3135       // Some Ins[] entries become multiple ArgLoc[] entries.
3136       // Process them only once.
3137       if (index != lastInsIndex)
3138         {
3139           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3140           // FIXME: For now, all byval parameter objects are marked mutable.
3141           // This can be changed with more analysis.
3142           // In case of tail call optimization mark all arguments mutable.
3143           // Since they could be overwritten by lowering of arguments in case of
3144           // a tail call.
3145           if (Flags.isByVal()) {
3146             assert(Ins[index].isOrigArg() &&
3147                    "Byval arguments cannot be implicit");
3148             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3149
3150             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3151                                             CurByValIndex, VA.getLocMemOffset(),
3152                                             Flags.getByValSize());
3153             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3154             CCInfo.nextInRegsParam();
3155           } else {
3156             unsigned FIOffset = VA.getLocMemOffset();
3157             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3158                                             FIOffset, true);
3159
3160             // Create load nodes to retrieve arguments from the stack.
3161             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3162             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3163                                          MachinePointerInfo::getFixedStack(FI),
3164                                          false, false, false, 0));
3165           }
3166           lastInsIndex = index;
3167         }
3168     }
3169   }
3170
3171   // varargs
3172   if (isVarArg && MFI->hasVAStart())
3173     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3174                          CCInfo.getNextStackOffset(),
3175                          TotalArgRegsSaveSize);
3176
3177   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3178
3179   return Chain;
3180 }
3181
3182 /// isFloatingPointZero - Return true if this is +0.0.
3183 static bool isFloatingPointZero(SDValue Op) {
3184   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3185     return CFP->getValueAPF().isPosZero();
3186   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3187     // Maybe this has already been legalized into the constant pool?
3188     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3189       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3190       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3191         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3192           return CFP->getValueAPF().isPosZero();
3193     }
3194   } else if (Op->getOpcode() == ISD::BITCAST &&
3195              Op->getValueType(0) == MVT::f64) {
3196     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3197     // created by LowerConstantFP().
3198     SDValue BitcastOp = Op->getOperand(0);
3199     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3200       SDValue MoveOp = BitcastOp->getOperand(0);
3201       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3202           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3203         return true;
3204       }
3205     }
3206   }
3207   return false;
3208 }
3209
3210 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3211 /// the given operands.
3212 SDValue
3213 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3214                              SDValue &ARMcc, SelectionDAG &DAG,
3215                              SDLoc dl) const {
3216   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3217     unsigned C = RHSC->getZExtValue();
3218     if (!isLegalICmpImmediate(C)) {
3219       // Constant does not fit, try adjusting it by one?
3220       switch (CC) {
3221       default: break;
3222       case ISD::SETLT:
3223       case ISD::SETGE:
3224         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3225           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3226           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3227         }
3228         break;
3229       case ISD::SETULT:
3230       case ISD::SETUGE:
3231         if (C != 0 && isLegalICmpImmediate(C-1)) {
3232           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3233           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3234         }
3235         break;
3236       case ISD::SETLE:
3237       case ISD::SETGT:
3238         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3239           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3240           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3241         }
3242         break;
3243       case ISD::SETULE:
3244       case ISD::SETUGT:
3245         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3246           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3247           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3248         }
3249         break;
3250       }
3251     }
3252   }
3253
3254   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3255   ARMISD::NodeType CompareType;
3256   switch (CondCode) {
3257   default:
3258     CompareType = ARMISD::CMP;
3259     break;
3260   case ARMCC::EQ:
3261   case ARMCC::NE:
3262     // Uses only Z Flag
3263     CompareType = ARMISD::CMPZ;
3264     break;
3265   }
3266   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3267   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3268 }
3269
3270 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3271 SDValue
3272 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3273                              SDLoc dl) const {
3274   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3275   SDValue Cmp;
3276   if (!isFloatingPointZero(RHS))
3277     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3278   else
3279     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3280   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3281 }
3282
3283 /// duplicateCmp - Glue values can have only one use, so this function
3284 /// duplicates a comparison node.
3285 SDValue
3286 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3287   unsigned Opc = Cmp.getOpcode();
3288   SDLoc DL(Cmp);
3289   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3290     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3291
3292   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3293   Cmp = Cmp.getOperand(0);
3294   Opc = Cmp.getOpcode();
3295   if (Opc == ARMISD::CMPFP)
3296     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3297   else {
3298     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3299     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3300   }
3301   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3302 }
3303
3304 std::pair<SDValue, SDValue>
3305 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3306                                  SDValue &ARMcc) const {
3307   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3308
3309   SDValue Value, OverflowCmp;
3310   SDValue LHS = Op.getOperand(0);
3311   SDValue RHS = Op.getOperand(1);
3312   SDLoc dl(Op);
3313
3314   // FIXME: We are currently always generating CMPs because we don't support
3315   // generating CMN through the backend. This is not as good as the natural
3316   // CMP case because it causes a register dependency and cannot be folded
3317   // later.
3318
3319   switch (Op.getOpcode()) {
3320   default:
3321     llvm_unreachable("Unknown overflow instruction!");
3322   case ISD::SADDO:
3323     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3324     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3325     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3326     break;
3327   case ISD::UADDO:
3328     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3329     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3330     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3331     break;
3332   case ISD::SSUBO:
3333     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3334     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3335     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3336     break;
3337   case ISD::USUBO:
3338     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3339     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3340     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3341     break;
3342   } // switch (...)
3343
3344   return std::make_pair(Value, OverflowCmp);
3345 }
3346
3347
3348 SDValue
3349 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3350   // Let legalize expand this if it isn't a legal type yet.
3351   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3352     return SDValue();
3353
3354   SDValue Value, OverflowCmp;
3355   SDValue ARMcc;
3356   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3357   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3358   SDLoc dl(Op);
3359   // We use 0 and 1 as false and true values.
3360   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3361   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3362   EVT VT = Op.getValueType();
3363
3364   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3365                                  ARMcc, CCR, OverflowCmp);
3366
3367   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3368   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3369 }
3370
3371
3372 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3373   SDValue Cond = Op.getOperand(0);
3374   SDValue SelectTrue = Op.getOperand(1);
3375   SDValue SelectFalse = Op.getOperand(2);
3376   SDLoc dl(Op);
3377   unsigned Opc = Cond.getOpcode();
3378
3379   if (Cond.getResNo() == 1 &&
3380       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3381        Opc == ISD::USUBO)) {
3382     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3383       return SDValue();
3384
3385     SDValue Value, OverflowCmp;
3386     SDValue ARMcc;
3387     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3388     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3389     EVT VT = Op.getValueType();
3390
3391     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3392                    OverflowCmp, DAG);
3393   }
3394
3395   // Convert:
3396   //
3397   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3398   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3399   //
3400   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3401     const ConstantSDNode *CMOVTrue =
3402       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3403     const ConstantSDNode *CMOVFalse =
3404       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3405
3406     if (CMOVTrue && CMOVFalse) {
3407       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3408       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3409
3410       SDValue True;
3411       SDValue False;
3412       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3413         True = SelectTrue;
3414         False = SelectFalse;
3415       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3416         True = SelectFalse;
3417         False = SelectTrue;
3418       }
3419
3420       if (True.getNode() && False.getNode()) {
3421         EVT VT = Op.getValueType();
3422         SDValue ARMcc = Cond.getOperand(2);
3423         SDValue CCR = Cond.getOperand(3);
3424         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3425         assert(True.getValueType() == VT);
3426         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3427       }
3428     }
3429   }
3430
3431   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3432   // undefined bits before doing a full-word comparison with zero.
3433   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3434                      DAG.getConstant(1, dl, Cond.getValueType()));
3435
3436   return DAG.getSelectCC(dl, Cond,
3437                          DAG.getConstant(0, dl, Cond.getValueType()),
3438                          SelectTrue, SelectFalse, ISD::SETNE);
3439 }
3440
3441 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3442                                  bool &swpCmpOps, bool &swpVselOps) {
3443   // Start by selecting the GE condition code for opcodes that return true for
3444   // 'equality'
3445   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3446       CC == ISD::SETULE)
3447     CondCode = ARMCC::GE;
3448
3449   // and GT for opcodes that return false for 'equality'.
3450   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3451            CC == ISD::SETULT)
3452     CondCode = ARMCC::GT;
3453
3454   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3455   // to swap the compare operands.
3456   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3457       CC == ISD::SETULT)
3458     swpCmpOps = true;
3459
3460   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3461   // If we have an unordered opcode, we need to swap the operands to the VSEL
3462   // instruction (effectively negating the condition).
3463   //
3464   // This also has the effect of swapping which one of 'less' or 'greater'
3465   // returns true, so we also swap the compare operands. It also switches
3466   // whether we return true for 'equality', so we compensate by picking the
3467   // opposite condition code to our original choice.
3468   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3469       CC == ISD::SETUGT) {
3470     swpCmpOps = !swpCmpOps;
3471     swpVselOps = !swpVselOps;
3472     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3473   }
3474
3475   // 'ordered' is 'anything but unordered', so use the VS condition code and
3476   // swap the VSEL operands.
3477   if (CC == ISD::SETO) {
3478     CondCode = ARMCC::VS;
3479     swpVselOps = true;
3480   }
3481
3482   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3483   // code and swap the VSEL operands.
3484   if (CC == ISD::SETUNE) {
3485     CondCode = ARMCC::EQ;
3486     swpVselOps = true;
3487   }
3488 }
3489
3490 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3491                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3492                                    SDValue Cmp, SelectionDAG &DAG) const {
3493   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3494     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3495                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3496     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3497                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3498
3499     SDValue TrueLow = TrueVal.getValue(0);
3500     SDValue TrueHigh = TrueVal.getValue(1);
3501     SDValue FalseLow = FalseVal.getValue(0);
3502     SDValue FalseHigh = FalseVal.getValue(1);
3503
3504     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3505                               ARMcc, CCR, Cmp);
3506     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3507                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3508
3509     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3510   } else {
3511     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3512                        Cmp);
3513   }
3514 }
3515
3516 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3517   EVT VT = Op.getValueType();
3518   SDValue LHS = Op.getOperand(0);
3519   SDValue RHS = Op.getOperand(1);
3520   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3521   SDValue TrueVal = Op.getOperand(2);
3522   SDValue FalseVal = Op.getOperand(3);
3523   SDLoc dl(Op);
3524
3525   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3526     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3527                                                     dl);
3528
3529     // If softenSetCCOperands only returned one value, we should compare it to
3530     // zero.
3531     if (!RHS.getNode()) {
3532       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3533       CC = ISD::SETNE;
3534     }
3535   }
3536
3537   if (LHS.getValueType() == MVT::i32) {
3538     // Try to generate VSEL on ARMv8.
3539     // The VSEL instruction can't use all the usual ARM condition
3540     // codes: it only has two bits to select the condition code, so it's
3541     // constrained to use only GE, GT, VS and EQ.
3542     //
3543     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3544     // swap the operands of the previous compare instruction (effectively
3545     // inverting the compare condition, swapping 'less' and 'greater') and
3546     // sometimes need to swap the operands to the VSEL (which inverts the
3547     // condition in the sense of firing whenever the previous condition didn't)
3548     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3549                                     TrueVal.getValueType() == MVT::f64)) {
3550       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3551       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3552           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3553         CC = ISD::getSetCCInverse(CC, true);
3554         std::swap(TrueVal, FalseVal);
3555       }
3556     }
3557
3558     SDValue ARMcc;
3559     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3560     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3561     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3562   }
3563
3564   ARMCC::CondCodes CondCode, CondCode2;
3565   FPCCToARMCC(CC, CondCode, CondCode2);
3566
3567   // Try to generate VMAXNM/VMINNM on ARMv8.
3568   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3569                                   TrueVal.getValueType() == MVT::f64)) {
3570     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3571     // same operands, as follows:
3572     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3573     //   select c, a, b
3574     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3575     bool swapSides = false;
3576     if (!getTargetMachine().Options.NoNaNsFPMath) {
3577       // transformability may depend on which way around we compare
3578       switch (CC) {
3579       default:
3580         break;
3581       case ISD::SETOGT:
3582       case ISD::SETOGE:
3583       case ISD::SETOLT:
3584       case ISD::SETOLE:
3585         // the non-NaN should be RHS
3586         swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3587         break;
3588       case ISD::SETUGT:
3589       case ISD::SETUGE:
3590       case ISD::SETULT:
3591       case ISD::SETULE:
3592         // the non-NaN should be LHS
3593         swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3594         break;
3595       }
3596     }
3597     swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3598     if (swapSides) {
3599       CC = ISD::getSetCCSwappedOperands(CC);
3600       std::swap(LHS, RHS);
3601     }
3602     if (LHS == TrueVal && RHS == FalseVal) {
3603       bool canTransform = true;
3604       // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3605       if (!getTargetMachine().Options.UnsafeFPMath &&
3606           !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3607         const ConstantFPSDNode *Zero;
3608         switch (CC) {
3609         default:
3610           break;
3611         case ISD::SETOGT:
3612         case ISD::SETUGT:
3613         case ISD::SETGT:
3614           // RHS must not be -0
3615           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3616                          !Zero->isNegative();
3617           break;
3618         case ISD::SETOGE:
3619         case ISD::SETUGE:
3620         case ISD::SETGE:
3621           // LHS must not be -0
3622           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3623                          !Zero->isNegative();
3624           break;
3625         case ISD::SETOLT:
3626         case ISD::SETULT:
3627         case ISD::SETLT:
3628           // RHS must not be +0
3629           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3630                           Zero->isNegative();
3631           break;
3632         case ISD::SETOLE:
3633         case ISD::SETULE:
3634         case ISD::SETLE:
3635           // LHS must not be +0
3636           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3637                           Zero->isNegative();
3638           break;
3639         }
3640       }
3641       if (canTransform) {
3642         // Note: If one of the elements in a pair is a number and the other
3643         // element is NaN, the corresponding result element is the number.
3644         // This is consistent with the IEEE 754-2008 standard.
3645         // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3646         switch (CC) {
3647         default:
3648           break;
3649         case ISD::SETOGT:
3650         case ISD::SETOGE:
3651           if (!DAG.isKnownNeverNaN(RHS))
3652             break;
3653           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3654         case ISD::SETUGT:
3655         case ISD::SETUGE:
3656           if (!DAG.isKnownNeverNaN(LHS))
3657             break;
3658         case ISD::SETGT:
3659         case ISD::SETGE:
3660           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3661         case ISD::SETOLT:
3662         case ISD::SETOLE:
3663           if (!DAG.isKnownNeverNaN(RHS))
3664             break;
3665           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3666         case ISD::SETULT:
3667         case ISD::SETULE:
3668           if (!DAG.isKnownNeverNaN(LHS))
3669             break;
3670         case ISD::SETLT:
3671         case ISD::SETLE:
3672           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3673         }
3674       }
3675     }
3676
3677     bool swpCmpOps = false;
3678     bool swpVselOps = false;
3679     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3680
3681     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3682         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3683       if (swpCmpOps)
3684         std::swap(LHS, RHS);
3685       if (swpVselOps)
3686         std::swap(TrueVal, FalseVal);
3687     }
3688   }
3689
3690   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3691   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3692   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3693   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3694   if (CondCode2 != ARMCC::AL) {
3695     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3696     // FIXME: Needs another CMP because flag can have but one use.
3697     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3698     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3699   }
3700   return Result;
3701 }
3702
3703 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3704 /// to morph to an integer compare sequence.
3705 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3706                            const ARMSubtarget *Subtarget) {
3707   SDNode *N = Op.getNode();
3708   if (!N->hasOneUse())
3709     // Otherwise it requires moving the value from fp to integer registers.
3710     return false;
3711   if (!N->getNumValues())
3712     return false;
3713   EVT VT = Op.getValueType();
3714   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3715     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3716     // vmrs are very slow, e.g. cortex-a8.
3717     return false;
3718
3719   if (isFloatingPointZero(Op)) {
3720     SeenZero = true;
3721     return true;
3722   }
3723   return ISD::isNormalLoad(N);
3724 }
3725
3726 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3727   if (isFloatingPointZero(Op))
3728     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3729
3730   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3731     return DAG.getLoad(MVT::i32, SDLoc(Op),
3732                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3733                        Ld->isVolatile(), Ld->isNonTemporal(),
3734                        Ld->isInvariant(), Ld->getAlignment());
3735
3736   llvm_unreachable("Unknown VFP cmp argument!");
3737 }
3738
3739 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3740                            SDValue &RetVal1, SDValue &RetVal2) {
3741   SDLoc dl(Op);
3742
3743   if (isFloatingPointZero(Op)) {
3744     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3745     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3746     return;
3747   }
3748
3749   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3750     SDValue Ptr = Ld->getBasePtr();
3751     RetVal1 = DAG.getLoad(MVT::i32, dl,
3752                           Ld->getChain(), Ptr,
3753                           Ld->getPointerInfo(),
3754                           Ld->isVolatile(), Ld->isNonTemporal(),
3755                           Ld->isInvariant(), Ld->getAlignment());
3756
3757     EVT PtrType = Ptr.getValueType();
3758     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3759     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3760                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3761     RetVal2 = DAG.getLoad(MVT::i32, dl,
3762                           Ld->getChain(), NewPtr,
3763                           Ld->getPointerInfo().getWithOffset(4),
3764                           Ld->isVolatile(), Ld->isNonTemporal(),
3765                           Ld->isInvariant(), NewAlign);
3766     return;
3767   }
3768
3769   llvm_unreachable("Unknown VFP cmp argument!");
3770 }
3771
3772 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3773 /// f32 and even f64 comparisons to integer ones.
3774 SDValue
3775 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3776   SDValue Chain = Op.getOperand(0);
3777   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3778   SDValue LHS = Op.getOperand(2);
3779   SDValue RHS = Op.getOperand(3);
3780   SDValue Dest = Op.getOperand(4);
3781   SDLoc dl(Op);
3782
3783   bool LHSSeenZero = false;
3784   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3785   bool RHSSeenZero = false;
3786   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3787   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3788     // If unsafe fp math optimization is enabled and there are no other uses of
3789     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3790     // to an integer comparison.
3791     if (CC == ISD::SETOEQ)
3792       CC = ISD::SETEQ;
3793     else if (CC == ISD::SETUNE)
3794       CC = ISD::SETNE;
3795
3796     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3797     SDValue ARMcc;
3798     if (LHS.getValueType() == MVT::f32) {
3799       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3800                         bitcastf32Toi32(LHS, DAG), Mask);
3801       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3802                         bitcastf32Toi32(RHS, DAG), Mask);
3803       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3804       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3805       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3806                          Chain, Dest, ARMcc, CCR, Cmp);
3807     }
3808
3809     SDValue LHS1, LHS2;
3810     SDValue RHS1, RHS2;
3811     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3812     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3813     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3814     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3815     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3816     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3817     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3818     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3819     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3820   }
3821
3822   return SDValue();
3823 }
3824
3825 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3826   SDValue Chain = Op.getOperand(0);
3827   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3828   SDValue LHS = Op.getOperand(2);
3829   SDValue RHS = Op.getOperand(3);
3830   SDValue Dest = Op.getOperand(4);
3831   SDLoc dl(Op);
3832
3833   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3834     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3835                                                     dl);
3836
3837     // If softenSetCCOperands only returned one value, we should compare it to
3838     // zero.
3839     if (!RHS.getNode()) {
3840       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3841       CC = ISD::SETNE;
3842     }
3843   }
3844
3845   if (LHS.getValueType() == MVT::i32) {
3846     SDValue ARMcc;
3847     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3848     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3849     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3850                        Chain, Dest, ARMcc, CCR, Cmp);
3851   }
3852
3853   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3854
3855   if (getTargetMachine().Options.UnsafeFPMath &&
3856       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3857        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3858     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3859     if (Result.getNode())
3860       return Result;
3861   }
3862
3863   ARMCC::CondCodes CondCode, CondCode2;
3864   FPCCToARMCC(CC, CondCode, CondCode2);
3865
3866   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3867   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3868   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3869   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3870   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3871   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3872   if (CondCode2 != ARMCC::AL) {
3873     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3874     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3875     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3876   }
3877   return Res;
3878 }
3879
3880 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3881   SDValue Chain = Op.getOperand(0);
3882   SDValue Table = Op.getOperand(1);
3883   SDValue Index = Op.getOperand(2);
3884   SDLoc dl(Op);
3885
3886   EVT PTy = getPointerTy(DAG.getDataLayout());
3887   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3888   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3889   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3890   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3891   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3892   if (Subtarget->isThumb2()) {
3893     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3894     // which does another jump to the destination. This also makes it easier
3895     // to translate it to TBB / TBH later.
3896     // FIXME: This might not work if the function is extremely large.
3897     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3898                        Addr, Op.getOperand(2), JTI);
3899   }
3900   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3901     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3902                        MachinePointerInfo::getJumpTable(),
3903                        false, false, false, 0);
3904     Chain = Addr.getValue(1);
3905     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3906     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3907   } else {
3908     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3909                        MachinePointerInfo::getJumpTable(),
3910                        false, false, false, 0);
3911     Chain = Addr.getValue(1);
3912     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3913   }
3914 }
3915
3916 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3917   EVT VT = Op.getValueType();
3918   SDLoc dl(Op);
3919
3920   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3921     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3922       return Op;
3923     return DAG.UnrollVectorOp(Op.getNode());
3924   }
3925
3926   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3927          "Invalid type for custom lowering!");
3928   if (VT != MVT::v4i16)
3929     return DAG.UnrollVectorOp(Op.getNode());
3930
3931   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3932   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3933 }
3934
3935 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3936   EVT VT = Op.getValueType();
3937   if (VT.isVector())
3938     return LowerVectorFP_TO_INT(Op, DAG);
3939   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3940     RTLIB::Libcall LC;
3941     if (Op.getOpcode() == ISD::FP_TO_SINT)
3942       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3943                               Op.getValueType());
3944     else
3945       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3946                               Op.getValueType());
3947     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3948                        /*isSigned*/ false, SDLoc(Op)).first;
3949   }
3950
3951   return Op;
3952 }
3953
3954 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3955   EVT VT = Op.getValueType();
3956   SDLoc dl(Op);
3957
3958   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3959     if (VT.getVectorElementType() == MVT::f32)
3960       return Op;
3961     return DAG.UnrollVectorOp(Op.getNode());
3962   }
3963
3964   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3965          "Invalid type for custom lowering!");
3966   if (VT != MVT::v4f32)
3967     return DAG.UnrollVectorOp(Op.getNode());
3968
3969   unsigned CastOpc;
3970   unsigned Opc;
3971   switch (Op.getOpcode()) {
3972   default: llvm_unreachable("Invalid opcode!");
3973   case ISD::SINT_TO_FP:
3974     CastOpc = ISD::SIGN_EXTEND;
3975     Opc = ISD::SINT_TO_FP;
3976     break;
3977   case ISD::UINT_TO_FP:
3978     CastOpc = ISD::ZERO_EXTEND;
3979     Opc = ISD::UINT_TO_FP;
3980     break;
3981   }
3982
3983   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3984   return DAG.getNode(Opc, dl, VT, Op);
3985 }
3986
3987 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3988   EVT VT = Op.getValueType();
3989   if (VT.isVector())
3990     return LowerVectorINT_TO_FP(Op, DAG);
3991   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3992     RTLIB::Libcall LC;
3993     if (Op.getOpcode() == ISD::SINT_TO_FP)
3994       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3995                               Op.getValueType());
3996     else
3997       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3998                               Op.getValueType());
3999     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
4000                        /*isSigned*/ false, SDLoc(Op)).first;
4001   }
4002
4003   return Op;
4004 }
4005
4006 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4007   // Implement fcopysign with a fabs and a conditional fneg.
4008   SDValue Tmp0 = Op.getOperand(0);
4009   SDValue Tmp1 = Op.getOperand(1);
4010   SDLoc dl(Op);
4011   EVT VT = Op.getValueType();
4012   EVT SrcVT = Tmp1.getValueType();
4013   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4014     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4015   bool UseNEON = !InGPR && Subtarget->hasNEON();
4016
4017   if (UseNEON) {
4018     // Use VBSL to copy the sign bit.
4019     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4020     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4021                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4022     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4023     if (VT == MVT::f64)
4024       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4025                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4026                          DAG.getConstant(32, dl, MVT::i32));
4027     else /*if (VT == MVT::f32)*/
4028       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4029     if (SrcVT == MVT::f32) {
4030       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4031       if (VT == MVT::f64)
4032         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4033                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4034                            DAG.getConstant(32, dl, MVT::i32));
4035     } else if (VT == MVT::f32)
4036       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4037                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4038                          DAG.getConstant(32, dl, MVT::i32));
4039     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4040     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4041
4042     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4043                                             dl, MVT::i32);
4044     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4045     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4046                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4047
4048     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4049                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4050                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4051     if (VT == MVT::f32) {
4052       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4053       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4054                         DAG.getConstant(0, dl, MVT::i32));
4055     } else {
4056       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4057     }
4058
4059     return Res;
4060   }
4061
4062   // Bitcast operand 1 to i32.
4063   if (SrcVT == MVT::f64)
4064     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4065                        Tmp1).getValue(1);
4066   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4067
4068   // Or in the signbit with integer operations.
4069   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4070   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4071   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4072   if (VT == MVT::f32) {
4073     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4074                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4075     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4076                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4077   }
4078
4079   // f64: Or the high part with signbit and then combine two parts.
4080   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4081                      Tmp0);
4082   SDValue Lo = Tmp0.getValue(0);
4083   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4084   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4085   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4086 }
4087
4088 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4089   MachineFunction &MF = DAG.getMachineFunction();
4090   MachineFrameInfo *MFI = MF.getFrameInfo();
4091   MFI->setReturnAddressIsTaken(true);
4092
4093   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4094     return SDValue();
4095
4096   EVT VT = Op.getValueType();
4097   SDLoc dl(Op);
4098   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4099   if (Depth) {
4100     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4101     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4102     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4103                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4104                        MachinePointerInfo(), false, false, false, 0);
4105   }
4106
4107   // Return LR, which contains the return address. Mark it an implicit live-in.
4108   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4109   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4110 }
4111
4112 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4113   const ARMBaseRegisterInfo &ARI =
4114     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4115   MachineFunction &MF = DAG.getMachineFunction();
4116   MachineFrameInfo *MFI = MF.getFrameInfo();
4117   MFI->setFrameAddressIsTaken(true);
4118
4119   EVT VT = Op.getValueType();
4120   SDLoc dl(Op);  // FIXME probably not meaningful
4121   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4122   unsigned FrameReg = ARI.getFrameRegister(MF);
4123   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4124   while (Depth--)
4125     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4126                             MachinePointerInfo(),
4127                             false, false, false, 0);
4128   return FrameAddr;
4129 }
4130
4131 // FIXME? Maybe this could be a TableGen attribute on some registers and
4132 // this table could be generated automatically from RegInfo.
4133 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4134                                               SelectionDAG &DAG) const {
4135   unsigned Reg = StringSwitch<unsigned>(RegName)
4136                        .Case("sp", ARM::SP)
4137                        .Default(0);
4138   if (Reg)
4139     return Reg;
4140   report_fatal_error(Twine("Invalid register name \""
4141                               + StringRef(RegName)  + "\"."));
4142 }
4143
4144 // Result is 64 bit value so split into two 32 bit values and return as a
4145 // pair of values.
4146 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4147                                 SelectionDAG &DAG) {
4148   SDLoc DL(N);
4149
4150   // This function is only supposed to be called for i64 type destination.
4151   assert(N->getValueType(0) == MVT::i64
4152           && "ExpandREAD_REGISTER called for non-i64 type result.");
4153
4154   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4155                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4156                              N->getOperand(0),
4157                              N->getOperand(1));
4158
4159   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4160                     Read.getValue(1)));
4161   Results.push_back(Read.getOperand(0));
4162 }
4163
4164 /// ExpandBITCAST - If the target supports VFP, this function is called to
4165 /// expand a bit convert where either the source or destination type is i64 to
4166 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4167 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4168 /// vectors), since the legalizer won't know what to do with that.
4169 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4170   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4171   SDLoc dl(N);
4172   SDValue Op = N->getOperand(0);
4173
4174   // This function is only supposed to be called for i64 types, either as the
4175   // source or destination of the bit convert.
4176   EVT SrcVT = Op.getValueType();
4177   EVT DstVT = N->getValueType(0);
4178   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4179          "ExpandBITCAST called for non-i64 type");
4180
4181   // Turn i64->f64 into VMOVDRR.
4182   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4183     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4184                              DAG.getConstant(0, dl, MVT::i32));
4185     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4186                              DAG.getConstant(1, dl, MVT::i32));
4187     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4188                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4189   }
4190
4191   // Turn f64->i64 into VMOVRRD.
4192   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4193     SDValue Cvt;
4194     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4195         SrcVT.getVectorNumElements() > 1)
4196       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4197                         DAG.getVTList(MVT::i32, MVT::i32),
4198                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4199     else
4200       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4201                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4202     // Merge the pieces into a single i64 value.
4203     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4204   }
4205
4206   return SDValue();
4207 }
4208
4209 /// getZeroVector - Returns a vector of specified type with all zero elements.
4210 /// Zero vectors are used to represent vector negation and in those cases
4211 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4212 /// not support i64 elements, so sometimes the zero vectors will need to be
4213 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4214 /// zero vector.
4215 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4216   assert(VT.isVector() && "Expected a vector type");
4217   // The canonical modified immediate encoding of a zero vector is....0!
4218   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4219   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4220   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4221   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4222 }
4223
4224 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4225 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4226 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4227                                                 SelectionDAG &DAG) const {
4228   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4229   EVT VT = Op.getValueType();
4230   unsigned VTBits = VT.getSizeInBits();
4231   SDLoc dl(Op);
4232   SDValue ShOpLo = Op.getOperand(0);
4233   SDValue ShOpHi = Op.getOperand(1);
4234   SDValue ShAmt  = Op.getOperand(2);
4235   SDValue ARMcc;
4236   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4237
4238   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4239
4240   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4241                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4242   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4243   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4244                                    DAG.getConstant(VTBits, dl, MVT::i32));
4245   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4246   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4247   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4248
4249   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4250   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4251                           ISD::SETGE, ARMcc, DAG, dl);
4252   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4253   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4254                            CCR, Cmp);
4255
4256   SDValue Ops[2] = { Lo, Hi };
4257   return DAG.getMergeValues(Ops, dl);
4258 }
4259
4260 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4261 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4262 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4263                                                SelectionDAG &DAG) const {
4264   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4265   EVT VT = Op.getValueType();
4266   unsigned VTBits = VT.getSizeInBits();
4267   SDLoc dl(Op);
4268   SDValue ShOpLo = Op.getOperand(0);
4269   SDValue ShOpHi = Op.getOperand(1);
4270   SDValue ShAmt  = Op.getOperand(2);
4271   SDValue ARMcc;
4272
4273   assert(Op.getOpcode() == ISD::SHL_PARTS);
4274   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4275                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4276   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4277   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4278                                    DAG.getConstant(VTBits, dl, MVT::i32));
4279   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4280   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4281
4282   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4283   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4284   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4285                           ISD::SETGE, ARMcc, DAG, dl);
4286   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4287   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4288                            CCR, Cmp);
4289
4290   SDValue Ops[2] = { Lo, Hi };
4291   return DAG.getMergeValues(Ops, dl);
4292 }
4293
4294 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4295                                             SelectionDAG &DAG) const {
4296   // The rounding mode is in bits 23:22 of the FPSCR.
4297   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4298   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4299   // so that the shift + and get folded into a bitfield extract.
4300   SDLoc dl(Op);
4301   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4302                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4303                                               MVT::i32));
4304   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4305                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4306   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4307                               DAG.getConstant(22, dl, MVT::i32));
4308   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4309                      DAG.getConstant(3, dl, MVT::i32));
4310 }
4311
4312 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4313                          const ARMSubtarget *ST) {
4314   SDLoc dl(N);
4315   EVT VT = N->getValueType(0);
4316   if (VT.isVector()) {
4317     assert(ST->hasNEON());
4318
4319     // Compute the least significant set bit: LSB = X & -X
4320     SDValue X = N->getOperand(0);
4321     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4322     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4323
4324     EVT ElemTy = VT.getVectorElementType();
4325
4326     if (ElemTy == MVT::i8) {
4327       // Compute with: cttz(x) = ctpop(lsb - 1)
4328       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4329                                 DAG.getTargetConstant(1, dl, ElemTy));
4330       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4331       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4332     }
4333
4334     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4335         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4336       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4337       unsigned NumBits = ElemTy.getSizeInBits();
4338       SDValue WidthMinus1 =
4339           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4340                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4341       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4342       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4343     }
4344
4345     // Compute with: cttz(x) = ctpop(lsb - 1)
4346
4347     // Since we can only compute the number of bits in a byte with vcnt.8, we
4348     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4349     // and i64.
4350
4351     // Compute LSB - 1.
4352     SDValue Bits;
4353     if (ElemTy == MVT::i64) {
4354       // Load constant 0xffff'ffff'ffff'ffff to register.
4355       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4356                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4357       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4358     } else {
4359       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4360                                 DAG.getTargetConstant(1, dl, ElemTy));
4361       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4362     }
4363
4364     // Count #bits with vcnt.8.
4365     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4366     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4367     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4368
4369     // Gather the #bits with vpaddl (pairwise add.)
4370     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4371     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4372         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4373         Cnt8);
4374     if (ElemTy == MVT::i16)
4375       return Cnt16;
4376
4377     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4378     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4379         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4380         Cnt16);
4381     if (ElemTy == MVT::i32)
4382       return Cnt32;
4383
4384     assert(ElemTy == MVT::i64);
4385     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4386         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4387         Cnt32);
4388     return Cnt64;
4389   }
4390
4391   if (!ST->hasV6T2Ops())
4392     return SDValue();
4393
4394   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4395   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4396 }
4397
4398 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4399 /// for each 16-bit element from operand, repeated.  The basic idea is to
4400 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4401 ///
4402 /// Trace for v4i16:
4403 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4404 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4405 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4406 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4407 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4408 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4409 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4410 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4411 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4412   EVT VT = N->getValueType(0);
4413   SDLoc DL(N);
4414
4415   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4416   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4417   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4418   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4419   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4420   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4421 }
4422
4423 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4424 /// bit-count for each 16-bit element from the operand.  We need slightly
4425 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4426 /// 64/128-bit registers.
4427 ///
4428 /// Trace for v4i16:
4429 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4430 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4431 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4432 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4433 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4434   EVT VT = N->getValueType(0);
4435   SDLoc DL(N);
4436
4437   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4438   if (VT.is64BitVector()) {
4439     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4440     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4441                        DAG.getIntPtrConstant(0, DL));
4442   } else {
4443     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4444                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4445     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4446   }
4447 }
4448
4449 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4450 /// bit-count for each 32-bit element from the operand.  The idea here is
4451 /// to split the vector into 16-bit elements, leverage the 16-bit count
4452 /// routine, and then combine the results.
4453 ///
4454 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4455 /// input    = [v0    v1    ] (vi: 32-bit elements)
4456 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4457 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4458 /// vrev: N0 = [k1 k0 k3 k2 ]
4459 ///            [k0 k1 k2 k3 ]
4460 ///       N1 =+[k1 k0 k3 k2 ]
4461 ///            [k0 k2 k1 k3 ]
4462 ///       N2 =+[k1 k3 k0 k2 ]
4463 ///            [k0    k2    k1    k3    ]
4464 /// Extended =+[k1    k3    k0    k2    ]
4465 ///            [k0    k2    ]
4466 /// Extracted=+[k1    k3    ]
4467 ///
4468 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4469   EVT VT = N->getValueType(0);
4470   SDLoc DL(N);
4471
4472   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4473
4474   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4475   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4476   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4477   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4478   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4479
4480   if (VT.is64BitVector()) {
4481     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4482     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4483                        DAG.getIntPtrConstant(0, DL));
4484   } else {
4485     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4486                                     DAG.getIntPtrConstant(0, DL));
4487     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4488   }
4489 }
4490
4491 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4492                           const ARMSubtarget *ST) {
4493   EVT VT = N->getValueType(0);
4494
4495   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4496   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4497           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4498          "Unexpected type for custom ctpop lowering");
4499
4500   if (VT.getVectorElementType() == MVT::i32)
4501     return lowerCTPOP32BitElements(N, DAG);
4502   else
4503     return lowerCTPOP16BitElements(N, DAG);
4504 }
4505
4506 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4507                           const ARMSubtarget *ST) {
4508   EVT VT = N->getValueType(0);
4509   SDLoc dl(N);
4510
4511   if (!VT.isVector())
4512     return SDValue();
4513
4514   // Lower vector shifts on NEON to use VSHL.
4515   assert(ST->hasNEON() && "unexpected vector shift");
4516
4517   // Left shifts translate directly to the vshiftu intrinsic.
4518   if (N->getOpcode() == ISD::SHL)
4519     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4520                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4521                                        MVT::i32),
4522                        N->getOperand(0), N->getOperand(1));
4523
4524   assert((N->getOpcode() == ISD::SRA ||
4525           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4526
4527   // NEON uses the same intrinsics for both left and right shifts.  For
4528   // right shifts, the shift amounts are negative, so negate the vector of
4529   // shift amounts.
4530   EVT ShiftVT = N->getOperand(1).getValueType();
4531   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4532                                      getZeroVector(ShiftVT, DAG, dl),
4533                                      N->getOperand(1));
4534   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4535                              Intrinsic::arm_neon_vshifts :
4536                              Intrinsic::arm_neon_vshiftu);
4537   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4538                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4539                      N->getOperand(0), NegatedCount);
4540 }
4541
4542 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4543                                 const ARMSubtarget *ST) {
4544   EVT VT = N->getValueType(0);
4545   SDLoc dl(N);
4546
4547   // We can get here for a node like i32 = ISD::SHL i32, i64
4548   if (VT != MVT::i64)
4549     return SDValue();
4550
4551   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4552          "Unknown shift to lower!");
4553
4554   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4555   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4556       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4557     return SDValue();
4558
4559   // If we are in thumb mode, we don't have RRX.
4560   if (ST->isThumb1Only()) return SDValue();
4561
4562   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4563   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4564                            DAG.getConstant(0, dl, MVT::i32));
4565   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4566                            DAG.getConstant(1, dl, MVT::i32));
4567
4568   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4569   // captures the result into a carry flag.
4570   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4571   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4572
4573   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4574   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4575
4576   // Merge the pieces into a single i64 value.
4577  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4578 }
4579
4580 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4581   SDValue TmpOp0, TmpOp1;
4582   bool Invert = false;
4583   bool Swap = false;
4584   unsigned Opc = 0;
4585
4586   SDValue Op0 = Op.getOperand(0);
4587   SDValue Op1 = Op.getOperand(1);
4588   SDValue CC = Op.getOperand(2);
4589   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4590   EVT VT = Op.getValueType();
4591   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4592   SDLoc dl(Op);
4593
4594   if (Op1.getValueType().isFloatingPoint()) {
4595     switch (SetCCOpcode) {
4596     default: llvm_unreachable("Illegal FP comparison");
4597     case ISD::SETUNE:
4598     case ISD::SETNE:  Invert = true; // Fallthrough
4599     case ISD::SETOEQ:
4600     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4601     case ISD::SETOLT:
4602     case ISD::SETLT: Swap = true; // Fallthrough
4603     case ISD::SETOGT:
4604     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4605     case ISD::SETOLE:
4606     case ISD::SETLE:  Swap = true; // Fallthrough
4607     case ISD::SETOGE:
4608     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4609     case ISD::SETUGE: Swap = true; // Fallthrough
4610     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4611     case ISD::SETUGT: Swap = true; // Fallthrough
4612     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4613     case ISD::SETUEQ: Invert = true; // Fallthrough
4614     case ISD::SETONE:
4615       // Expand this to (OLT | OGT).
4616       TmpOp0 = Op0;
4617       TmpOp1 = Op1;
4618       Opc = ISD::OR;
4619       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4620       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4621       break;
4622     case ISD::SETUO: Invert = true; // Fallthrough
4623     case ISD::SETO:
4624       // Expand this to (OLT | OGE).
4625       TmpOp0 = Op0;
4626       TmpOp1 = Op1;
4627       Opc = ISD::OR;
4628       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4629       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4630       break;
4631     }
4632   } else {
4633     // Integer comparisons.
4634     switch (SetCCOpcode) {
4635     default: llvm_unreachable("Illegal integer comparison");
4636     case ISD::SETNE:  Invert = true;
4637     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4638     case ISD::SETLT:  Swap = true;
4639     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4640     case ISD::SETLE:  Swap = true;
4641     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4642     case ISD::SETULT: Swap = true;
4643     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4644     case ISD::SETULE: Swap = true;
4645     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4646     }
4647
4648     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4649     if (Opc == ARMISD::VCEQ) {
4650
4651       SDValue AndOp;
4652       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4653         AndOp = Op0;
4654       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4655         AndOp = Op1;
4656
4657       // Ignore bitconvert.
4658       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4659         AndOp = AndOp.getOperand(0);
4660
4661       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4662         Opc = ARMISD::VTST;
4663         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4664         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4665         Invert = !Invert;
4666       }
4667     }
4668   }
4669
4670   if (Swap)
4671     std::swap(Op0, Op1);
4672
4673   // If one of the operands is a constant vector zero, attempt to fold the
4674   // comparison to a specialized compare-against-zero form.
4675   SDValue SingleOp;
4676   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4677     SingleOp = Op0;
4678   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4679     if (Opc == ARMISD::VCGE)
4680       Opc = ARMISD::VCLEZ;
4681     else if (Opc == ARMISD::VCGT)
4682       Opc = ARMISD::VCLTZ;
4683     SingleOp = Op1;
4684   }
4685
4686   SDValue Result;
4687   if (SingleOp.getNode()) {
4688     switch (Opc) {
4689     case ARMISD::VCEQ:
4690       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4691     case ARMISD::VCGE:
4692       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4693     case ARMISD::VCLEZ:
4694       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4695     case ARMISD::VCGT:
4696       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4697     case ARMISD::VCLTZ:
4698       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4699     default:
4700       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4701     }
4702   } else {
4703      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4704   }
4705
4706   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4707
4708   if (Invert)
4709     Result = DAG.getNOT(dl, Result, VT);
4710
4711   return Result;
4712 }
4713
4714 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4715 /// valid vector constant for a NEON instruction with a "modified immediate"
4716 /// operand (e.g., VMOV).  If so, return the encoded value.
4717 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4718                                  unsigned SplatBitSize, SelectionDAG &DAG,
4719                                  SDLoc dl, EVT &VT, bool is128Bits,
4720                                  NEONModImmType type) {
4721   unsigned OpCmode, Imm;
4722
4723   // SplatBitSize is set to the smallest size that splats the vector, so a
4724   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4725   // immediate instructions others than VMOV do not support the 8-bit encoding
4726   // of a zero vector, and the default encoding of zero is supposed to be the
4727   // 32-bit version.
4728   if (SplatBits == 0)
4729     SplatBitSize = 32;
4730
4731   switch (SplatBitSize) {
4732   case 8:
4733     if (type != VMOVModImm)
4734       return SDValue();
4735     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4736     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4737     OpCmode = 0xe;
4738     Imm = SplatBits;
4739     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4740     break;
4741
4742   case 16:
4743     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4744     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4745     if ((SplatBits & ~0xff) == 0) {
4746       // Value = 0x00nn: Op=x, Cmode=100x.
4747       OpCmode = 0x8;
4748       Imm = SplatBits;
4749       break;
4750     }
4751     if ((SplatBits & ~0xff00) == 0) {
4752       // Value = 0xnn00: Op=x, Cmode=101x.
4753       OpCmode = 0xa;
4754       Imm = SplatBits >> 8;
4755       break;
4756     }
4757     return SDValue();
4758
4759   case 32:
4760     // NEON's 32-bit VMOV supports splat values where:
4761     // * only one byte is nonzero, or
4762     // * the least significant byte is 0xff and the second byte is nonzero, or
4763     // * the least significant 2 bytes are 0xff and the third is nonzero.
4764     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4765     if ((SplatBits & ~0xff) == 0) {
4766       // Value = 0x000000nn: Op=x, Cmode=000x.
4767       OpCmode = 0;
4768       Imm = SplatBits;
4769       break;
4770     }
4771     if ((SplatBits & ~0xff00) == 0) {
4772       // Value = 0x0000nn00: Op=x, Cmode=001x.
4773       OpCmode = 0x2;
4774       Imm = SplatBits >> 8;
4775       break;
4776     }
4777     if ((SplatBits & ~0xff0000) == 0) {
4778       // Value = 0x00nn0000: Op=x, Cmode=010x.
4779       OpCmode = 0x4;
4780       Imm = SplatBits >> 16;
4781       break;
4782     }
4783     if ((SplatBits & ~0xff000000) == 0) {
4784       // Value = 0xnn000000: Op=x, Cmode=011x.
4785       OpCmode = 0x6;
4786       Imm = SplatBits >> 24;
4787       break;
4788     }
4789
4790     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4791     if (type == OtherModImm) return SDValue();
4792
4793     if ((SplatBits & ~0xffff) == 0 &&
4794         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4795       // Value = 0x0000nnff: Op=x, Cmode=1100.
4796       OpCmode = 0xc;
4797       Imm = SplatBits >> 8;
4798       break;
4799     }
4800
4801     if ((SplatBits & ~0xffffff) == 0 &&
4802         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4803       // Value = 0x00nnffff: Op=x, Cmode=1101.
4804       OpCmode = 0xd;
4805       Imm = SplatBits >> 16;
4806       break;
4807     }
4808
4809     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4810     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4811     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4812     // and fall through here to test for a valid 64-bit splat.  But, then the
4813     // caller would also need to check and handle the change in size.
4814     return SDValue();
4815
4816   case 64: {
4817     if (type != VMOVModImm)
4818       return SDValue();
4819     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4820     uint64_t BitMask = 0xff;
4821     uint64_t Val = 0;
4822     unsigned ImmMask = 1;
4823     Imm = 0;
4824     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4825       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4826         Val |= BitMask;
4827         Imm |= ImmMask;
4828       } else if ((SplatBits & BitMask) != 0) {
4829         return SDValue();
4830       }
4831       BitMask <<= 8;
4832       ImmMask <<= 1;
4833     }
4834
4835     if (DAG.getDataLayout().isBigEndian())
4836       // swap higher and lower 32 bit word
4837       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4838
4839     // Op=1, Cmode=1110.
4840     OpCmode = 0x1e;
4841     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4842     break;
4843   }
4844
4845   default:
4846     llvm_unreachable("unexpected size for isNEONModifiedImm");
4847   }
4848
4849   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4850   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4851 }
4852
4853 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4854                                            const ARMSubtarget *ST) const {
4855   if (!ST->hasVFP3())
4856     return SDValue();
4857
4858   bool IsDouble = Op.getValueType() == MVT::f64;
4859   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4860
4861   // Use the default (constant pool) lowering for double constants when we have
4862   // an SP-only FPU
4863   if (IsDouble && Subtarget->isFPOnlySP())
4864     return SDValue();
4865
4866   // Try splatting with a VMOV.f32...
4867   APFloat FPVal = CFP->getValueAPF();
4868   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4869
4870   if (ImmVal != -1) {
4871     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4872       // We have code in place to select a valid ConstantFP already, no need to
4873       // do any mangling.
4874       return Op;
4875     }
4876
4877     // It's a float and we are trying to use NEON operations where
4878     // possible. Lower it to a splat followed by an extract.
4879     SDLoc DL(Op);
4880     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4881     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4882                                       NewVal);
4883     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4884                        DAG.getConstant(0, DL, MVT::i32));
4885   }
4886
4887   // The rest of our options are NEON only, make sure that's allowed before
4888   // proceeding..
4889   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4890     return SDValue();
4891
4892   EVT VMovVT;
4893   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4894
4895   // It wouldn't really be worth bothering for doubles except for one very
4896   // important value, which does happen to match: 0.0. So make sure we don't do
4897   // anything stupid.
4898   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4899     return SDValue();
4900
4901   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4902   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4903                                      VMovVT, false, VMOVModImm);
4904   if (NewVal != SDValue()) {
4905     SDLoc DL(Op);
4906     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4907                                       NewVal);
4908     if (IsDouble)
4909       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4910
4911     // It's a float: cast and extract a vector element.
4912     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4913                                        VecConstant);
4914     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4915                        DAG.getConstant(0, DL, MVT::i32));
4916   }
4917
4918   // Finally, try a VMVN.i32
4919   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4920                              false, VMVNModImm);
4921   if (NewVal != SDValue()) {
4922     SDLoc DL(Op);
4923     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4924
4925     if (IsDouble)
4926       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4927
4928     // It's a float: cast and extract a vector element.
4929     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4930                                        VecConstant);
4931     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4932                        DAG.getConstant(0, DL, MVT::i32));
4933   }
4934
4935   return SDValue();
4936 }
4937
4938 // check if an VEXT instruction can handle the shuffle mask when the
4939 // vector sources of the shuffle are the same.
4940 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4941   unsigned NumElts = VT.getVectorNumElements();
4942
4943   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4944   if (M[0] < 0)
4945     return false;
4946
4947   Imm = M[0];
4948
4949   // If this is a VEXT shuffle, the immediate value is the index of the first
4950   // element.  The other shuffle indices must be the successive elements after
4951   // the first one.
4952   unsigned ExpectedElt = Imm;
4953   for (unsigned i = 1; i < NumElts; ++i) {
4954     // Increment the expected index.  If it wraps around, just follow it
4955     // back to index zero and keep going.
4956     ++ExpectedElt;
4957     if (ExpectedElt == NumElts)
4958       ExpectedElt = 0;
4959
4960     if (M[i] < 0) continue; // ignore UNDEF indices
4961     if (ExpectedElt != static_cast<unsigned>(M[i]))
4962       return false;
4963   }
4964
4965   return true;
4966 }
4967
4968
4969 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4970                        bool &ReverseVEXT, unsigned &Imm) {
4971   unsigned NumElts = VT.getVectorNumElements();
4972   ReverseVEXT = false;
4973
4974   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4975   if (M[0] < 0)
4976     return false;
4977
4978   Imm = M[0];
4979
4980   // If this is a VEXT shuffle, the immediate value is the index of the first
4981   // element.  The other shuffle indices must be the successive elements after
4982   // the first one.
4983   unsigned ExpectedElt = Imm;
4984   for (unsigned i = 1; i < NumElts; ++i) {
4985     // Increment the expected index.  If it wraps around, it may still be
4986     // a VEXT but the source vectors must be swapped.
4987     ExpectedElt += 1;
4988     if (ExpectedElt == NumElts * 2) {
4989       ExpectedElt = 0;
4990       ReverseVEXT = true;
4991     }
4992
4993     if (M[i] < 0) continue; // ignore UNDEF indices
4994     if (ExpectedElt != static_cast<unsigned>(M[i]))
4995       return false;
4996   }
4997
4998   // Adjust the index value if the source operands will be swapped.
4999   if (ReverseVEXT)
5000     Imm -= NumElts;
5001
5002   return true;
5003 }
5004
5005 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5006 /// instruction with the specified blocksize.  (The order of the elements
5007 /// within each block of the vector is reversed.)
5008 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5009   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5010          "Only possible block sizes for VREV are: 16, 32, 64");
5011
5012   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5013   if (EltSz == 64)
5014     return false;
5015
5016   unsigned NumElts = VT.getVectorNumElements();
5017   unsigned BlockElts = M[0] + 1;
5018   // If the first shuffle index is UNDEF, be optimistic.
5019   if (M[0] < 0)
5020     BlockElts = BlockSize / EltSz;
5021
5022   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5023     return false;
5024
5025   for (unsigned i = 0; i < NumElts; ++i) {
5026     if (M[i] < 0) continue; // ignore UNDEF indices
5027     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5028       return false;
5029   }
5030
5031   return true;
5032 }
5033
5034 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5035   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5036   // range, then 0 is placed into the resulting vector. So pretty much any mask
5037   // of 8 elements can work here.
5038   return VT == MVT::v8i8 && M.size() == 8;
5039 }
5040
5041 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5042   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5043   if (EltSz == 64)
5044     return false;
5045
5046   unsigned NumElts = VT.getVectorNumElements();
5047   WhichResult = (M[0] == 0 ? 0 : 1);
5048   for (unsigned i = 0; i < NumElts; i += 2) {
5049     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
5050         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
5051       return false;
5052   }
5053   return true;
5054 }
5055
5056 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5057 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5058 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5059 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5060   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5061   if (EltSz == 64)
5062     return false;
5063
5064   unsigned NumElts = VT.getVectorNumElements();
5065   WhichResult = (M[0] == 0 ? 0 : 1);
5066   for (unsigned i = 0; i < NumElts; i += 2) {
5067     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
5068         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
5069       return false;
5070   }
5071   return true;
5072 }
5073
5074 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5075   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5076   if (EltSz == 64)
5077     return false;
5078
5079   unsigned NumElts = VT.getVectorNumElements();
5080   WhichResult = (M[0] == 0 ? 0 : 1);
5081   for (unsigned i = 0; i != NumElts; ++i) {
5082     if (M[i] < 0) continue; // ignore UNDEF indices
5083     if ((unsigned) M[i] != 2 * i + WhichResult)
5084       return false;
5085   }
5086
5087   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5088   if (VT.is64BitVector() && EltSz == 32)
5089     return false;
5090
5091   return true;
5092 }
5093
5094 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5095 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5096 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5097 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5098   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5099   if (EltSz == 64)
5100     return false;
5101
5102   unsigned Half = VT.getVectorNumElements() / 2;
5103   WhichResult = (M[0] == 0 ? 0 : 1);
5104   for (unsigned j = 0; j != 2; ++j) {
5105     unsigned Idx = WhichResult;
5106     for (unsigned i = 0; i != Half; ++i) {
5107       int MIdx = M[i + j * Half];
5108       if (MIdx >= 0 && (unsigned) MIdx != Idx)
5109         return false;
5110       Idx += 2;
5111     }
5112   }
5113
5114   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5115   if (VT.is64BitVector() && EltSz == 32)
5116     return false;
5117
5118   return true;
5119 }
5120
5121 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5122   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5123   if (EltSz == 64)
5124     return false;
5125
5126   unsigned NumElts = VT.getVectorNumElements();
5127   WhichResult = (M[0] == 0 ? 0 : 1);
5128   unsigned Idx = WhichResult * NumElts / 2;
5129   for (unsigned i = 0; i != NumElts; i += 2) {
5130     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5131         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5132       return false;
5133     Idx += 1;
5134   }
5135
5136   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5137   if (VT.is64BitVector() && EltSz == 32)
5138     return false;
5139
5140   return true;
5141 }
5142
5143 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5144 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5145 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5146 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5147   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5148   if (EltSz == 64)
5149     return false;
5150
5151   unsigned NumElts = VT.getVectorNumElements();
5152   WhichResult = (M[0] == 0 ? 0 : 1);
5153   unsigned Idx = WhichResult * NumElts / 2;
5154   for (unsigned i = 0; i != NumElts; i += 2) {
5155     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5156         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5157       return false;
5158     Idx += 1;
5159   }
5160
5161   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5162   if (VT.is64BitVector() && EltSz == 32)
5163     return false;
5164
5165   return true;
5166 }
5167
5168 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5169 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5170 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5171                                            unsigned &WhichResult,
5172                                            bool &isV_UNDEF) {
5173   isV_UNDEF = false;
5174   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5175     return ARMISD::VTRN;
5176   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5177     return ARMISD::VUZP;
5178   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5179     return ARMISD::VZIP;
5180
5181   isV_UNDEF = true;
5182   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5183     return ARMISD::VTRN;
5184   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5185     return ARMISD::VUZP;
5186   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5187     return ARMISD::VZIP;
5188
5189   return 0;
5190 }
5191
5192 /// \return true if this is a reverse operation on an vector.
5193 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5194   unsigned NumElts = VT.getVectorNumElements();
5195   // Make sure the mask has the right size.
5196   if (NumElts != M.size())
5197       return false;
5198
5199   // Look for <15, ..., 3, -1, 1, 0>.
5200   for (unsigned i = 0; i != NumElts; ++i)
5201     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5202       return false;
5203
5204   return true;
5205 }
5206
5207 // If N is an integer constant that can be moved into a register in one
5208 // instruction, return an SDValue of such a constant (will become a MOV
5209 // instruction).  Otherwise return null.
5210 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5211                                      const ARMSubtarget *ST, SDLoc dl) {
5212   uint64_t Val;
5213   if (!isa<ConstantSDNode>(N))
5214     return SDValue();
5215   Val = cast<ConstantSDNode>(N)->getZExtValue();
5216
5217   if (ST->isThumb1Only()) {
5218     if (Val <= 255 || ~Val <= 255)
5219       return DAG.getConstant(Val, dl, MVT::i32);
5220   } else {
5221     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5222       return DAG.getConstant(Val, dl, MVT::i32);
5223   }
5224   return SDValue();
5225 }
5226
5227 // If this is a case we can't handle, return null and let the default
5228 // expansion code take care of it.
5229 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5230                                              const ARMSubtarget *ST) const {
5231   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5232   SDLoc dl(Op);
5233   EVT VT = Op.getValueType();
5234
5235   APInt SplatBits, SplatUndef;
5236   unsigned SplatBitSize;
5237   bool HasAnyUndefs;
5238   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5239     if (SplatBitSize <= 64) {
5240       // Check if an immediate VMOV works.
5241       EVT VmovVT;
5242       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5243                                       SplatUndef.getZExtValue(), SplatBitSize,
5244                                       DAG, dl, VmovVT, VT.is128BitVector(),
5245                                       VMOVModImm);
5246       if (Val.getNode()) {
5247         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5248         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5249       }
5250
5251       // Try an immediate VMVN.
5252       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5253       Val = isNEONModifiedImm(NegatedImm,
5254                                       SplatUndef.getZExtValue(), SplatBitSize,
5255                                       DAG, dl, VmovVT, VT.is128BitVector(),
5256                                       VMVNModImm);
5257       if (Val.getNode()) {
5258         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5259         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5260       }
5261
5262       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5263       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5264         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5265         if (ImmVal != -1) {
5266           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5267           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5268         }
5269       }
5270     }
5271   }
5272
5273   // Scan through the operands to see if only one value is used.
5274   //
5275   // As an optimisation, even if more than one value is used it may be more
5276   // profitable to splat with one value then change some lanes.
5277   //
5278   // Heuristically we decide to do this if the vector has a "dominant" value,
5279   // defined as splatted to more than half of the lanes.
5280   unsigned NumElts = VT.getVectorNumElements();
5281   bool isOnlyLowElement = true;
5282   bool usesOnlyOneValue = true;
5283   bool hasDominantValue = false;
5284   bool isConstant = true;
5285
5286   // Map of the number of times a particular SDValue appears in the
5287   // element list.
5288   DenseMap<SDValue, unsigned> ValueCounts;
5289   SDValue Value;
5290   for (unsigned i = 0; i < NumElts; ++i) {
5291     SDValue V = Op.getOperand(i);
5292     if (V.getOpcode() == ISD::UNDEF)
5293       continue;
5294     if (i > 0)
5295       isOnlyLowElement = false;
5296     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5297       isConstant = false;
5298
5299     ValueCounts.insert(std::make_pair(V, 0));
5300     unsigned &Count = ValueCounts[V];
5301
5302     // Is this value dominant? (takes up more than half of the lanes)
5303     if (++Count > (NumElts / 2)) {
5304       hasDominantValue = true;
5305       Value = V;
5306     }
5307   }
5308   if (ValueCounts.size() != 1)
5309     usesOnlyOneValue = false;
5310   if (!Value.getNode() && ValueCounts.size() > 0)
5311     Value = ValueCounts.begin()->first;
5312
5313   if (ValueCounts.size() == 0)
5314     return DAG.getUNDEF(VT);
5315
5316   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5317   // Keep going if we are hitting this case.
5318   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5319     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5320
5321   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5322
5323   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5324   // i32 and try again.
5325   if (hasDominantValue && EltSize <= 32) {
5326     if (!isConstant) {
5327       SDValue N;
5328
5329       // If we are VDUPing a value that comes directly from a vector, that will
5330       // cause an unnecessary move to and from a GPR, where instead we could
5331       // just use VDUPLANE. We can only do this if the lane being extracted
5332       // is at a constant index, as the VDUP from lane instructions only have
5333       // constant-index forms.
5334       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5335           isa<ConstantSDNode>(Value->getOperand(1))) {
5336         // We need to create a new undef vector to use for the VDUPLANE if the
5337         // size of the vector from which we get the value is different than the
5338         // size of the vector that we need to create. We will insert the element
5339         // such that the register coalescer will remove unnecessary copies.
5340         if (VT != Value->getOperand(0).getValueType()) {
5341           ConstantSDNode *constIndex;
5342           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5343           assert(constIndex && "The index is not a constant!");
5344           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5345                              VT.getVectorNumElements();
5346           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5347                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5348                         Value, DAG.getConstant(index, dl, MVT::i32)),
5349                            DAG.getConstant(index, dl, MVT::i32));
5350         } else
5351           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5352                         Value->getOperand(0), Value->getOperand(1));
5353       } else
5354         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5355
5356       if (!usesOnlyOneValue) {
5357         // The dominant value was splatted as 'N', but we now have to insert
5358         // all differing elements.
5359         for (unsigned I = 0; I < NumElts; ++I) {
5360           if (Op.getOperand(I) == Value)
5361             continue;
5362           SmallVector<SDValue, 3> Ops;
5363           Ops.push_back(N);
5364           Ops.push_back(Op.getOperand(I));
5365           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5366           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5367         }
5368       }
5369       return N;
5370     }
5371     if (VT.getVectorElementType().isFloatingPoint()) {
5372       SmallVector<SDValue, 8> Ops;
5373       for (unsigned i = 0; i < NumElts; ++i)
5374         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5375                                   Op.getOperand(i)));
5376       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5377       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5378       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5379       if (Val.getNode())
5380         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5381     }
5382     if (usesOnlyOneValue) {
5383       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5384       if (isConstant && Val.getNode())
5385         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5386     }
5387   }
5388
5389   // If all elements are constants and the case above didn't get hit, fall back
5390   // to the default expansion, which will generate a load from the constant
5391   // pool.
5392   if (isConstant)
5393     return SDValue();
5394
5395   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5396   if (NumElts >= 4) {
5397     SDValue shuffle = ReconstructShuffle(Op, DAG);
5398     if (shuffle != SDValue())
5399       return shuffle;
5400   }
5401
5402   // Vectors with 32- or 64-bit elements can be built by directly assigning
5403   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5404   // will be legalized.
5405   if (EltSize >= 32) {
5406     // Do the expansion with floating-point types, since that is what the VFP
5407     // registers are defined to use, and since i64 is not legal.
5408     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5409     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5410     SmallVector<SDValue, 8> Ops;
5411     for (unsigned i = 0; i < NumElts; ++i)
5412       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5413     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5414     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5415   }
5416
5417   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5418   // know the default expansion would otherwise fall back on something even
5419   // worse. For a vector with one or two non-undef values, that's
5420   // scalar_to_vector for the elements followed by a shuffle (provided the
5421   // shuffle is valid for the target) and materialization element by element
5422   // on the stack followed by a load for everything else.
5423   if (!isConstant && !usesOnlyOneValue) {
5424     SDValue Vec = DAG.getUNDEF(VT);
5425     for (unsigned i = 0 ; i < NumElts; ++i) {
5426       SDValue V = Op.getOperand(i);
5427       if (V.getOpcode() == ISD::UNDEF)
5428         continue;
5429       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5430       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5431     }
5432     return Vec;
5433   }
5434
5435   return SDValue();
5436 }
5437
5438 // Gather data to see if the operation can be modelled as a
5439 // shuffle in combination with VEXTs.
5440 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5441                                               SelectionDAG &DAG) const {
5442   SDLoc dl(Op);
5443   EVT VT = Op.getValueType();
5444   unsigned NumElts = VT.getVectorNumElements();
5445
5446   SmallVector<SDValue, 2> SourceVecs;
5447   SmallVector<unsigned, 2> MinElts;
5448   SmallVector<unsigned, 2> MaxElts;
5449
5450   for (unsigned i = 0; i < NumElts; ++i) {
5451     SDValue V = Op.getOperand(i);
5452     if (V.getOpcode() == ISD::UNDEF)
5453       continue;
5454     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5455       // A shuffle can only come from building a vector from various
5456       // elements of other vectors.
5457       return SDValue();
5458     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5459                VT.getVectorElementType()) {
5460       // This code doesn't know how to handle shuffles where the vector
5461       // element types do not match (this happens because type legalization
5462       // promotes the return type of EXTRACT_VECTOR_ELT).
5463       // FIXME: It might be appropriate to extend this code to handle
5464       // mismatched types.
5465       return SDValue();
5466     }
5467
5468     // Record this extraction against the appropriate vector if possible...
5469     SDValue SourceVec = V.getOperand(0);
5470     // If the element number isn't a constant, we can't effectively
5471     // analyze what's going on.
5472     if (!isa<ConstantSDNode>(V.getOperand(1)))
5473       return SDValue();
5474     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5475     bool FoundSource = false;
5476     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5477       if (SourceVecs[j] == SourceVec) {
5478         if (MinElts[j] > EltNo)
5479           MinElts[j] = EltNo;
5480         if (MaxElts[j] < EltNo)
5481           MaxElts[j] = EltNo;
5482         FoundSource = true;
5483         break;
5484       }
5485     }
5486
5487     // Or record a new source if not...
5488     if (!FoundSource) {
5489       SourceVecs.push_back(SourceVec);
5490       MinElts.push_back(EltNo);
5491       MaxElts.push_back(EltNo);
5492     }
5493   }
5494
5495   // Currently only do something sane when at most two source vectors
5496   // involved.
5497   if (SourceVecs.size() > 2)
5498     return SDValue();
5499
5500   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5501   int VEXTOffsets[2] = {0, 0};
5502
5503   // This loop extracts the usage patterns of the source vectors
5504   // and prepares appropriate SDValues for a shuffle if possible.
5505   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5506     if (SourceVecs[i].getValueType() == VT) {
5507       // No VEXT necessary
5508       ShuffleSrcs[i] = SourceVecs[i];
5509       VEXTOffsets[i] = 0;
5510       continue;
5511     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5512       // It probably isn't worth padding out a smaller vector just to
5513       // break it down again in a shuffle.
5514       return SDValue();
5515     }
5516
5517     // Since only 64-bit and 128-bit vectors are legal on ARM and
5518     // we've eliminated the other cases...
5519     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5520            "unexpected vector sizes in ReconstructShuffle");
5521
5522     if (MaxElts[i] - MinElts[i] >= NumElts) {
5523       // Span too large for a VEXT to cope
5524       return SDValue();
5525     }
5526
5527     if (MinElts[i] >= NumElts) {
5528       // The extraction can just take the second half
5529       VEXTOffsets[i] = NumElts;
5530       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5531                                    SourceVecs[i],
5532                                    DAG.getIntPtrConstant(NumElts, dl));
5533     } else if (MaxElts[i] < NumElts) {
5534       // The extraction can just take the first half
5535       VEXTOffsets[i] = 0;
5536       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5537                                    SourceVecs[i],
5538                                    DAG.getIntPtrConstant(0, dl));
5539     } else {
5540       // An actual VEXT is needed
5541       VEXTOffsets[i] = MinElts[i];
5542       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5543                                      SourceVecs[i],
5544                                      DAG.getIntPtrConstant(0, dl));
5545       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5546                                      SourceVecs[i],
5547                                      DAG.getIntPtrConstant(NumElts, dl));
5548       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5549                                    DAG.getConstant(VEXTOffsets[i], dl,
5550                                                    MVT::i32));
5551     }
5552   }
5553
5554   SmallVector<int, 8> Mask;
5555
5556   for (unsigned i = 0; i < NumElts; ++i) {
5557     SDValue Entry = Op.getOperand(i);
5558     if (Entry.getOpcode() == ISD::UNDEF) {
5559       Mask.push_back(-1);
5560       continue;
5561     }
5562
5563     SDValue ExtractVec = Entry.getOperand(0);
5564     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5565                                           .getOperand(1))->getSExtValue();
5566     if (ExtractVec == SourceVecs[0]) {
5567       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5568     } else {
5569       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5570     }
5571   }
5572
5573   // Final check before we try to produce nonsense...
5574   if (isShuffleMaskLegal(Mask, VT))
5575     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5576                                 &Mask[0]);
5577
5578   return SDValue();
5579 }
5580
5581 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5582 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5583 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5584 /// are assumed to be legal.
5585 bool
5586 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5587                                       EVT VT) const {
5588   if (VT.getVectorNumElements() == 4 &&
5589       (VT.is128BitVector() || VT.is64BitVector())) {
5590     unsigned PFIndexes[4];
5591     for (unsigned i = 0; i != 4; ++i) {
5592       if (M[i] < 0)
5593         PFIndexes[i] = 8;
5594       else
5595         PFIndexes[i] = M[i];
5596     }
5597
5598     // Compute the index in the perfect shuffle table.
5599     unsigned PFTableIndex =
5600       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5601     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5602     unsigned Cost = (PFEntry >> 30);
5603
5604     if (Cost <= 4)
5605       return true;
5606   }
5607
5608   bool ReverseVEXT, isV_UNDEF;
5609   unsigned Imm, WhichResult;
5610
5611   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5612   return (EltSize >= 32 ||
5613           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5614           isVREVMask(M, VT, 64) ||
5615           isVREVMask(M, VT, 32) ||
5616           isVREVMask(M, VT, 16) ||
5617           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5618           isVTBLMask(M, VT) ||
5619           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5620           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5621 }
5622
5623 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5624 /// the specified operations to build the shuffle.
5625 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5626                                       SDValue RHS, SelectionDAG &DAG,
5627                                       SDLoc dl) {
5628   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5629   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5630   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5631
5632   enum {
5633     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5634     OP_VREV,
5635     OP_VDUP0,
5636     OP_VDUP1,
5637     OP_VDUP2,
5638     OP_VDUP3,
5639     OP_VEXT1,
5640     OP_VEXT2,
5641     OP_VEXT3,
5642     OP_VUZPL, // VUZP, left result
5643     OP_VUZPR, // VUZP, right result
5644     OP_VZIPL, // VZIP, left result
5645     OP_VZIPR, // VZIP, right result
5646     OP_VTRNL, // VTRN, left result
5647     OP_VTRNR  // VTRN, right result
5648   };
5649
5650   if (OpNum == OP_COPY) {
5651     if (LHSID == (1*9+2)*9+3) return LHS;
5652     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5653     return RHS;
5654   }
5655
5656   SDValue OpLHS, OpRHS;
5657   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5658   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5659   EVT VT = OpLHS.getValueType();
5660
5661   switch (OpNum) {
5662   default: llvm_unreachable("Unknown shuffle opcode!");
5663   case OP_VREV:
5664     // VREV divides the vector in half and swaps within the half.
5665     if (VT.getVectorElementType() == MVT::i32 ||
5666         VT.getVectorElementType() == MVT::f32)
5667       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5668     // vrev <4 x i16> -> VREV32
5669     if (VT.getVectorElementType() == MVT::i16)
5670       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5671     // vrev <4 x i8> -> VREV16
5672     assert(VT.getVectorElementType() == MVT::i8);
5673     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5674   case OP_VDUP0:
5675   case OP_VDUP1:
5676   case OP_VDUP2:
5677   case OP_VDUP3:
5678     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5679                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5680   case OP_VEXT1:
5681   case OP_VEXT2:
5682   case OP_VEXT3:
5683     return DAG.getNode(ARMISD::VEXT, dl, VT,
5684                        OpLHS, OpRHS,
5685                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5686   case OP_VUZPL:
5687   case OP_VUZPR:
5688     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5689                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5690   case OP_VZIPL:
5691   case OP_VZIPR:
5692     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5693                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5694   case OP_VTRNL:
5695   case OP_VTRNR:
5696     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5697                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5698   }
5699 }
5700
5701 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5702                                        ArrayRef<int> ShuffleMask,
5703                                        SelectionDAG &DAG) {
5704   // Check to see if we can use the VTBL instruction.
5705   SDValue V1 = Op.getOperand(0);
5706   SDValue V2 = Op.getOperand(1);
5707   SDLoc DL(Op);
5708
5709   SmallVector<SDValue, 8> VTBLMask;
5710   for (ArrayRef<int>::iterator
5711          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5712     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5713
5714   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5715     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5716                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5717
5718   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5719                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5720 }
5721
5722 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5723                                                       SelectionDAG &DAG) {
5724   SDLoc DL(Op);
5725   SDValue OpLHS = Op.getOperand(0);
5726   EVT VT = OpLHS.getValueType();
5727
5728   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5729          "Expect an v8i16/v16i8 type");
5730   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5731   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5732   // extract the first 8 bytes into the top double word and the last 8 bytes
5733   // into the bottom double word. The v8i16 case is similar.
5734   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5735   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5736                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5737 }
5738
5739 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5740   SDValue V1 = Op.getOperand(0);
5741   SDValue V2 = Op.getOperand(1);
5742   SDLoc dl(Op);
5743   EVT VT = Op.getValueType();
5744   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5745
5746   // Convert shuffles that are directly supported on NEON to target-specific
5747   // DAG nodes, instead of keeping them as shuffles and matching them again
5748   // during code selection.  This is more efficient and avoids the possibility
5749   // of inconsistencies between legalization and selection.
5750   // FIXME: floating-point vectors should be canonicalized to integer vectors
5751   // of the same time so that they get CSEd properly.
5752   ArrayRef<int> ShuffleMask = SVN->getMask();
5753
5754   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5755   if (EltSize <= 32) {
5756     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5757       int Lane = SVN->getSplatIndex();
5758       // If this is undef splat, generate it via "just" vdup, if possible.
5759       if (Lane == -1) Lane = 0;
5760
5761       // Test if V1 is a SCALAR_TO_VECTOR.
5762       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5763         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5764       }
5765       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5766       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5767       // reaches it).
5768       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5769           !isa<ConstantSDNode>(V1.getOperand(0))) {
5770         bool IsScalarToVector = true;
5771         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5772           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5773             IsScalarToVector = false;
5774             break;
5775           }
5776         if (IsScalarToVector)
5777           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5778       }
5779       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5780                          DAG.getConstant(Lane, dl, MVT::i32));
5781     }
5782
5783     bool ReverseVEXT;
5784     unsigned Imm;
5785     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5786       if (ReverseVEXT)
5787         std::swap(V1, V2);
5788       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5789                          DAG.getConstant(Imm, dl, MVT::i32));
5790     }
5791
5792     if (isVREVMask(ShuffleMask, VT, 64))
5793       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5794     if (isVREVMask(ShuffleMask, VT, 32))
5795       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5796     if (isVREVMask(ShuffleMask, VT, 16))
5797       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5798
5799     if (V2->getOpcode() == ISD::UNDEF &&
5800         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5801       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5802                          DAG.getConstant(Imm, dl, MVT::i32));
5803     }
5804
5805     // Check for Neon shuffles that modify both input vectors in place.
5806     // If both results are used, i.e., if there are two shuffles with the same
5807     // source operands and with masks corresponding to both results of one of
5808     // these operations, DAG memoization will ensure that a single node is
5809     // used for both shuffles.
5810     unsigned WhichResult;
5811     bool isV_UNDEF;
5812     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5813             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5814       if (isV_UNDEF)
5815         V2 = V1;
5816       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5817           .getValue(WhichResult);
5818     }
5819
5820     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5821     // shuffles that produce a result larger than their operands with:
5822     //   shuffle(concat(v1, undef), concat(v2, undef))
5823     // ->
5824     //   shuffle(concat(v1, v2), undef)
5825     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5826     //
5827     // This is useful in the general case, but there are special cases where
5828     // native shuffles produce larger results: the two-result ops.
5829     //
5830     // Look through the concat when lowering them:
5831     //   shuffle(concat(v1, v2), undef)
5832     // ->
5833     //   concat(VZIP(v1, v2):0, :1)
5834     //
5835     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5836         V2->getOpcode() == ISD::UNDEF) {
5837       SDValue SubV1 = V1->getOperand(0);
5838       SDValue SubV2 = V1->getOperand(1);
5839       EVT SubVT = SubV1.getValueType();
5840
5841       // We expect these to have been canonicalized to -1.
5842       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5843         return i < (int)VT.getVectorNumElements();
5844       }) && "Unexpected shuffle index into UNDEF operand!");
5845
5846       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5847               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5848         if (isV_UNDEF)
5849           SubV2 = SubV1;
5850         assert((WhichResult == 0) &&
5851                "In-place shuffle of concat can only have one result!");
5852         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5853                                   SubV1, SubV2);
5854         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5855                            Res.getValue(1));
5856       }
5857     }
5858   }
5859
5860   // If the shuffle is not directly supported and it has 4 elements, use
5861   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5862   unsigned NumElts = VT.getVectorNumElements();
5863   if (NumElts == 4) {
5864     unsigned PFIndexes[4];
5865     for (unsigned i = 0; i != 4; ++i) {
5866       if (ShuffleMask[i] < 0)
5867         PFIndexes[i] = 8;
5868       else
5869         PFIndexes[i] = ShuffleMask[i];
5870     }
5871
5872     // Compute the index in the perfect shuffle table.
5873     unsigned PFTableIndex =
5874       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5875     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5876     unsigned Cost = (PFEntry >> 30);
5877
5878     if (Cost <= 4)
5879       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5880   }
5881
5882   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5883   if (EltSize >= 32) {
5884     // Do the expansion with floating-point types, since that is what the VFP
5885     // registers are defined to use, and since i64 is not legal.
5886     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5887     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5888     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5889     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5890     SmallVector<SDValue, 8> Ops;
5891     for (unsigned i = 0; i < NumElts; ++i) {
5892       if (ShuffleMask[i] < 0)
5893         Ops.push_back(DAG.getUNDEF(EltVT));
5894       else
5895         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5896                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5897                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5898                                                   dl, MVT::i32)));
5899     }
5900     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5901     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5902   }
5903
5904   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5905     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5906
5907   if (VT == MVT::v8i8) {
5908     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5909     if (NewOp.getNode())
5910       return NewOp;
5911   }
5912
5913   return SDValue();
5914 }
5915
5916 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5917   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5918   SDValue Lane = Op.getOperand(2);
5919   if (!isa<ConstantSDNode>(Lane))
5920     return SDValue();
5921
5922   return Op;
5923 }
5924
5925 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5926   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5927   SDValue Lane = Op.getOperand(1);
5928   if (!isa<ConstantSDNode>(Lane))
5929     return SDValue();
5930
5931   SDValue Vec = Op.getOperand(0);
5932   if (Op.getValueType() == MVT::i32 &&
5933       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5934     SDLoc dl(Op);
5935     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5936   }
5937
5938   return Op;
5939 }
5940
5941 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5942   // The only time a CONCAT_VECTORS operation can have legal types is when
5943   // two 64-bit vectors are concatenated to a 128-bit vector.
5944   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5945          "unexpected CONCAT_VECTORS");
5946   SDLoc dl(Op);
5947   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5948   SDValue Op0 = Op.getOperand(0);
5949   SDValue Op1 = Op.getOperand(1);
5950   if (Op0.getOpcode() != ISD::UNDEF)
5951     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5952                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5953                       DAG.getIntPtrConstant(0, dl));
5954   if (Op1.getOpcode() != ISD::UNDEF)
5955     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5956                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5957                       DAG.getIntPtrConstant(1, dl));
5958   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5959 }
5960
5961 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5962 /// element has been zero/sign-extended, depending on the isSigned parameter,
5963 /// from an integer type half its size.
5964 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5965                                    bool isSigned) {
5966   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5967   EVT VT = N->getValueType(0);
5968   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5969     SDNode *BVN = N->getOperand(0).getNode();
5970     if (BVN->getValueType(0) != MVT::v4i32 ||
5971         BVN->getOpcode() != ISD::BUILD_VECTOR)
5972       return false;
5973     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
5974     unsigned HiElt = 1 - LoElt;
5975     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5976     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5977     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5978     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5979     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5980       return false;
5981     if (isSigned) {
5982       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5983           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5984         return true;
5985     } else {
5986       if (Hi0->isNullValue() && Hi1->isNullValue())
5987         return true;
5988     }
5989     return false;
5990   }
5991
5992   if (N->getOpcode() != ISD::BUILD_VECTOR)
5993     return false;
5994
5995   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5996     SDNode *Elt = N->getOperand(i).getNode();
5997     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5998       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5999       unsigned HalfSize = EltSize / 2;
6000       if (isSigned) {
6001         if (!isIntN(HalfSize, C->getSExtValue()))
6002           return false;
6003       } else {
6004         if (!isUIntN(HalfSize, C->getZExtValue()))
6005           return false;
6006       }
6007       continue;
6008     }
6009     return false;
6010   }
6011
6012   return true;
6013 }
6014
6015 /// isSignExtended - Check if a node is a vector value that is sign-extended
6016 /// or a constant BUILD_VECTOR with sign-extended elements.
6017 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6018   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6019     return true;
6020   if (isExtendedBUILD_VECTOR(N, DAG, true))
6021     return true;
6022   return false;
6023 }
6024
6025 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6026 /// or a constant BUILD_VECTOR with zero-extended elements.
6027 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6028   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6029     return true;
6030   if (isExtendedBUILD_VECTOR(N, DAG, false))
6031     return true;
6032   return false;
6033 }
6034
6035 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6036   if (OrigVT.getSizeInBits() >= 64)
6037     return OrigVT;
6038
6039   assert(OrigVT.isSimple() && "Expecting a simple value type");
6040
6041   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6042   switch (OrigSimpleTy) {
6043   default: llvm_unreachable("Unexpected Vector Type");
6044   case MVT::v2i8:
6045   case MVT::v2i16:
6046      return MVT::v2i32;
6047   case MVT::v4i8:
6048     return  MVT::v4i16;
6049   }
6050 }
6051
6052 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6053 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6054 /// We insert the required extension here to get the vector to fill a D register.
6055 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6056                                             const EVT &OrigTy,
6057                                             const EVT &ExtTy,
6058                                             unsigned ExtOpcode) {
6059   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6060   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6061   // 64-bits we need to insert a new extension so that it will be 64-bits.
6062   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6063   if (OrigTy.getSizeInBits() >= 64)
6064     return N;
6065
6066   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6067   EVT NewVT = getExtensionTo64Bits(OrigTy);
6068
6069   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6070 }
6071
6072 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6073 /// does not do any sign/zero extension. If the original vector is less
6074 /// than 64 bits, an appropriate extension will be added after the load to
6075 /// reach a total size of 64 bits. We have to add the extension separately
6076 /// because ARM does not have a sign/zero extending load for vectors.
6077 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6078   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6079
6080   // The load already has the right type.
6081   if (ExtendedTy == LD->getMemoryVT())
6082     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6083                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6084                 LD->isNonTemporal(), LD->isInvariant(),
6085                 LD->getAlignment());
6086
6087   // We need to create a zextload/sextload. We cannot just create a load
6088   // followed by a zext/zext node because LowerMUL is also run during normal
6089   // operation legalization where we can't create illegal types.
6090   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6091                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6092                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6093                         LD->isNonTemporal(), LD->getAlignment());
6094 }
6095
6096 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6097 /// extending load, or BUILD_VECTOR with extended elements, return the
6098 /// unextended value. The unextended vector should be 64 bits so that it can
6099 /// be used as an operand to a VMULL instruction. If the original vector size
6100 /// before extension is less than 64 bits we add a an extension to resize
6101 /// the vector to 64 bits.
6102 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6103   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6104     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6105                                         N->getOperand(0)->getValueType(0),
6106                                         N->getValueType(0),
6107                                         N->getOpcode());
6108
6109   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6110     return SkipLoadExtensionForVMULL(LD, DAG);
6111
6112   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6113   // have been legalized as a BITCAST from v4i32.
6114   if (N->getOpcode() == ISD::BITCAST) {
6115     SDNode *BVN = N->getOperand(0).getNode();
6116     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6117            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6118     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6119     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6120                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6121   }
6122   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6123   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6124   EVT VT = N->getValueType(0);
6125   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6126   unsigned NumElts = VT.getVectorNumElements();
6127   MVT TruncVT = MVT::getIntegerVT(EltSize);
6128   SmallVector<SDValue, 8> Ops;
6129   SDLoc dl(N);
6130   for (unsigned i = 0; i != NumElts; ++i) {
6131     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6132     const APInt &CInt = C->getAPIntValue();
6133     // Element types smaller than 32 bits are not legal, so use i32 elements.
6134     // The values are implicitly truncated so sext vs. zext doesn't matter.
6135     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6136   }
6137   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6138                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6139 }
6140
6141 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6142   unsigned Opcode = N->getOpcode();
6143   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6144     SDNode *N0 = N->getOperand(0).getNode();
6145     SDNode *N1 = N->getOperand(1).getNode();
6146     return N0->hasOneUse() && N1->hasOneUse() &&
6147       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6148   }
6149   return false;
6150 }
6151
6152 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6153   unsigned Opcode = N->getOpcode();
6154   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6155     SDNode *N0 = N->getOperand(0).getNode();
6156     SDNode *N1 = N->getOperand(1).getNode();
6157     return N0->hasOneUse() && N1->hasOneUse() &&
6158       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6159   }
6160   return false;
6161 }
6162
6163 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6164   // Multiplications are only custom-lowered for 128-bit vectors so that
6165   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6166   EVT VT = Op.getValueType();
6167   assert(VT.is128BitVector() && VT.isInteger() &&
6168          "unexpected type for custom-lowering ISD::MUL");
6169   SDNode *N0 = Op.getOperand(0).getNode();
6170   SDNode *N1 = Op.getOperand(1).getNode();
6171   unsigned NewOpc = 0;
6172   bool isMLA = false;
6173   bool isN0SExt = isSignExtended(N0, DAG);
6174   bool isN1SExt = isSignExtended(N1, DAG);
6175   if (isN0SExt && isN1SExt)
6176     NewOpc = ARMISD::VMULLs;
6177   else {
6178     bool isN0ZExt = isZeroExtended(N0, DAG);
6179     bool isN1ZExt = isZeroExtended(N1, DAG);
6180     if (isN0ZExt && isN1ZExt)
6181       NewOpc = ARMISD::VMULLu;
6182     else if (isN1SExt || isN1ZExt) {
6183       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6184       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6185       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6186         NewOpc = ARMISD::VMULLs;
6187         isMLA = true;
6188       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6189         NewOpc = ARMISD::VMULLu;
6190         isMLA = true;
6191       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6192         std::swap(N0, N1);
6193         NewOpc = ARMISD::VMULLu;
6194         isMLA = true;
6195       }
6196     }
6197
6198     if (!NewOpc) {
6199       if (VT == MVT::v2i64)
6200         // Fall through to expand this.  It is not legal.
6201         return SDValue();
6202       else
6203         // Other vector multiplications are legal.
6204         return Op;
6205     }
6206   }
6207
6208   // Legalize to a VMULL instruction.
6209   SDLoc DL(Op);
6210   SDValue Op0;
6211   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6212   if (!isMLA) {
6213     Op0 = SkipExtensionForVMULL(N0, DAG);
6214     assert(Op0.getValueType().is64BitVector() &&
6215            Op1.getValueType().is64BitVector() &&
6216            "unexpected types for extended operands to VMULL");
6217     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6218   }
6219
6220   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6221   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6222   //   vmull q0, d4, d6
6223   //   vmlal q0, d5, d6
6224   // is faster than
6225   //   vaddl q0, d4, d5
6226   //   vmovl q1, d6
6227   //   vmul  q0, q0, q1
6228   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6229   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6230   EVT Op1VT = Op1.getValueType();
6231   return DAG.getNode(N0->getOpcode(), DL, VT,
6232                      DAG.getNode(NewOpc, DL, VT,
6233                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6234                      DAG.getNode(NewOpc, DL, VT,
6235                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6236 }
6237
6238 static SDValue
6239 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6240   // Convert to float
6241   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6242   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6243   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6244   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6245   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6246   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6247   // Get reciprocal estimate.
6248   // float4 recip = vrecpeq_f32(yf);
6249   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6250                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6251                    Y);
6252   // Because char has a smaller range than uchar, we can actually get away
6253   // without any newton steps.  This requires that we use a weird bias
6254   // of 0xb000, however (again, this has been exhaustively tested).
6255   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6256   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6257   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6258   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6259   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6260   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6261   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6262   // Convert back to short.
6263   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6264   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6265   return X;
6266 }
6267
6268 static SDValue
6269 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6270   SDValue N2;
6271   // Convert to float.
6272   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6273   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6274   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6275   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6276   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6277   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6278
6279   // Use reciprocal estimate and one refinement step.
6280   // float4 recip = vrecpeq_f32(yf);
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                    N1);
6285   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6286                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6287                    N1, N2);
6288   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6289   // Because short has a smaller range than ushort, we can actually get away
6290   // with only a single newton step.  This requires that we use a weird bias
6291   // of 89, however (again, this has been exhaustively tested).
6292   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6293   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6294   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6295   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6296   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6297   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6298   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6299   // Convert back to integer and return.
6300   // return vmovn_s32(vcvt_s32_f32(result));
6301   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6302   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6303   return N0;
6304 }
6305
6306 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6307   EVT VT = Op.getValueType();
6308   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6309          "unexpected type for custom-lowering ISD::SDIV");
6310
6311   SDLoc dl(Op);
6312   SDValue N0 = Op.getOperand(0);
6313   SDValue N1 = Op.getOperand(1);
6314   SDValue N2, N3;
6315
6316   if (VT == MVT::v8i8) {
6317     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6318     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6319
6320     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6321                      DAG.getIntPtrConstant(4, dl));
6322     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6323                      DAG.getIntPtrConstant(4, dl));
6324     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6325                      DAG.getIntPtrConstant(0, dl));
6326     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6327                      DAG.getIntPtrConstant(0, dl));
6328
6329     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6330     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6331
6332     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6333     N0 = LowerCONCAT_VECTORS(N0, DAG);
6334
6335     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6336     return N0;
6337   }
6338   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6339 }
6340
6341 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6342   EVT VT = Op.getValueType();
6343   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6344          "unexpected type for custom-lowering ISD::UDIV");
6345
6346   SDLoc dl(Op);
6347   SDValue N0 = Op.getOperand(0);
6348   SDValue N1 = Op.getOperand(1);
6349   SDValue N2, N3;
6350
6351   if (VT == MVT::v8i8) {
6352     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6353     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6354
6355     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6356                      DAG.getIntPtrConstant(4, dl));
6357     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6358                      DAG.getIntPtrConstant(4, dl));
6359     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6360                      DAG.getIntPtrConstant(0, dl));
6361     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6362                      DAG.getIntPtrConstant(0, dl));
6363
6364     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6365     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6366
6367     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6368     N0 = LowerCONCAT_VECTORS(N0, DAG);
6369
6370     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6371                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6372                                      MVT::i32),
6373                      N0);
6374     return N0;
6375   }
6376
6377   // v4i16 sdiv ... Convert to float.
6378   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6379   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6380   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6381   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6382   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6383   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6384
6385   // Use reciprocal estimate and two refinement steps.
6386   // float4 recip = vrecpeq_f32(yf);
6387   // recip *= vrecpsq_f32(yf, recip);
6388   // recip *= vrecpsq_f32(yf, recip);
6389   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6390                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6391                    BN1);
6392   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6393                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6394                    BN1, N2);
6395   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6396   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6397                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6398                    BN1, N2);
6399   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6400   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6401   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6402   // and that it will never cause us to return an answer too large).
6403   // float4 result = as_float4(as_int4(xf*recip) + 2);
6404   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6405   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6406   N1 = DAG.getConstant(2, dl, MVT::i32);
6407   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6408   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6409   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6410   // Convert back to integer and return.
6411   // return vmovn_u32(vcvt_s32_f32(result));
6412   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6413   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6414   return N0;
6415 }
6416
6417 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6418   EVT VT = Op.getNode()->getValueType(0);
6419   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6420
6421   unsigned Opc;
6422   bool ExtraOp = false;
6423   switch (Op.getOpcode()) {
6424   default: llvm_unreachable("Invalid code");
6425   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6426   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6427   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6428   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6429   }
6430
6431   if (!ExtraOp)
6432     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6433                        Op.getOperand(1));
6434   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6435                      Op.getOperand(1), Op.getOperand(2));
6436 }
6437
6438 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6439   assert(Subtarget->isTargetDarwin());
6440
6441   // For iOS, we want to call an alternative entry point: __sincos_stret,
6442   // return values are passed via sret.
6443   SDLoc dl(Op);
6444   SDValue Arg = Op.getOperand(0);
6445   EVT ArgVT = Arg.getValueType();
6446   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6447   auto PtrVT = getPointerTy(DAG.getDataLayout());
6448
6449   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6450
6451   // Pair of floats / doubles used to pass the result.
6452   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6453
6454   // Create stack object for sret.
6455   auto &DL = DAG.getDataLayout();
6456   const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6457   const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6458   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6459   SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6460
6461   ArgListTy Args;
6462   ArgListEntry Entry;
6463
6464   Entry.Node = SRet;
6465   Entry.Ty = RetTy->getPointerTo();
6466   Entry.isSExt = false;
6467   Entry.isZExt = false;
6468   Entry.isSRet = true;
6469   Args.push_back(Entry);
6470
6471   Entry.Node = Arg;
6472   Entry.Ty = ArgTy;
6473   Entry.isSExt = false;
6474   Entry.isZExt = false;
6475   Args.push_back(Entry);
6476
6477   const char *LibcallName  = (ArgVT == MVT::f64)
6478   ? "__sincos_stret" : "__sincosf_stret";
6479   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6480
6481   TargetLowering::CallLoweringInfo CLI(DAG);
6482   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6483     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6484                std::move(Args), 0)
6485     .setDiscardResult();
6486
6487   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6488
6489   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6490                                 MachinePointerInfo(), false, false, false, 0);
6491
6492   // Address of cos field.
6493   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6494                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6495   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6496                                 MachinePointerInfo(), false, false, false, 0);
6497
6498   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6499   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6500                      LoadSin.getValue(0), LoadCos.getValue(0));
6501 }
6502
6503 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6504   // Monotonic load/store is legal for all targets
6505   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6506     return Op;
6507
6508   // Acquire/Release load/store is not legal for targets without a
6509   // dmb or equivalent available.
6510   return SDValue();
6511 }
6512
6513 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6514                                     SmallVectorImpl<SDValue> &Results,
6515                                     SelectionDAG &DAG,
6516                                     const ARMSubtarget *Subtarget) {
6517   SDLoc DL(N);
6518   SDValue Cycles32, OutChain;
6519
6520   if (Subtarget->hasPerfMon()) {
6521     // Under Power Management extensions, the cycle-count is:
6522     //    mrc p15, #0, <Rt>, c9, c13, #0
6523     SDValue Ops[] = { N->getOperand(0), // Chain
6524                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6525                       DAG.getConstant(15, DL, MVT::i32),
6526                       DAG.getConstant(0, DL, MVT::i32),
6527                       DAG.getConstant(9, DL, MVT::i32),
6528                       DAG.getConstant(13, DL, MVT::i32),
6529                       DAG.getConstant(0, DL, MVT::i32)
6530     };
6531
6532     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6533                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6534     OutChain = Cycles32.getValue(1);
6535   } else {
6536     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6537     // there are older ARM CPUs that have implementation-specific ways of
6538     // obtaining this information (FIXME!).
6539     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6540     OutChain = DAG.getEntryNode();
6541   }
6542
6543
6544   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6545                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6546   Results.push_back(Cycles64);
6547   Results.push_back(OutChain);
6548 }
6549
6550 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6551   switch (Op.getOpcode()) {
6552   default: llvm_unreachable("Don't know how to custom lower this!");
6553   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6554   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6555   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6556   case ISD::GlobalAddress:
6557     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6558     default: llvm_unreachable("unknown object format");
6559     case Triple::COFF:
6560       return LowerGlobalAddressWindows(Op, DAG);
6561     case Triple::ELF:
6562       return LowerGlobalAddressELF(Op, DAG);
6563     case Triple::MachO:
6564       return LowerGlobalAddressDarwin(Op, DAG);
6565     }
6566   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6567   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6568   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6569   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6570   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6571   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6572   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6573   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6574   case ISD::SINT_TO_FP:
6575   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6576   case ISD::FP_TO_SINT:
6577   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6578   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6579   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6580   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6581   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6582   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6583   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6584   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6585   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6586                                                                Subtarget);
6587   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6588   case ISD::SHL:
6589   case ISD::SRL:
6590   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6591   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6592   case ISD::SRL_PARTS:
6593   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6594   case ISD::CTTZ:
6595   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6596   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6597   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6598   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6599   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6600   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6601   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6602   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6603   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6604   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6605   case ISD::MUL:           return LowerMUL(Op, DAG);
6606   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6607   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6608   case ISD::ADDC:
6609   case ISD::ADDE:
6610   case ISD::SUBC:
6611   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6612   case ISD::SADDO:
6613   case ISD::UADDO:
6614   case ISD::SSUBO:
6615   case ISD::USUBO:
6616     return LowerXALUO(Op, DAG);
6617   case ISD::ATOMIC_LOAD:
6618   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6619   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6620   case ISD::SDIVREM:
6621   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6622   case ISD::DYNAMIC_STACKALLOC:
6623     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6624       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6625     llvm_unreachable("Don't know how to custom lower this!");
6626   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6627   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6628   }
6629 }
6630
6631 /// ReplaceNodeResults - Replace the results of node with an illegal result
6632 /// type with new values built out of custom code.
6633 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6634                                            SmallVectorImpl<SDValue>&Results,
6635                                            SelectionDAG &DAG) const {
6636   SDValue Res;
6637   switch (N->getOpcode()) {
6638   default:
6639     llvm_unreachable("Don't know how to custom expand this!");
6640   case ISD::READ_REGISTER:
6641     ExpandREAD_REGISTER(N, Results, DAG);
6642     break;
6643   case ISD::BITCAST:
6644     Res = ExpandBITCAST(N, DAG);
6645     break;
6646   case ISD::SRL:
6647   case ISD::SRA:
6648     Res = Expand64BitShift(N, DAG, Subtarget);
6649     break;
6650   case ISD::READCYCLECOUNTER:
6651     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6652     return;
6653   }
6654   if (Res.getNode())
6655     Results.push_back(Res);
6656 }
6657
6658 //===----------------------------------------------------------------------===//
6659 //                           ARM Scheduler Hooks
6660 //===----------------------------------------------------------------------===//
6661
6662 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6663 /// registers the function context.
6664 void ARMTargetLowering::
6665 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6666                        MachineBasicBlock *DispatchBB, int FI) const {
6667   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6668   DebugLoc dl = MI->getDebugLoc();
6669   MachineFunction *MF = MBB->getParent();
6670   MachineRegisterInfo *MRI = &MF->getRegInfo();
6671   MachineConstantPool *MCP = MF->getConstantPool();
6672   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6673   const Function *F = MF->getFunction();
6674
6675   bool isThumb = Subtarget->isThumb();
6676   bool isThumb2 = Subtarget->isThumb2();
6677
6678   unsigned PCLabelId = AFI->createPICLabelUId();
6679   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6680   ARMConstantPoolValue *CPV =
6681     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6682   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6683
6684   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6685                                            : &ARM::GPRRegClass;
6686
6687   // Grab constant pool and fixed stack memory operands.
6688   MachineMemOperand *CPMMO =
6689     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6690                              MachineMemOperand::MOLoad, 4, 4);
6691
6692   MachineMemOperand *FIMMOSt =
6693     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6694                              MachineMemOperand::MOStore, 4, 4);
6695
6696   // Load the address of the dispatch MBB into the jump buffer.
6697   if (isThumb2) {
6698     // Incoming value: jbuf
6699     //   ldr.n  r5, LCPI1_1
6700     //   orr    r5, r5, #1
6701     //   add    r5, pc
6702     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6703     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6704     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6705                    .addConstantPoolIndex(CPI)
6706                    .addMemOperand(CPMMO));
6707     // Set the low bit because of thumb mode.
6708     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6709     AddDefaultCC(
6710       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6711                      .addReg(NewVReg1, RegState::Kill)
6712                      .addImm(0x01)));
6713     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6714     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6715       .addReg(NewVReg2, RegState::Kill)
6716       .addImm(PCLabelId);
6717     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6718                    .addReg(NewVReg3, RegState::Kill)
6719                    .addFrameIndex(FI)
6720                    .addImm(36)  // &jbuf[1] :: pc
6721                    .addMemOperand(FIMMOSt));
6722   } else if (isThumb) {
6723     // Incoming value: jbuf
6724     //   ldr.n  r1, LCPI1_4
6725     //   add    r1, pc
6726     //   mov    r2, #1
6727     //   orrs   r1, r2
6728     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6729     //   str    r1, [r2]
6730     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6731     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6732                    .addConstantPoolIndex(CPI)
6733                    .addMemOperand(CPMMO));
6734     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6735     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6736       .addReg(NewVReg1, RegState::Kill)
6737       .addImm(PCLabelId);
6738     // Set the low bit because of thumb mode.
6739     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6740     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6741                    .addReg(ARM::CPSR, RegState::Define)
6742                    .addImm(1));
6743     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6744     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6745                    .addReg(ARM::CPSR, RegState::Define)
6746                    .addReg(NewVReg2, RegState::Kill)
6747                    .addReg(NewVReg3, RegState::Kill));
6748     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6749     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6750             .addFrameIndex(FI)
6751             .addImm(36); // &jbuf[1] :: pc
6752     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6753                    .addReg(NewVReg4, RegState::Kill)
6754                    .addReg(NewVReg5, RegState::Kill)
6755                    .addImm(0)
6756                    .addMemOperand(FIMMOSt));
6757   } else {
6758     // Incoming value: jbuf
6759     //   ldr  r1, LCPI1_1
6760     //   add  r1, pc, r1
6761     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6762     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6763     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6764                    .addConstantPoolIndex(CPI)
6765                    .addImm(0)
6766                    .addMemOperand(CPMMO));
6767     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6768     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6769                    .addReg(NewVReg1, RegState::Kill)
6770                    .addImm(PCLabelId));
6771     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6772                    .addReg(NewVReg2, RegState::Kill)
6773                    .addFrameIndex(FI)
6774                    .addImm(36)  // &jbuf[1] :: pc
6775                    .addMemOperand(FIMMOSt));
6776   }
6777 }
6778
6779 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6780                                               MachineBasicBlock *MBB) const {
6781   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6782   DebugLoc dl = MI->getDebugLoc();
6783   MachineFunction *MF = MBB->getParent();
6784   MachineRegisterInfo *MRI = &MF->getRegInfo();
6785   MachineFrameInfo *MFI = MF->getFrameInfo();
6786   int FI = MFI->getFunctionContextIndex();
6787
6788   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6789                                                         : &ARM::GPRnopcRegClass;
6790
6791   // Get a mapping of the call site numbers to all of the landing pads they're
6792   // associated with.
6793   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6794   unsigned MaxCSNum = 0;
6795   MachineModuleInfo &MMI = MF->getMMI();
6796   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6797        ++BB) {
6798     if (!BB->isLandingPad()) continue;
6799
6800     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6801     // pad.
6802     for (MachineBasicBlock::iterator
6803            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6804       if (!II->isEHLabel()) continue;
6805
6806       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6807       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6808
6809       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6810       for (SmallVectorImpl<unsigned>::iterator
6811              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6812            CSI != CSE; ++CSI) {
6813         CallSiteNumToLPad[*CSI].push_back(BB);
6814         MaxCSNum = std::max(MaxCSNum, *CSI);
6815       }
6816       break;
6817     }
6818   }
6819
6820   // Get an ordered list of the machine basic blocks for the jump table.
6821   std::vector<MachineBasicBlock*> LPadList;
6822   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6823   LPadList.reserve(CallSiteNumToLPad.size());
6824   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6825     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6826     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6827            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6828       LPadList.push_back(*II);
6829       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6830     }
6831   }
6832
6833   assert(!LPadList.empty() &&
6834          "No landing pad destinations for the dispatch jump table!");
6835
6836   // Create the jump table and associated information.
6837   MachineJumpTableInfo *JTI =
6838     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6839   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6840   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6841
6842   // Create the MBBs for the dispatch code.
6843
6844   // Shove the dispatch's address into the return slot in the function context.
6845   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6846   DispatchBB->setIsLandingPad();
6847
6848   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6849   unsigned trap_opcode;
6850   if (Subtarget->isThumb())
6851     trap_opcode = ARM::tTRAP;
6852   else
6853     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6854
6855   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6856   DispatchBB->addSuccessor(TrapBB);
6857
6858   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6859   DispatchBB->addSuccessor(DispContBB);
6860
6861   // Insert and MBBs.
6862   MF->insert(MF->end(), DispatchBB);
6863   MF->insert(MF->end(), DispContBB);
6864   MF->insert(MF->end(), TrapBB);
6865
6866   // Insert code into the entry block that creates and registers the function
6867   // context.
6868   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6869
6870   MachineMemOperand *FIMMOLd =
6871     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6872                              MachineMemOperand::MOLoad |
6873                              MachineMemOperand::MOVolatile, 4, 4);
6874
6875   MachineInstrBuilder MIB;
6876   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6877
6878   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6879   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6880
6881   // Add a register mask with no preserved registers.  This results in all
6882   // registers being marked as clobbered.
6883   MIB.addRegMask(RI.getNoPreservedMask());
6884
6885   unsigned NumLPads = LPadList.size();
6886   if (Subtarget->isThumb2()) {
6887     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6888     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6889                    .addFrameIndex(FI)
6890                    .addImm(4)
6891                    .addMemOperand(FIMMOLd));
6892
6893     if (NumLPads < 256) {
6894       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6895                      .addReg(NewVReg1)
6896                      .addImm(LPadList.size()));
6897     } else {
6898       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6899       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6900                      .addImm(NumLPads & 0xFFFF));
6901
6902       unsigned VReg2 = VReg1;
6903       if ((NumLPads & 0xFFFF0000) != 0) {
6904         VReg2 = MRI->createVirtualRegister(TRC);
6905         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6906                        .addReg(VReg1)
6907                        .addImm(NumLPads >> 16));
6908       }
6909
6910       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6911                      .addReg(NewVReg1)
6912                      .addReg(VReg2));
6913     }
6914
6915     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6916       .addMBB(TrapBB)
6917       .addImm(ARMCC::HI)
6918       .addReg(ARM::CPSR);
6919
6920     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6921     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6922                    .addJumpTableIndex(MJTI));
6923
6924     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6925     AddDefaultCC(
6926       AddDefaultPred(
6927         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6928         .addReg(NewVReg3, RegState::Kill)
6929         .addReg(NewVReg1)
6930         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6931
6932     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6933       .addReg(NewVReg4, RegState::Kill)
6934       .addReg(NewVReg1)
6935       .addJumpTableIndex(MJTI);
6936   } else if (Subtarget->isThumb()) {
6937     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6938     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6939                    .addFrameIndex(FI)
6940                    .addImm(1)
6941                    .addMemOperand(FIMMOLd));
6942
6943     if (NumLPads < 256) {
6944       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6945                      .addReg(NewVReg1)
6946                      .addImm(NumLPads));
6947     } else {
6948       MachineConstantPool *ConstantPool = MF->getConstantPool();
6949       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6950       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6951
6952       // MachineConstantPool wants an explicit alignment.
6953       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
6954       if (Align == 0)
6955         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
6956       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6957
6958       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6959       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6960                      .addReg(VReg1, RegState::Define)
6961                      .addConstantPoolIndex(Idx));
6962       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6963                      .addReg(NewVReg1)
6964                      .addReg(VReg1));
6965     }
6966
6967     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6968       .addMBB(TrapBB)
6969       .addImm(ARMCC::HI)
6970       .addReg(ARM::CPSR);
6971
6972     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6973     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6974                    .addReg(ARM::CPSR, RegState::Define)
6975                    .addReg(NewVReg1)
6976                    .addImm(2));
6977
6978     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6979     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6980                    .addJumpTableIndex(MJTI));
6981
6982     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6983     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6984                    .addReg(ARM::CPSR, RegState::Define)
6985                    .addReg(NewVReg2, RegState::Kill)
6986                    .addReg(NewVReg3));
6987
6988     MachineMemOperand *JTMMOLd =
6989       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6990                                MachineMemOperand::MOLoad, 4, 4);
6991
6992     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6993     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6994                    .addReg(NewVReg4, RegState::Kill)
6995                    .addImm(0)
6996                    .addMemOperand(JTMMOLd));
6997
6998     unsigned NewVReg6 = NewVReg5;
6999     if (RelocM == Reloc::PIC_) {
7000       NewVReg6 = MRI->createVirtualRegister(TRC);
7001       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7002                      .addReg(ARM::CPSR, RegState::Define)
7003                      .addReg(NewVReg5, RegState::Kill)
7004                      .addReg(NewVReg3));
7005     }
7006
7007     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7008       .addReg(NewVReg6, RegState::Kill)
7009       .addJumpTableIndex(MJTI);
7010   } else {
7011     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7012     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7013                    .addFrameIndex(FI)
7014                    .addImm(4)
7015                    .addMemOperand(FIMMOLd));
7016
7017     if (NumLPads < 256) {
7018       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7019                      .addReg(NewVReg1)
7020                      .addImm(NumLPads));
7021     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7022       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7023       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7024                      .addImm(NumLPads & 0xFFFF));
7025
7026       unsigned VReg2 = VReg1;
7027       if ((NumLPads & 0xFFFF0000) != 0) {
7028         VReg2 = MRI->createVirtualRegister(TRC);
7029         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7030                        .addReg(VReg1)
7031                        .addImm(NumLPads >> 16));
7032       }
7033
7034       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7035                      .addReg(NewVReg1)
7036                      .addReg(VReg2));
7037     } else {
7038       MachineConstantPool *ConstantPool = MF->getConstantPool();
7039       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7040       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7041
7042       // MachineConstantPool wants an explicit alignment.
7043       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7044       if (Align == 0)
7045         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7046       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7047
7048       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7049       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7050                      .addReg(VReg1, RegState::Define)
7051                      .addConstantPoolIndex(Idx)
7052                      .addImm(0));
7053       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7054                      .addReg(NewVReg1)
7055                      .addReg(VReg1, RegState::Kill));
7056     }
7057
7058     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7059       .addMBB(TrapBB)
7060       .addImm(ARMCC::HI)
7061       .addReg(ARM::CPSR);
7062
7063     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7064     AddDefaultCC(
7065       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7066                      .addReg(NewVReg1)
7067                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7068     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7069     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7070                    .addJumpTableIndex(MJTI));
7071
7072     MachineMemOperand *JTMMOLd =
7073       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7074                                MachineMemOperand::MOLoad, 4, 4);
7075     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7076     AddDefaultPred(
7077       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7078       .addReg(NewVReg3, RegState::Kill)
7079       .addReg(NewVReg4)
7080       .addImm(0)
7081       .addMemOperand(JTMMOLd));
7082
7083     if (RelocM == Reloc::PIC_) {
7084       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7085         .addReg(NewVReg5, RegState::Kill)
7086         .addReg(NewVReg4)
7087         .addJumpTableIndex(MJTI);
7088     } else {
7089       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7090         .addReg(NewVReg5, RegState::Kill)
7091         .addJumpTableIndex(MJTI);
7092     }
7093   }
7094
7095   // Add the jump table entries as successors to the MBB.
7096   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7097   for (std::vector<MachineBasicBlock*>::iterator
7098          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7099     MachineBasicBlock *CurMBB = *I;
7100     if (SeenMBBs.insert(CurMBB).second)
7101       DispContBB->addSuccessor(CurMBB);
7102   }
7103
7104   // N.B. the order the invoke BBs are processed in doesn't matter here.
7105   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7106   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7107   for (MachineBasicBlock *BB : InvokeBBs) {
7108
7109     // Remove the landing pad successor from the invoke block and replace it
7110     // with the new dispatch block.
7111     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7112                                                   BB->succ_end());
7113     while (!Successors.empty()) {
7114       MachineBasicBlock *SMBB = Successors.pop_back_val();
7115       if (SMBB->isLandingPad()) {
7116         BB->removeSuccessor(SMBB);
7117         MBBLPads.push_back(SMBB);
7118       }
7119     }
7120
7121     BB->addSuccessor(DispatchBB);
7122
7123     // Find the invoke call and mark all of the callee-saved registers as
7124     // 'implicit defined' so that they're spilled. This prevents code from
7125     // moving instructions to before the EH block, where they will never be
7126     // executed.
7127     for (MachineBasicBlock::reverse_iterator
7128            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7129       if (!II->isCall()) continue;
7130
7131       DenseMap<unsigned, bool> DefRegs;
7132       for (MachineInstr::mop_iterator
7133              OI = II->operands_begin(), OE = II->operands_end();
7134            OI != OE; ++OI) {
7135         if (!OI->isReg()) continue;
7136         DefRegs[OI->getReg()] = true;
7137       }
7138
7139       MachineInstrBuilder MIB(*MF, &*II);
7140
7141       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7142         unsigned Reg = SavedRegs[i];
7143         if (Subtarget->isThumb2() &&
7144             !ARM::tGPRRegClass.contains(Reg) &&
7145             !ARM::hGPRRegClass.contains(Reg))
7146           continue;
7147         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7148           continue;
7149         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7150           continue;
7151         if (!DefRegs[Reg])
7152           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7153       }
7154
7155       break;
7156     }
7157   }
7158
7159   // Mark all former landing pads as non-landing pads. The dispatch is the only
7160   // landing pad now.
7161   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7162          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7163     (*I)->setIsLandingPad(false);
7164
7165   // The instruction is gone now.
7166   MI->eraseFromParent();
7167 }
7168
7169 static
7170 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7171   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7172        E = MBB->succ_end(); I != E; ++I)
7173     if (*I != Succ)
7174       return *I;
7175   llvm_unreachable("Expecting a BB with two successors!");
7176 }
7177
7178 /// Return the load opcode for a given load size. If load size >= 8,
7179 /// neon opcode will be returned.
7180 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7181   if (LdSize >= 8)
7182     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7183                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7184   if (IsThumb1)
7185     return LdSize == 4 ? ARM::tLDRi
7186                        : LdSize == 2 ? ARM::tLDRHi
7187                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7188   if (IsThumb2)
7189     return LdSize == 4 ? ARM::t2LDR_POST
7190                        : LdSize == 2 ? ARM::t2LDRH_POST
7191                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7192   return LdSize == 4 ? ARM::LDR_POST_IMM
7193                      : LdSize == 2 ? ARM::LDRH_POST
7194                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7195 }
7196
7197 /// Return the store opcode for a given store size. If store size >= 8,
7198 /// neon opcode will be returned.
7199 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7200   if (StSize >= 8)
7201     return StSize == 16 ? ARM::VST1q32wb_fixed
7202                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7203   if (IsThumb1)
7204     return StSize == 4 ? ARM::tSTRi
7205                        : StSize == 2 ? ARM::tSTRHi
7206                                      : StSize == 1 ? ARM::tSTRBi : 0;
7207   if (IsThumb2)
7208     return StSize == 4 ? ARM::t2STR_POST
7209                        : StSize == 2 ? ARM::t2STRH_POST
7210                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7211   return StSize == 4 ? ARM::STR_POST_IMM
7212                      : StSize == 2 ? ARM::STRH_POST
7213                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7214 }
7215
7216 /// Emit a post-increment load operation with given size. The instructions
7217 /// will be added to BB at Pos.
7218 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7219                        const TargetInstrInfo *TII, DebugLoc dl,
7220                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7221                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7222   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7223   assert(LdOpc != 0 && "Should have a load opcode");
7224   if (LdSize >= 8) {
7225     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7226                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7227                        .addImm(0));
7228   } else if (IsThumb1) {
7229     // load + update AddrIn
7230     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7231                        .addReg(AddrIn).addImm(0));
7232     MachineInstrBuilder MIB =
7233         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7234     MIB = AddDefaultT1CC(MIB);
7235     MIB.addReg(AddrIn).addImm(LdSize);
7236     AddDefaultPred(MIB);
7237   } else if (IsThumb2) {
7238     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7239                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7240                        .addImm(LdSize));
7241   } else { // arm
7242     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7243                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7244                        .addReg(0).addImm(LdSize));
7245   }
7246 }
7247
7248 /// Emit a post-increment store operation with given size. The instructions
7249 /// will be added to BB at Pos.
7250 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7251                        const TargetInstrInfo *TII, DebugLoc dl,
7252                        unsigned StSize, unsigned Data, unsigned AddrIn,
7253                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7254   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7255   assert(StOpc != 0 && "Should have a store opcode");
7256   if (StSize >= 8) {
7257     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7258                        .addReg(AddrIn).addImm(0).addReg(Data));
7259   } else if (IsThumb1) {
7260     // store + update AddrIn
7261     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7262                        .addReg(AddrIn).addImm(0));
7263     MachineInstrBuilder MIB =
7264         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7265     MIB = AddDefaultT1CC(MIB);
7266     MIB.addReg(AddrIn).addImm(StSize);
7267     AddDefaultPred(MIB);
7268   } else if (IsThumb2) {
7269     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7270                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7271   } else { // arm
7272     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7273                        .addReg(Data).addReg(AddrIn).addReg(0)
7274                        .addImm(StSize));
7275   }
7276 }
7277
7278 MachineBasicBlock *
7279 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7280                                    MachineBasicBlock *BB) const {
7281   // This pseudo instruction has 3 operands: dst, src, size
7282   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7283   // Otherwise, we will generate unrolled scalar copies.
7284   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7285   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7286   MachineFunction::iterator It = BB;
7287   ++It;
7288
7289   unsigned dest = MI->getOperand(0).getReg();
7290   unsigned src = MI->getOperand(1).getReg();
7291   unsigned SizeVal = MI->getOperand(2).getImm();
7292   unsigned Align = MI->getOperand(3).getImm();
7293   DebugLoc dl = MI->getDebugLoc();
7294
7295   MachineFunction *MF = BB->getParent();
7296   MachineRegisterInfo &MRI = MF->getRegInfo();
7297   unsigned UnitSize = 0;
7298   const TargetRegisterClass *TRC = nullptr;
7299   const TargetRegisterClass *VecTRC = nullptr;
7300
7301   bool IsThumb1 = Subtarget->isThumb1Only();
7302   bool IsThumb2 = Subtarget->isThumb2();
7303
7304   if (Align & 1) {
7305     UnitSize = 1;
7306   } else if (Align & 2) {
7307     UnitSize = 2;
7308   } else {
7309     // Check whether we can use NEON instructions.
7310     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7311         Subtarget->hasNEON()) {
7312       if ((Align % 16 == 0) && SizeVal >= 16)
7313         UnitSize = 16;
7314       else if ((Align % 8 == 0) && SizeVal >= 8)
7315         UnitSize = 8;
7316     }
7317     // Can't use NEON instructions.
7318     if (UnitSize == 0)
7319       UnitSize = 4;
7320   }
7321
7322   // Select the correct opcode and register class for unit size load/store
7323   bool IsNeon = UnitSize >= 8;
7324   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7325   if (IsNeon)
7326     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7327                             : UnitSize == 8 ? &ARM::DPRRegClass
7328                                             : nullptr;
7329
7330   unsigned BytesLeft = SizeVal % UnitSize;
7331   unsigned LoopSize = SizeVal - BytesLeft;
7332
7333   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7334     // Use LDR and STR to copy.
7335     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7336     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7337     unsigned srcIn = src;
7338     unsigned destIn = dest;
7339     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7340       unsigned srcOut = MRI.createVirtualRegister(TRC);
7341       unsigned destOut = MRI.createVirtualRegister(TRC);
7342       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7343       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7344                  IsThumb1, IsThumb2);
7345       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7346                  IsThumb1, IsThumb2);
7347       srcIn = srcOut;
7348       destIn = destOut;
7349     }
7350
7351     // Handle the leftover bytes with LDRB and STRB.
7352     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7353     // [destOut] = STRB_POST(scratch, destIn, 1)
7354     for (unsigned i = 0; i < BytesLeft; i++) {
7355       unsigned srcOut = MRI.createVirtualRegister(TRC);
7356       unsigned destOut = MRI.createVirtualRegister(TRC);
7357       unsigned scratch = MRI.createVirtualRegister(TRC);
7358       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7359                  IsThumb1, IsThumb2);
7360       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7361                  IsThumb1, IsThumb2);
7362       srcIn = srcOut;
7363       destIn = destOut;
7364     }
7365     MI->eraseFromParent();   // The instruction is gone now.
7366     return BB;
7367   }
7368
7369   // Expand the pseudo op to a loop.
7370   // thisMBB:
7371   //   ...
7372   //   movw varEnd, # --> with thumb2
7373   //   movt varEnd, #
7374   //   ldrcp varEnd, idx --> without thumb2
7375   //   fallthrough --> loopMBB
7376   // loopMBB:
7377   //   PHI varPhi, varEnd, varLoop
7378   //   PHI srcPhi, src, srcLoop
7379   //   PHI destPhi, dst, destLoop
7380   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7381   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7382   //   subs varLoop, varPhi, #UnitSize
7383   //   bne loopMBB
7384   //   fallthrough --> exitMBB
7385   // exitMBB:
7386   //   epilogue to handle left-over bytes
7387   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7388   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7389   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7390   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7391   MF->insert(It, loopMBB);
7392   MF->insert(It, exitMBB);
7393
7394   // Transfer the remainder of BB and its successor edges to exitMBB.
7395   exitMBB->splice(exitMBB->begin(), BB,
7396                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7397   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7398
7399   // Load an immediate to varEnd.
7400   unsigned varEnd = MRI.createVirtualRegister(TRC);
7401   if (Subtarget->useMovt(*MF)) {
7402     unsigned Vtmp = varEnd;
7403     if ((LoopSize & 0xFFFF0000) != 0)
7404       Vtmp = MRI.createVirtualRegister(TRC);
7405     AddDefaultPred(BuildMI(BB, dl,
7406                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7407                            Vtmp).addImm(LoopSize & 0xFFFF));
7408
7409     if ((LoopSize & 0xFFFF0000) != 0)
7410       AddDefaultPred(BuildMI(BB, dl,
7411                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7412                              varEnd)
7413                          .addReg(Vtmp)
7414                          .addImm(LoopSize >> 16));
7415   } else {
7416     MachineConstantPool *ConstantPool = MF->getConstantPool();
7417     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7418     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7419
7420     // MachineConstantPool wants an explicit alignment.
7421     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7422     if (Align == 0)
7423       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7424     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7425
7426     if (IsThumb1)
7427       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7428           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7429     else
7430       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7431           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7432   }
7433   BB->addSuccessor(loopMBB);
7434
7435   // Generate the loop body:
7436   //   varPhi = PHI(varLoop, varEnd)
7437   //   srcPhi = PHI(srcLoop, src)
7438   //   destPhi = PHI(destLoop, dst)
7439   MachineBasicBlock *entryBB = BB;
7440   BB = loopMBB;
7441   unsigned varLoop = MRI.createVirtualRegister(TRC);
7442   unsigned varPhi = MRI.createVirtualRegister(TRC);
7443   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7444   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7445   unsigned destLoop = MRI.createVirtualRegister(TRC);
7446   unsigned destPhi = MRI.createVirtualRegister(TRC);
7447
7448   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7449     .addReg(varLoop).addMBB(loopMBB)
7450     .addReg(varEnd).addMBB(entryBB);
7451   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7452     .addReg(srcLoop).addMBB(loopMBB)
7453     .addReg(src).addMBB(entryBB);
7454   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7455     .addReg(destLoop).addMBB(loopMBB)
7456     .addReg(dest).addMBB(entryBB);
7457
7458   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7459   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7460   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7461   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7462              IsThumb1, IsThumb2);
7463   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7464              IsThumb1, IsThumb2);
7465
7466   // Decrement loop variable by UnitSize.
7467   if (IsThumb1) {
7468     MachineInstrBuilder MIB =
7469         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7470     MIB = AddDefaultT1CC(MIB);
7471     MIB.addReg(varPhi).addImm(UnitSize);
7472     AddDefaultPred(MIB);
7473   } else {
7474     MachineInstrBuilder MIB =
7475         BuildMI(*BB, BB->end(), dl,
7476                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7477     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7478     MIB->getOperand(5).setReg(ARM::CPSR);
7479     MIB->getOperand(5).setIsDef(true);
7480   }
7481   BuildMI(*BB, BB->end(), dl,
7482           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7483       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7484
7485   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7486   BB->addSuccessor(loopMBB);
7487   BB->addSuccessor(exitMBB);
7488
7489   // Add epilogue to handle BytesLeft.
7490   BB = exitMBB;
7491   MachineInstr *StartOfExit = exitMBB->begin();
7492
7493   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7494   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7495   unsigned srcIn = srcLoop;
7496   unsigned destIn = destLoop;
7497   for (unsigned i = 0; i < BytesLeft; i++) {
7498     unsigned srcOut = MRI.createVirtualRegister(TRC);
7499     unsigned destOut = MRI.createVirtualRegister(TRC);
7500     unsigned scratch = MRI.createVirtualRegister(TRC);
7501     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7502                IsThumb1, IsThumb2);
7503     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7504                IsThumb1, IsThumb2);
7505     srcIn = srcOut;
7506     destIn = destOut;
7507   }
7508
7509   MI->eraseFromParent();   // The instruction is gone now.
7510   return BB;
7511 }
7512
7513 MachineBasicBlock *
7514 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7515                                        MachineBasicBlock *MBB) const {
7516   const TargetMachine &TM = getTargetMachine();
7517   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7518   DebugLoc DL = MI->getDebugLoc();
7519
7520   assert(Subtarget->isTargetWindows() &&
7521          "__chkstk is only supported on Windows");
7522   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7523
7524   // __chkstk takes the number of words to allocate on the stack in R4, and
7525   // returns the stack adjustment in number of bytes in R4.  This will not
7526   // clober any other registers (other than the obvious lr).
7527   //
7528   // Although, technically, IP should be considered a register which may be
7529   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7530   // thumb-2 environment, so there is no interworking required.  As a result, we
7531   // do not expect a veneer to be emitted by the linker, clobbering IP.
7532   //
7533   // Each module receives its own copy of __chkstk, so no import thunk is
7534   // required, again, ensuring that IP is not clobbered.
7535   //
7536   // Finally, although some linkers may theoretically provide a trampoline for
7537   // out of range calls (which is quite common due to a 32M range limitation of
7538   // branches for Thumb), we can generate the long-call version via
7539   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7540   // IP.
7541
7542   switch (TM.getCodeModel()) {
7543   case CodeModel::Small:
7544   case CodeModel::Medium:
7545   case CodeModel::Default:
7546   case CodeModel::Kernel:
7547     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7548       .addImm((unsigned)ARMCC::AL).addReg(0)
7549       .addExternalSymbol("__chkstk")
7550       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7551       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7552       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7553     break;
7554   case CodeModel::Large:
7555   case CodeModel::JITDefault: {
7556     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7557     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7558
7559     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7560       .addExternalSymbol("__chkstk");
7561     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7562       .addImm((unsigned)ARMCC::AL).addReg(0)
7563       .addReg(Reg, RegState::Kill)
7564       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7565       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7566       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7567     break;
7568   }
7569   }
7570
7571   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7572                                       ARM::SP)
7573                               .addReg(ARM::SP).addReg(ARM::R4)));
7574
7575   MI->eraseFromParent();
7576   return MBB;
7577 }
7578
7579 MachineBasicBlock *
7580 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7581                                                MachineBasicBlock *BB) const {
7582   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7583   DebugLoc dl = MI->getDebugLoc();
7584   bool isThumb2 = Subtarget->isThumb2();
7585   switch (MI->getOpcode()) {
7586   default: {
7587     MI->dump();
7588     llvm_unreachable("Unexpected instr type to insert");
7589   }
7590   // The Thumb2 pre-indexed stores have the same MI operands, they just
7591   // define them differently in the .td files from the isel patterns, so
7592   // they need pseudos.
7593   case ARM::t2STR_preidx:
7594     MI->setDesc(TII->get(ARM::t2STR_PRE));
7595     return BB;
7596   case ARM::t2STRB_preidx:
7597     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7598     return BB;
7599   case ARM::t2STRH_preidx:
7600     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7601     return BB;
7602
7603   case ARM::STRi_preidx:
7604   case ARM::STRBi_preidx: {
7605     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7606       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7607     // Decode the offset.
7608     unsigned Offset = MI->getOperand(4).getImm();
7609     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7610     Offset = ARM_AM::getAM2Offset(Offset);
7611     if (isSub)
7612       Offset = -Offset;
7613
7614     MachineMemOperand *MMO = *MI->memoperands_begin();
7615     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7616       .addOperand(MI->getOperand(0))  // Rn_wb
7617       .addOperand(MI->getOperand(1))  // Rt
7618       .addOperand(MI->getOperand(2))  // Rn
7619       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7620       .addOperand(MI->getOperand(5))  // pred
7621       .addOperand(MI->getOperand(6))
7622       .addMemOperand(MMO);
7623     MI->eraseFromParent();
7624     return BB;
7625   }
7626   case ARM::STRr_preidx:
7627   case ARM::STRBr_preidx:
7628   case ARM::STRH_preidx: {
7629     unsigned NewOpc;
7630     switch (MI->getOpcode()) {
7631     default: llvm_unreachable("unexpected opcode!");
7632     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7633     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7634     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7635     }
7636     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7637     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7638       MIB.addOperand(MI->getOperand(i));
7639     MI->eraseFromParent();
7640     return BB;
7641   }
7642
7643   case ARM::tMOVCCr_pseudo: {
7644     // To "insert" a SELECT_CC instruction, we actually have to insert the
7645     // diamond control-flow pattern.  The incoming instruction knows the
7646     // destination vreg to set, the condition code register to branch on, the
7647     // true/false values to select between, and a branch opcode to use.
7648     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7649     MachineFunction::iterator It = BB;
7650     ++It;
7651
7652     //  thisMBB:
7653     //  ...
7654     //   TrueVal = ...
7655     //   cmpTY ccX, r1, r2
7656     //   bCC copy1MBB
7657     //   fallthrough --> copy0MBB
7658     MachineBasicBlock *thisMBB  = BB;
7659     MachineFunction *F = BB->getParent();
7660     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7661     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7662     F->insert(It, copy0MBB);
7663     F->insert(It, sinkMBB);
7664
7665     // Transfer the remainder of BB and its successor edges to sinkMBB.
7666     sinkMBB->splice(sinkMBB->begin(), BB,
7667                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7668     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7669
7670     BB->addSuccessor(copy0MBB);
7671     BB->addSuccessor(sinkMBB);
7672
7673     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7674       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7675
7676     //  copy0MBB:
7677     //   %FalseValue = ...
7678     //   # fallthrough to sinkMBB
7679     BB = copy0MBB;
7680
7681     // Update machine-CFG edges
7682     BB->addSuccessor(sinkMBB);
7683
7684     //  sinkMBB:
7685     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7686     //  ...
7687     BB = sinkMBB;
7688     BuildMI(*BB, BB->begin(), dl,
7689             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7690       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7691       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7692
7693     MI->eraseFromParent();   // The pseudo instruction is gone now.
7694     return BB;
7695   }
7696
7697   case ARM::BCCi64:
7698   case ARM::BCCZi64: {
7699     // If there is an unconditional branch to the other successor, remove it.
7700     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7701
7702     // Compare both parts that make up the double comparison separately for
7703     // equality.
7704     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7705
7706     unsigned LHS1 = MI->getOperand(1).getReg();
7707     unsigned LHS2 = MI->getOperand(2).getReg();
7708     if (RHSisZero) {
7709       AddDefaultPred(BuildMI(BB, dl,
7710                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7711                      .addReg(LHS1).addImm(0));
7712       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7713         .addReg(LHS2).addImm(0)
7714         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7715     } else {
7716       unsigned RHS1 = MI->getOperand(3).getReg();
7717       unsigned RHS2 = MI->getOperand(4).getReg();
7718       AddDefaultPred(BuildMI(BB, dl,
7719                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7720                      .addReg(LHS1).addReg(RHS1));
7721       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7722         .addReg(LHS2).addReg(RHS2)
7723         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7724     }
7725
7726     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7727     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7728     if (MI->getOperand(0).getImm() == ARMCC::NE)
7729       std::swap(destMBB, exitMBB);
7730
7731     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7732       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7733     if (isThumb2)
7734       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7735     else
7736       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7737
7738     MI->eraseFromParent();   // The pseudo instruction is gone now.
7739     return BB;
7740   }
7741
7742   case ARM::Int_eh_sjlj_setjmp:
7743   case ARM::Int_eh_sjlj_setjmp_nofp:
7744   case ARM::tInt_eh_sjlj_setjmp:
7745   case ARM::t2Int_eh_sjlj_setjmp:
7746   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7747     return BB;
7748
7749   case ARM::Int_eh_sjlj_setup_dispatch:
7750     EmitSjLjDispatchBlock(MI, BB);
7751     return BB;
7752
7753   case ARM::ABS:
7754   case ARM::t2ABS: {
7755     // To insert an ABS instruction, we have to insert the
7756     // diamond control-flow pattern.  The incoming instruction knows the
7757     // source vreg to test against 0, the destination vreg to set,
7758     // the condition code register to branch on, the
7759     // true/false values to select between, and a branch opcode to use.
7760     // It transforms
7761     //     V1 = ABS V0
7762     // into
7763     //     V2 = MOVS V0
7764     //     BCC                      (branch to SinkBB if V0 >= 0)
7765     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7766     //     SinkBB: V1 = PHI(V2, V3)
7767     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7768     MachineFunction::iterator BBI = BB;
7769     ++BBI;
7770     MachineFunction *Fn = BB->getParent();
7771     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7772     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7773     Fn->insert(BBI, RSBBB);
7774     Fn->insert(BBI, SinkBB);
7775
7776     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7777     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7778     bool ABSSrcKIll = MI->getOperand(1).isKill();
7779     bool isThumb2 = Subtarget->isThumb2();
7780     MachineRegisterInfo &MRI = Fn->getRegInfo();
7781     // In Thumb mode S must not be specified if source register is the SP or
7782     // PC and if destination register is the SP, so restrict register class
7783     unsigned NewRsbDstReg =
7784       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7785
7786     // Transfer the remainder of BB and its successor edges to sinkMBB.
7787     SinkBB->splice(SinkBB->begin(), BB,
7788                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7789     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7790
7791     BB->addSuccessor(RSBBB);
7792     BB->addSuccessor(SinkBB);
7793
7794     // fall through to SinkMBB
7795     RSBBB->addSuccessor(SinkBB);
7796
7797     // insert a cmp at the end of BB
7798     AddDefaultPred(BuildMI(BB, dl,
7799                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7800                    .addReg(ABSSrcReg).addImm(0));
7801
7802     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7803     BuildMI(BB, dl,
7804       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7805       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7806
7807     // insert rsbri in RSBBB
7808     // Note: BCC and rsbri will be converted into predicated rsbmi
7809     // by if-conversion pass
7810     BuildMI(*RSBBB, RSBBB->begin(), dl,
7811       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7812       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7813       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7814
7815     // insert PHI in SinkBB,
7816     // reuse ABSDstReg to not change uses of ABS instruction
7817     BuildMI(*SinkBB, SinkBB->begin(), dl,
7818       TII->get(ARM::PHI), ABSDstReg)
7819       .addReg(NewRsbDstReg).addMBB(RSBBB)
7820       .addReg(ABSSrcReg).addMBB(BB);
7821
7822     // remove ABS instruction
7823     MI->eraseFromParent();
7824
7825     // return last added BB
7826     return SinkBB;
7827   }
7828   case ARM::COPY_STRUCT_BYVAL_I32:
7829     ++NumLoopByVals;
7830     return EmitStructByval(MI, BB);
7831   case ARM::WIN__CHKSTK:
7832     return EmitLowered__chkstk(MI, BB);
7833   }
7834 }
7835
7836 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7837                                                       SDNode *Node) const {
7838   const MCInstrDesc *MCID = &MI->getDesc();
7839   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7840   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7841   // operand is still set to noreg. If needed, set the optional operand's
7842   // register to CPSR, and remove the redundant implicit def.
7843   //
7844   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7845
7846   // Rename pseudo opcodes.
7847   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7848   if (NewOpc) {
7849     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7850     MCID = &TII->get(NewOpc);
7851
7852     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7853            "converted opcode should be the same except for cc_out");
7854
7855     MI->setDesc(*MCID);
7856
7857     // Add the optional cc_out operand
7858     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7859   }
7860   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7861
7862   // Any ARM instruction that sets the 's' bit should specify an optional
7863   // "cc_out" operand in the last operand position.
7864   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7865     assert(!NewOpc && "Optional cc_out operand required");
7866     return;
7867   }
7868   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7869   // since we already have an optional CPSR def.
7870   bool definesCPSR = false;
7871   bool deadCPSR = false;
7872   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7873        i != e; ++i) {
7874     const MachineOperand &MO = MI->getOperand(i);
7875     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7876       definesCPSR = true;
7877       if (MO.isDead())
7878         deadCPSR = true;
7879       MI->RemoveOperand(i);
7880       break;
7881     }
7882   }
7883   if (!definesCPSR) {
7884     assert(!NewOpc && "Optional cc_out operand required");
7885     return;
7886   }
7887   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7888   if (deadCPSR) {
7889     assert(!MI->getOperand(ccOutIdx).getReg() &&
7890            "expect uninitialized optional cc_out operand");
7891     return;
7892   }
7893
7894   // If this instruction was defined with an optional CPSR def and its dag node
7895   // had a live implicit CPSR def, then activate the optional CPSR def.
7896   MachineOperand &MO = MI->getOperand(ccOutIdx);
7897   MO.setReg(ARM::CPSR);
7898   MO.setIsDef(true);
7899 }
7900
7901 //===----------------------------------------------------------------------===//
7902 //                           ARM Optimization Hooks
7903 //===----------------------------------------------------------------------===//
7904
7905 // Helper function that checks if N is a null or all ones constant.
7906 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7907   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7908   if (!C)
7909     return false;
7910   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7911 }
7912
7913 // Return true if N is conditionally 0 or all ones.
7914 // Detects these expressions where cc is an i1 value:
7915 //
7916 //   (select cc 0, y)   [AllOnes=0]
7917 //   (select cc y, 0)   [AllOnes=0]
7918 //   (zext cc)          [AllOnes=0]
7919 //   (sext cc)          [AllOnes=0/1]
7920 //   (select cc -1, y)  [AllOnes=1]
7921 //   (select cc y, -1)  [AllOnes=1]
7922 //
7923 // Invert is set when N is the null/all ones constant when CC is false.
7924 // OtherOp is set to the alternative value of N.
7925 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7926                                        SDValue &CC, bool &Invert,
7927                                        SDValue &OtherOp,
7928                                        SelectionDAG &DAG) {
7929   switch (N->getOpcode()) {
7930   default: return false;
7931   case ISD::SELECT: {
7932     CC = N->getOperand(0);
7933     SDValue N1 = N->getOperand(1);
7934     SDValue N2 = N->getOperand(2);
7935     if (isZeroOrAllOnes(N1, AllOnes)) {
7936       Invert = false;
7937       OtherOp = N2;
7938       return true;
7939     }
7940     if (isZeroOrAllOnes(N2, AllOnes)) {
7941       Invert = true;
7942       OtherOp = N1;
7943       return true;
7944     }
7945     return false;
7946   }
7947   case ISD::ZERO_EXTEND:
7948     // (zext cc) can never be the all ones value.
7949     if (AllOnes)
7950       return false;
7951     // Fall through.
7952   case ISD::SIGN_EXTEND: {
7953     SDLoc dl(N);
7954     EVT VT = N->getValueType(0);
7955     CC = N->getOperand(0);
7956     if (CC.getValueType() != MVT::i1)
7957       return false;
7958     Invert = !AllOnes;
7959     if (AllOnes)
7960       // When looking for an AllOnes constant, N is an sext, and the 'other'
7961       // value is 0.
7962       OtherOp = DAG.getConstant(0, dl, VT);
7963     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7964       // When looking for a 0 constant, N can be zext or sext.
7965       OtherOp = DAG.getConstant(1, dl, VT);
7966     else
7967       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
7968                                 VT);
7969     return true;
7970   }
7971   }
7972 }
7973
7974 // Combine a constant select operand into its use:
7975 //
7976 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7977 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7978 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7979 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7980 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7981 //
7982 // The transform is rejected if the select doesn't have a constant operand that
7983 // is null, or all ones when AllOnes is set.
7984 //
7985 // Also recognize sext/zext from i1:
7986 //
7987 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7988 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7989 //
7990 // These transformations eventually create predicated instructions.
7991 //
7992 // @param N       The node to transform.
7993 // @param Slct    The N operand that is a select.
7994 // @param OtherOp The other N operand (x above).
7995 // @param DCI     Context.
7996 // @param AllOnes Require the select constant to be all ones instead of null.
7997 // @returns The new node, or SDValue() on failure.
7998 static
7999 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8000                             TargetLowering::DAGCombinerInfo &DCI,
8001                             bool AllOnes = false) {
8002   SelectionDAG &DAG = DCI.DAG;
8003   EVT VT = N->getValueType(0);
8004   SDValue NonConstantVal;
8005   SDValue CCOp;
8006   bool SwapSelectOps;
8007   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8008                                   NonConstantVal, DAG))
8009     return SDValue();
8010
8011   // Slct is now know to be the desired identity constant when CC is true.
8012   SDValue TrueVal = OtherOp;
8013   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8014                                  OtherOp, NonConstantVal);
8015   // Unless SwapSelectOps says CC should be false.
8016   if (SwapSelectOps)
8017     std::swap(TrueVal, FalseVal);
8018
8019   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8020                      CCOp, TrueVal, FalseVal);
8021 }
8022
8023 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8024 static
8025 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8026                                        TargetLowering::DAGCombinerInfo &DCI) {
8027   SDValue N0 = N->getOperand(0);
8028   SDValue N1 = N->getOperand(1);
8029   if (N0.getNode()->hasOneUse()) {
8030     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8031     if (Result.getNode())
8032       return Result;
8033   }
8034   if (N1.getNode()->hasOneUse()) {
8035     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8036     if (Result.getNode())
8037       return Result;
8038   }
8039   return SDValue();
8040 }
8041
8042 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8043 // (only after legalization).
8044 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8045                                  TargetLowering::DAGCombinerInfo &DCI,
8046                                  const ARMSubtarget *Subtarget) {
8047
8048   // Only perform optimization if after legalize, and if NEON is available. We
8049   // also expected both operands to be BUILD_VECTORs.
8050   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8051       || N0.getOpcode() != ISD::BUILD_VECTOR
8052       || N1.getOpcode() != ISD::BUILD_VECTOR)
8053     return SDValue();
8054
8055   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8056   EVT VT = N->getValueType(0);
8057   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8058     return SDValue();
8059
8060   // Check that the vector operands are of the right form.
8061   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8062   // operands, where N is the size of the formed vector.
8063   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8064   // index such that we have a pair wise add pattern.
8065
8066   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8067   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8068     return SDValue();
8069   SDValue Vec = N0->getOperand(0)->getOperand(0);
8070   SDNode *V = Vec.getNode();
8071   unsigned nextIndex = 0;
8072
8073   // For each operands to the ADD which are BUILD_VECTORs,
8074   // check to see if each of their operands are an EXTRACT_VECTOR with
8075   // the same vector and appropriate index.
8076   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8077     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8078         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8079
8080       SDValue ExtVec0 = N0->getOperand(i);
8081       SDValue ExtVec1 = N1->getOperand(i);
8082
8083       // First operand is the vector, verify its the same.
8084       if (V != ExtVec0->getOperand(0).getNode() ||
8085           V != ExtVec1->getOperand(0).getNode())
8086         return SDValue();
8087
8088       // Second is the constant, verify its correct.
8089       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8090       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8091
8092       // For the constant, we want to see all the even or all the odd.
8093       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8094           || C1->getZExtValue() != nextIndex+1)
8095         return SDValue();
8096
8097       // Increment index.
8098       nextIndex+=2;
8099     } else
8100       return SDValue();
8101   }
8102
8103   // Create VPADDL node.
8104   SelectionDAG &DAG = DCI.DAG;
8105   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8106
8107   SDLoc dl(N);
8108
8109   // Build operand list.
8110   SmallVector<SDValue, 8> Ops;
8111   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8112                                 TLI.getPointerTy(DAG.getDataLayout())));
8113
8114   // Input is the vector.
8115   Ops.push_back(Vec);
8116
8117   // Get widened type and narrowed type.
8118   MVT widenType;
8119   unsigned numElem = VT.getVectorNumElements();
8120   
8121   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8122   switch (inputLaneType.getSimpleVT().SimpleTy) {
8123     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8124     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8125     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8126     default:
8127       llvm_unreachable("Invalid vector element type for padd optimization.");
8128   }
8129
8130   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8131   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8132   return DAG.getNode(ExtOp, dl, VT, tmp);
8133 }
8134
8135 static SDValue findMUL_LOHI(SDValue V) {
8136   if (V->getOpcode() == ISD::UMUL_LOHI ||
8137       V->getOpcode() == ISD::SMUL_LOHI)
8138     return V;
8139   return SDValue();
8140 }
8141
8142 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8143                                      TargetLowering::DAGCombinerInfo &DCI,
8144                                      const ARMSubtarget *Subtarget) {
8145
8146   if (Subtarget->isThumb1Only()) return SDValue();
8147
8148   // Only perform the checks after legalize when the pattern is available.
8149   if (DCI.isBeforeLegalize()) return SDValue();
8150
8151   // Look for multiply add opportunities.
8152   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8153   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8154   // a glue link from the first add to the second add.
8155   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8156   // a S/UMLAL instruction.
8157   //                  UMUL_LOHI
8158   //                 / :lo    \ :hi
8159   //                /          \          [no multiline comment]
8160   //    loAdd ->  ADDE         |
8161   //                 \ :glue  /
8162   //                  \      /
8163   //                    ADDC   <- hiAdd
8164   //
8165   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8166   SDValue AddcOp0 = AddcNode->getOperand(0);
8167   SDValue AddcOp1 = AddcNode->getOperand(1);
8168
8169   // Check if the two operands are from the same mul_lohi node.
8170   if (AddcOp0.getNode() == AddcOp1.getNode())
8171     return SDValue();
8172
8173   assert(AddcNode->getNumValues() == 2 &&
8174          AddcNode->getValueType(0) == MVT::i32 &&
8175          "Expect ADDC with two result values. First: i32");
8176
8177   // Check that we have a glued ADDC node.
8178   if (AddcNode->getValueType(1) != MVT::Glue)
8179     return SDValue();
8180
8181   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8182   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8183       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8184       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8185       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8186     return SDValue();
8187
8188   // Look for the glued ADDE.
8189   SDNode* AddeNode = AddcNode->getGluedUser();
8190   if (!AddeNode)
8191     return SDValue();
8192
8193   // Make sure it is really an ADDE.
8194   if (AddeNode->getOpcode() != ISD::ADDE)
8195     return SDValue();
8196
8197   assert(AddeNode->getNumOperands() == 3 &&
8198          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8199          "ADDE node has the wrong inputs");
8200
8201   // Check for the triangle shape.
8202   SDValue AddeOp0 = AddeNode->getOperand(0);
8203   SDValue AddeOp1 = AddeNode->getOperand(1);
8204
8205   // Make sure that the ADDE operands are not coming from the same node.
8206   if (AddeOp0.getNode() == AddeOp1.getNode())
8207     return SDValue();
8208
8209   // Find the MUL_LOHI node walking up ADDE's operands.
8210   bool IsLeftOperandMUL = false;
8211   SDValue MULOp = findMUL_LOHI(AddeOp0);
8212   if (MULOp == SDValue())
8213    MULOp = findMUL_LOHI(AddeOp1);
8214   else
8215     IsLeftOperandMUL = true;
8216   if (MULOp == SDValue())
8217     return SDValue();
8218
8219   // Figure out the right opcode.
8220   unsigned Opc = MULOp->getOpcode();
8221   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8222
8223   // Figure out the high and low input values to the MLAL node.
8224   SDValue* HiAdd = nullptr;
8225   SDValue* LoMul = nullptr;
8226   SDValue* LowAdd = nullptr;
8227
8228   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8229   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8230     return SDValue();
8231
8232   if (IsLeftOperandMUL)
8233     HiAdd = &AddeOp1;
8234   else
8235     HiAdd = &AddeOp0;
8236
8237
8238   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8239   // whose low result is fed to the ADDC we are checking.
8240
8241   if (AddcOp0 == MULOp.getValue(0)) {
8242     LoMul = &AddcOp0;
8243     LowAdd = &AddcOp1;
8244   }
8245   if (AddcOp1 == MULOp.getValue(0)) {
8246     LoMul = &AddcOp1;
8247     LowAdd = &AddcOp0;
8248   }
8249
8250   if (!LoMul)
8251     return SDValue();
8252
8253   // Create the merged node.
8254   SelectionDAG &DAG = DCI.DAG;
8255
8256   // Build operand list.
8257   SmallVector<SDValue, 8> Ops;
8258   Ops.push_back(LoMul->getOperand(0));
8259   Ops.push_back(LoMul->getOperand(1));
8260   Ops.push_back(*LowAdd);
8261   Ops.push_back(*HiAdd);
8262
8263   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8264                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8265
8266   // Replace the ADDs' nodes uses by the MLA node's values.
8267   SDValue HiMLALResult(MLALNode.getNode(), 1);
8268   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8269
8270   SDValue LoMLALResult(MLALNode.getNode(), 0);
8271   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8272
8273   // Return original node to notify the driver to stop replacing.
8274   SDValue resNode(AddcNode, 0);
8275   return resNode;
8276 }
8277
8278 /// PerformADDCCombine - Target-specific dag combine transform from
8279 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8280 static SDValue PerformADDCCombine(SDNode *N,
8281                                  TargetLowering::DAGCombinerInfo &DCI,
8282                                  const ARMSubtarget *Subtarget) {
8283
8284   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8285
8286 }
8287
8288 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8289 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8290 /// called with the default operands, and if that fails, with commuted
8291 /// operands.
8292 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8293                                           TargetLowering::DAGCombinerInfo &DCI,
8294                                           const ARMSubtarget *Subtarget){
8295
8296   // Attempt to create vpaddl for this add.
8297   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8298   if (Result.getNode())
8299     return Result;
8300
8301   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8302   if (N0.getNode()->hasOneUse()) {
8303     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8304     if (Result.getNode()) return Result;
8305   }
8306   return SDValue();
8307 }
8308
8309 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8310 ///
8311 static SDValue PerformADDCombine(SDNode *N,
8312                                  TargetLowering::DAGCombinerInfo &DCI,
8313                                  const ARMSubtarget *Subtarget) {
8314   SDValue N0 = N->getOperand(0);
8315   SDValue N1 = N->getOperand(1);
8316
8317   // First try with the default operand order.
8318   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8319   if (Result.getNode())
8320     return Result;
8321
8322   // If that didn't work, try again with the operands commuted.
8323   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8324 }
8325
8326 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8327 ///
8328 static SDValue PerformSUBCombine(SDNode *N,
8329                                  TargetLowering::DAGCombinerInfo &DCI) {
8330   SDValue N0 = N->getOperand(0);
8331   SDValue N1 = N->getOperand(1);
8332
8333   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8334   if (N1.getNode()->hasOneUse()) {
8335     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8336     if (Result.getNode()) return Result;
8337   }
8338
8339   return SDValue();
8340 }
8341
8342 /// PerformVMULCombine
8343 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8344 /// special multiplier accumulator forwarding.
8345 ///   vmul d3, d0, d2
8346 ///   vmla d3, d1, d2
8347 /// is faster than
8348 ///   vadd d3, d0, d1
8349 ///   vmul d3, d3, d2
8350 //  However, for (A + B) * (A + B),
8351 //    vadd d2, d0, d1
8352 //    vmul d3, d0, d2
8353 //    vmla d3, d1, d2
8354 //  is slower than
8355 //    vadd d2, d0, d1
8356 //    vmul d3, d2, d2
8357 static SDValue PerformVMULCombine(SDNode *N,
8358                                   TargetLowering::DAGCombinerInfo &DCI,
8359                                   const ARMSubtarget *Subtarget) {
8360   if (!Subtarget->hasVMLxForwarding())
8361     return SDValue();
8362
8363   SelectionDAG &DAG = DCI.DAG;
8364   SDValue N0 = N->getOperand(0);
8365   SDValue N1 = N->getOperand(1);
8366   unsigned Opcode = N0.getOpcode();
8367   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8368       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8369     Opcode = N1.getOpcode();
8370     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8371         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8372       return SDValue();
8373     std::swap(N0, N1);
8374   }
8375
8376   if (N0 == N1)
8377     return SDValue();
8378
8379   EVT VT = N->getValueType(0);
8380   SDLoc DL(N);
8381   SDValue N00 = N0->getOperand(0);
8382   SDValue N01 = N0->getOperand(1);
8383   return DAG.getNode(Opcode, DL, VT,
8384                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8385                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8386 }
8387
8388 static SDValue PerformMULCombine(SDNode *N,
8389                                  TargetLowering::DAGCombinerInfo &DCI,
8390                                  const ARMSubtarget *Subtarget) {
8391   SelectionDAG &DAG = DCI.DAG;
8392
8393   if (Subtarget->isThumb1Only())
8394     return SDValue();
8395
8396   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8397     return SDValue();
8398
8399   EVT VT = N->getValueType(0);
8400   if (VT.is64BitVector() || VT.is128BitVector())
8401     return PerformVMULCombine(N, DCI, Subtarget);
8402   if (VT != MVT::i32)
8403     return SDValue();
8404
8405   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8406   if (!C)
8407     return SDValue();
8408
8409   int64_t MulAmt = C->getSExtValue();
8410   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8411
8412   ShiftAmt = ShiftAmt & (32 - 1);
8413   SDValue V = N->getOperand(0);
8414   SDLoc DL(N);
8415
8416   SDValue Res;
8417   MulAmt >>= ShiftAmt;
8418
8419   if (MulAmt >= 0) {
8420     if (isPowerOf2_32(MulAmt - 1)) {
8421       // (mul x, 2^N + 1) => (add (shl x, N), x)
8422       Res = DAG.getNode(ISD::ADD, DL, VT,
8423                         V,
8424                         DAG.getNode(ISD::SHL, DL, VT,
8425                                     V,
8426                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8427                                                     MVT::i32)));
8428     } else if (isPowerOf2_32(MulAmt + 1)) {
8429       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8430       Res = DAG.getNode(ISD::SUB, DL, VT,
8431                         DAG.getNode(ISD::SHL, DL, VT,
8432                                     V,
8433                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8434                                                     MVT::i32)),
8435                         V);
8436     } else
8437       return SDValue();
8438   } else {
8439     uint64_t MulAmtAbs = -MulAmt;
8440     if (isPowerOf2_32(MulAmtAbs + 1)) {
8441       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8442       Res = DAG.getNode(ISD::SUB, DL, VT,
8443                         V,
8444                         DAG.getNode(ISD::SHL, DL, VT,
8445                                     V,
8446                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8447                                                     MVT::i32)));
8448     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8449       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8450       Res = DAG.getNode(ISD::ADD, DL, VT,
8451                         V,
8452                         DAG.getNode(ISD::SHL, DL, VT,
8453                                     V,
8454                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8455                                                     MVT::i32)));
8456       Res = DAG.getNode(ISD::SUB, DL, VT,
8457                         DAG.getConstant(0, DL, MVT::i32), Res);
8458
8459     } else
8460       return SDValue();
8461   }
8462
8463   if (ShiftAmt != 0)
8464     Res = DAG.getNode(ISD::SHL, DL, VT,
8465                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8466
8467   // Do not add new nodes to DAG combiner worklist.
8468   DCI.CombineTo(N, Res, false);
8469   return SDValue();
8470 }
8471
8472 static SDValue PerformANDCombine(SDNode *N,
8473                                  TargetLowering::DAGCombinerInfo &DCI,
8474                                  const ARMSubtarget *Subtarget) {
8475
8476   // Attempt to use immediate-form VBIC
8477   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8478   SDLoc dl(N);
8479   EVT VT = N->getValueType(0);
8480   SelectionDAG &DAG = DCI.DAG;
8481
8482   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8483     return SDValue();
8484
8485   APInt SplatBits, SplatUndef;
8486   unsigned SplatBitSize;
8487   bool HasAnyUndefs;
8488   if (BVN &&
8489       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8490     if (SplatBitSize <= 64) {
8491       EVT VbicVT;
8492       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8493                                       SplatUndef.getZExtValue(), SplatBitSize,
8494                                       DAG, dl, VbicVT, VT.is128BitVector(),
8495                                       OtherModImm);
8496       if (Val.getNode()) {
8497         SDValue Input =
8498           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8499         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8500         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8501       }
8502     }
8503   }
8504
8505   if (!Subtarget->isThumb1Only()) {
8506     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8507     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8508     if (Result.getNode())
8509       return Result;
8510   }
8511
8512   return SDValue();
8513 }
8514
8515 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8516 static SDValue PerformORCombine(SDNode *N,
8517                                 TargetLowering::DAGCombinerInfo &DCI,
8518                                 const ARMSubtarget *Subtarget) {
8519   // Attempt to use immediate-form VORR
8520   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8521   SDLoc dl(N);
8522   EVT VT = N->getValueType(0);
8523   SelectionDAG &DAG = DCI.DAG;
8524
8525   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8526     return SDValue();
8527
8528   APInt SplatBits, SplatUndef;
8529   unsigned SplatBitSize;
8530   bool HasAnyUndefs;
8531   if (BVN && Subtarget->hasNEON() &&
8532       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8533     if (SplatBitSize <= 64) {
8534       EVT VorrVT;
8535       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8536                                       SplatUndef.getZExtValue(), SplatBitSize,
8537                                       DAG, dl, VorrVT, VT.is128BitVector(),
8538                                       OtherModImm);
8539       if (Val.getNode()) {
8540         SDValue Input =
8541           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8542         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8543         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8544       }
8545     }
8546   }
8547
8548   if (!Subtarget->isThumb1Only()) {
8549     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8550     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8551     if (Result.getNode())
8552       return Result;
8553   }
8554
8555   // The code below optimizes (or (and X, Y), Z).
8556   // The AND operand needs to have a single user to make these optimizations
8557   // profitable.
8558   SDValue N0 = N->getOperand(0);
8559   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8560     return SDValue();
8561   SDValue N1 = N->getOperand(1);
8562
8563   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8564   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8565       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8566     APInt SplatUndef;
8567     unsigned SplatBitSize;
8568     bool HasAnyUndefs;
8569
8570     APInt SplatBits0, SplatBits1;
8571     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8572     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8573     // Ensure that the second operand of both ands are constants
8574     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8575                                       HasAnyUndefs) && !HasAnyUndefs) {
8576         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8577                                           HasAnyUndefs) && !HasAnyUndefs) {
8578             // Ensure that the bit width of the constants are the same and that
8579             // the splat arguments are logical inverses as per the pattern we
8580             // are trying to simplify.
8581             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8582                 SplatBits0 == ~SplatBits1) {
8583                 // Canonicalize the vector type to make instruction selection
8584                 // simpler.
8585                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8586                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8587                                              N0->getOperand(1),
8588                                              N0->getOperand(0),
8589                                              N1->getOperand(0));
8590                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8591             }
8592         }
8593     }
8594   }
8595
8596   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8597   // reasonable.
8598
8599   // BFI is only available on V6T2+
8600   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8601     return SDValue();
8602
8603   SDLoc DL(N);
8604   // 1) or (and A, mask), val => ARMbfi A, val, mask
8605   //      iff (val & mask) == val
8606   //
8607   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8608   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8609   //          && mask == ~mask2
8610   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8611   //          && ~mask == mask2
8612   //  (i.e., copy a bitfield value into another bitfield of the same width)
8613
8614   if (VT != MVT::i32)
8615     return SDValue();
8616
8617   SDValue N00 = N0.getOperand(0);
8618
8619   // The value and the mask need to be constants so we can verify this is
8620   // actually a bitfield set. If the mask is 0xffff, we can do better
8621   // via a movt instruction, so don't use BFI in that case.
8622   SDValue MaskOp = N0.getOperand(1);
8623   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8624   if (!MaskC)
8625     return SDValue();
8626   unsigned Mask = MaskC->getZExtValue();
8627   if (Mask == 0xffff)
8628     return SDValue();
8629   SDValue Res;
8630   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8631   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8632   if (N1C) {
8633     unsigned Val = N1C->getZExtValue();
8634     if ((Val & ~Mask) != Val)
8635       return SDValue();
8636
8637     if (ARM::isBitFieldInvertedMask(Mask)) {
8638       Val >>= countTrailingZeros(~Mask);
8639
8640       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8641                         DAG.getConstant(Val, DL, MVT::i32),
8642                         DAG.getConstant(Mask, DL, MVT::i32));
8643
8644       // Do not add new nodes to DAG combiner worklist.
8645       DCI.CombineTo(N, Res, false);
8646       return SDValue();
8647     }
8648   } else if (N1.getOpcode() == ISD::AND) {
8649     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8650     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8651     if (!N11C)
8652       return SDValue();
8653     unsigned Mask2 = N11C->getZExtValue();
8654
8655     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8656     // as is to match.
8657     if (ARM::isBitFieldInvertedMask(Mask) &&
8658         (Mask == ~Mask2)) {
8659       // The pack halfword instruction works better for masks that fit it,
8660       // so use that when it's available.
8661       if (Subtarget->hasT2ExtractPack() &&
8662           (Mask == 0xffff || Mask == 0xffff0000))
8663         return SDValue();
8664       // 2a
8665       unsigned amt = countTrailingZeros(Mask2);
8666       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8667                         DAG.getConstant(amt, DL, MVT::i32));
8668       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8669                         DAG.getConstant(Mask, DL, MVT::i32));
8670       // Do not add new nodes to DAG combiner worklist.
8671       DCI.CombineTo(N, Res, false);
8672       return SDValue();
8673     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8674                (~Mask == Mask2)) {
8675       // The pack halfword instruction works better for masks that fit it,
8676       // so use that when it's available.
8677       if (Subtarget->hasT2ExtractPack() &&
8678           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8679         return SDValue();
8680       // 2b
8681       unsigned lsb = countTrailingZeros(Mask);
8682       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8683                         DAG.getConstant(lsb, DL, MVT::i32));
8684       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8685                         DAG.getConstant(Mask2, DL, MVT::i32));
8686       // Do not add new nodes to DAG combiner worklist.
8687       DCI.CombineTo(N, Res, false);
8688       return SDValue();
8689     }
8690   }
8691
8692   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8693       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8694       ARM::isBitFieldInvertedMask(~Mask)) {
8695     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8696     // where lsb(mask) == #shamt and masked bits of B are known zero.
8697     SDValue ShAmt = N00.getOperand(1);
8698     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8699     unsigned LSB = countTrailingZeros(Mask);
8700     if (ShAmtC != LSB)
8701       return SDValue();
8702
8703     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8704                       DAG.getConstant(~Mask, DL, MVT::i32));
8705
8706     // Do not add new nodes to DAG combiner worklist.
8707     DCI.CombineTo(N, Res, false);
8708   }
8709
8710   return SDValue();
8711 }
8712
8713 static SDValue PerformXORCombine(SDNode *N,
8714                                  TargetLowering::DAGCombinerInfo &DCI,
8715                                  const ARMSubtarget *Subtarget) {
8716   EVT VT = N->getValueType(0);
8717   SelectionDAG &DAG = DCI.DAG;
8718
8719   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8720     return SDValue();
8721
8722   if (!Subtarget->isThumb1Only()) {
8723     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8724     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8725     if (Result.getNode())
8726       return Result;
8727   }
8728
8729   return SDValue();
8730 }
8731
8732 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8733 /// the bits being cleared by the AND are not demanded by the BFI.
8734 static SDValue PerformBFICombine(SDNode *N,
8735                                  TargetLowering::DAGCombinerInfo &DCI) {
8736   SDValue N1 = N->getOperand(1);
8737   if (N1.getOpcode() == ISD::AND) {
8738     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8739     if (!N11C)
8740       return SDValue();
8741     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8742     unsigned LSB = countTrailingZeros(~InvMask);
8743     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8744     assert(Width <
8745                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8746            "undefined behavior");
8747     unsigned Mask = (1u << Width) - 1;
8748     unsigned Mask2 = N11C->getZExtValue();
8749     if ((Mask & (~Mask2)) == 0)
8750       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8751                              N->getOperand(0), N1.getOperand(0),
8752                              N->getOperand(2));
8753   }
8754   return SDValue();
8755 }
8756
8757 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8758 /// ARMISD::VMOVRRD.
8759 static SDValue PerformVMOVRRDCombine(SDNode *N,
8760                                      TargetLowering::DAGCombinerInfo &DCI,
8761                                      const ARMSubtarget *Subtarget) {
8762   // vmovrrd(vmovdrr x, y) -> x,y
8763   SDValue InDouble = N->getOperand(0);
8764   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8765     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8766
8767   // vmovrrd(load f64) -> (load i32), (load i32)
8768   SDNode *InNode = InDouble.getNode();
8769   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8770       InNode->getValueType(0) == MVT::f64 &&
8771       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8772       !cast<LoadSDNode>(InNode)->isVolatile()) {
8773     // TODO: Should this be done for non-FrameIndex operands?
8774     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8775
8776     SelectionDAG &DAG = DCI.DAG;
8777     SDLoc DL(LD);
8778     SDValue BasePtr = LD->getBasePtr();
8779     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8780                                  LD->getPointerInfo(), LD->isVolatile(),
8781                                  LD->isNonTemporal(), LD->isInvariant(),
8782                                  LD->getAlignment());
8783
8784     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8785                                     DAG.getConstant(4, DL, MVT::i32));
8786     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8787                                  LD->getPointerInfo(), LD->isVolatile(),
8788                                  LD->isNonTemporal(), LD->isInvariant(),
8789                                  std::min(4U, LD->getAlignment() / 2));
8790
8791     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8792     if (DCI.DAG.getDataLayout().isBigEndian())
8793       std::swap (NewLD1, NewLD2);
8794     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8795     return Result;
8796   }
8797
8798   return SDValue();
8799 }
8800
8801 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8802 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8803 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8804   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8805   SDValue Op0 = N->getOperand(0);
8806   SDValue Op1 = N->getOperand(1);
8807   if (Op0.getOpcode() == ISD::BITCAST)
8808     Op0 = Op0.getOperand(0);
8809   if (Op1.getOpcode() == ISD::BITCAST)
8810     Op1 = Op1.getOperand(0);
8811   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8812       Op0.getNode() == Op1.getNode() &&
8813       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8814     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8815                        N->getValueType(0), Op0.getOperand(0));
8816   return SDValue();
8817 }
8818
8819 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8820 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8821 /// i64 vector to have f64 elements, since the value can then be loaded
8822 /// directly into a VFP register.
8823 static bool hasNormalLoadOperand(SDNode *N) {
8824   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8825   for (unsigned i = 0; i < NumElts; ++i) {
8826     SDNode *Elt = N->getOperand(i).getNode();
8827     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8828       return true;
8829   }
8830   return false;
8831 }
8832
8833 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8834 /// ISD::BUILD_VECTOR.
8835 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8836                                           TargetLowering::DAGCombinerInfo &DCI,
8837                                           const ARMSubtarget *Subtarget) {
8838   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8839   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8840   // into a pair of GPRs, which is fine when the value is used as a scalar,
8841   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8842   SelectionDAG &DAG = DCI.DAG;
8843   if (N->getNumOperands() == 2) {
8844     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8845     if (RV.getNode())
8846       return RV;
8847   }
8848
8849   // Load i64 elements as f64 values so that type legalization does not split
8850   // them up into i32 values.
8851   EVT VT = N->getValueType(0);
8852   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8853     return SDValue();
8854   SDLoc dl(N);
8855   SmallVector<SDValue, 8> Ops;
8856   unsigned NumElts = VT.getVectorNumElements();
8857   for (unsigned i = 0; i < NumElts; ++i) {
8858     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8859     Ops.push_back(V);
8860     // Make the DAGCombiner fold the bitcast.
8861     DCI.AddToWorklist(V.getNode());
8862   }
8863   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8864   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8865   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8866 }
8867
8868 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8869 static SDValue
8870 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8871   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8872   // At that time, we may have inserted bitcasts from integer to float.
8873   // If these bitcasts have survived DAGCombine, change the lowering of this
8874   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8875   // force to use floating point types.
8876
8877   // Make sure we can change the type of the vector.
8878   // This is possible iff:
8879   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8880   //    1.1. Vector is used only once.
8881   //    1.2. Use is a bit convert to an integer type.
8882   // 2. The size of its operands are 32-bits (64-bits are not legal).
8883   EVT VT = N->getValueType(0);
8884   EVT EltVT = VT.getVectorElementType();
8885
8886   // Check 1.1. and 2.
8887   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8888     return SDValue();
8889
8890   // By construction, the input type must be float.
8891   assert(EltVT == MVT::f32 && "Unexpected type!");
8892
8893   // Check 1.2.
8894   SDNode *Use = *N->use_begin();
8895   if (Use->getOpcode() != ISD::BITCAST ||
8896       Use->getValueType(0).isFloatingPoint())
8897     return SDValue();
8898
8899   // Check profitability.
8900   // Model is, if more than half of the relevant operands are bitcast from
8901   // i32, turn the build_vector into a sequence of insert_vector_elt.
8902   // Relevant operands are everything that is not statically
8903   // (i.e., at compile time) bitcasted.
8904   unsigned NumOfBitCastedElts = 0;
8905   unsigned NumElts = VT.getVectorNumElements();
8906   unsigned NumOfRelevantElts = NumElts;
8907   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8908     SDValue Elt = N->getOperand(Idx);
8909     if (Elt->getOpcode() == ISD::BITCAST) {
8910       // Assume only bit cast to i32 will go away.
8911       if (Elt->getOperand(0).getValueType() == MVT::i32)
8912         ++NumOfBitCastedElts;
8913     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8914       // Constants are statically casted, thus do not count them as
8915       // relevant operands.
8916       --NumOfRelevantElts;
8917   }
8918
8919   // Check if more than half of the elements require a non-free bitcast.
8920   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8921     return SDValue();
8922
8923   SelectionDAG &DAG = DCI.DAG;
8924   // Create the new vector type.
8925   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8926   // Check if the type is legal.
8927   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8928   if (!TLI.isTypeLegal(VecVT))
8929     return SDValue();
8930
8931   // Combine:
8932   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8933   // => BITCAST INSERT_VECTOR_ELT
8934   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8935   //                      (BITCAST EN), N.
8936   SDValue Vec = DAG.getUNDEF(VecVT);
8937   SDLoc dl(N);
8938   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8939     SDValue V = N->getOperand(Idx);
8940     if (V.getOpcode() == ISD::UNDEF)
8941       continue;
8942     if (V.getOpcode() == ISD::BITCAST &&
8943         V->getOperand(0).getValueType() == MVT::i32)
8944       // Fold obvious case.
8945       V = V.getOperand(0);
8946     else {
8947       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8948       // Make the DAGCombiner fold the bitcasts.
8949       DCI.AddToWorklist(V.getNode());
8950     }
8951     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
8952     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8953   }
8954   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8955   // Make the DAGCombiner fold the bitcasts.
8956   DCI.AddToWorklist(Vec.getNode());
8957   return Vec;
8958 }
8959
8960 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8961 /// ISD::INSERT_VECTOR_ELT.
8962 static SDValue PerformInsertEltCombine(SDNode *N,
8963                                        TargetLowering::DAGCombinerInfo &DCI) {
8964   // Bitcast an i64 load inserted into a vector to f64.
8965   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8966   EVT VT = N->getValueType(0);
8967   SDNode *Elt = N->getOperand(1).getNode();
8968   if (VT.getVectorElementType() != MVT::i64 ||
8969       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8970     return SDValue();
8971
8972   SelectionDAG &DAG = DCI.DAG;
8973   SDLoc dl(N);
8974   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8975                                  VT.getVectorNumElements());
8976   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8977   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8978   // Make the DAGCombiner fold the bitcasts.
8979   DCI.AddToWorklist(Vec.getNode());
8980   DCI.AddToWorklist(V.getNode());
8981   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8982                                Vec, V, N->getOperand(2));
8983   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8984 }
8985
8986 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8987 /// ISD::VECTOR_SHUFFLE.
8988 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8989   // The LLVM shufflevector instruction does not require the shuffle mask
8990   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8991   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8992   // operands do not match the mask length, they are extended by concatenating
8993   // them with undef vectors.  That is probably the right thing for other
8994   // targets, but for NEON it is better to concatenate two double-register
8995   // size vector operands into a single quad-register size vector.  Do that
8996   // transformation here:
8997   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8998   //   shuffle(concat(v1, v2), undef)
8999   SDValue Op0 = N->getOperand(0);
9000   SDValue Op1 = N->getOperand(1);
9001   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9002       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9003       Op0.getNumOperands() != 2 ||
9004       Op1.getNumOperands() != 2)
9005     return SDValue();
9006   SDValue Concat0Op1 = Op0.getOperand(1);
9007   SDValue Concat1Op1 = Op1.getOperand(1);
9008   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9009       Concat1Op1.getOpcode() != ISD::UNDEF)
9010     return SDValue();
9011   // Skip the transformation if any of the types are illegal.
9012   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9013   EVT VT = N->getValueType(0);
9014   if (!TLI.isTypeLegal(VT) ||
9015       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9016       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9017     return SDValue();
9018
9019   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9020                                   Op0.getOperand(0), Op1.getOperand(0));
9021   // Translate the shuffle mask.
9022   SmallVector<int, 16> NewMask;
9023   unsigned NumElts = VT.getVectorNumElements();
9024   unsigned HalfElts = NumElts/2;
9025   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9026   for (unsigned n = 0; n < NumElts; ++n) {
9027     int MaskElt = SVN->getMaskElt(n);
9028     int NewElt = -1;
9029     if (MaskElt < (int)HalfElts)
9030       NewElt = MaskElt;
9031     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9032       NewElt = HalfElts + MaskElt - NumElts;
9033     NewMask.push_back(NewElt);
9034   }
9035   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9036                               DAG.getUNDEF(VT), NewMask.data());
9037 }
9038
9039 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9040 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9041 /// base address updates.
9042 /// For generic load/stores, the memory type is assumed to be a vector.
9043 /// The caller is assumed to have checked legality.
9044 static SDValue CombineBaseUpdate(SDNode *N,
9045                                  TargetLowering::DAGCombinerInfo &DCI) {
9046   SelectionDAG &DAG = DCI.DAG;
9047   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9048                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9049   const bool isStore = N->getOpcode() == ISD::STORE;
9050   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9051   SDValue Addr = N->getOperand(AddrOpIdx);
9052   MemSDNode *MemN = cast<MemSDNode>(N);
9053   SDLoc dl(N);
9054
9055   // Search for a use of the address operand that is an increment.
9056   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9057          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9058     SDNode *User = *UI;
9059     if (User->getOpcode() != ISD::ADD ||
9060         UI.getUse().getResNo() != Addr.getResNo())
9061       continue;
9062
9063     // Check that the add is independent of the load/store.  Otherwise, folding
9064     // it would create a cycle.
9065     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9066       continue;
9067
9068     // Find the new opcode for the updating load/store.
9069     bool isLoadOp = true;
9070     bool isLaneOp = false;
9071     unsigned NewOpc = 0;
9072     unsigned NumVecs = 0;
9073     if (isIntrinsic) {
9074       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9075       switch (IntNo) {
9076       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9077       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9078         NumVecs = 1; break;
9079       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9080         NumVecs = 2; break;
9081       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9082         NumVecs = 3; break;
9083       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9084         NumVecs = 4; break;
9085       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9086         NumVecs = 2; isLaneOp = true; break;
9087       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9088         NumVecs = 3; isLaneOp = true; break;
9089       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9090         NumVecs = 4; isLaneOp = true; break;
9091       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9092         NumVecs = 1; isLoadOp = false; break;
9093       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9094         NumVecs = 2; isLoadOp = false; break;
9095       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9096         NumVecs = 3; isLoadOp = false; break;
9097       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9098         NumVecs = 4; isLoadOp = false; break;
9099       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9100         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9101       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9102         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9103       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9104         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9105       }
9106     } else {
9107       isLaneOp = true;
9108       switch (N->getOpcode()) {
9109       default: llvm_unreachable("unexpected opcode for Neon base update");
9110       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9111       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9112       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9113       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9114         NumVecs = 1; isLaneOp = false; break;
9115       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9116         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9117       }
9118     }
9119
9120     // Find the size of memory referenced by the load/store.
9121     EVT VecTy;
9122     if (isLoadOp) {
9123       VecTy = N->getValueType(0);
9124     } else if (isIntrinsic) {
9125       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9126     } else {
9127       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9128       VecTy = N->getOperand(1).getValueType();
9129     }
9130
9131     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9132     if (isLaneOp)
9133       NumBytes /= VecTy.getVectorNumElements();
9134
9135     // If the increment is a constant, it must match the memory ref size.
9136     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9137     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9138       uint64_t IncVal = CInc->getZExtValue();
9139       if (IncVal != NumBytes)
9140         continue;
9141     } else if (NumBytes >= 3 * 16) {
9142       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9143       // separate instructions that make it harder to use a non-constant update.
9144       continue;
9145     }
9146
9147     // OK, we found an ADD we can fold into the base update.
9148     // Now, create a _UPD node, taking care of not breaking alignment.
9149
9150     EVT AlignedVecTy = VecTy;
9151     unsigned Alignment = MemN->getAlignment();
9152
9153     // If this is a less-than-standard-aligned load/store, change the type to
9154     // match the standard alignment.
9155     // The alignment is overlooked when selecting _UPD variants; and it's
9156     // easier to introduce bitcasts here than fix that.
9157     // There are 3 ways to get to this base-update combine:
9158     // - intrinsics: they are assumed to be properly aligned (to the standard
9159     //   alignment of the memory type), so we don't need to do anything.
9160     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9161     //   intrinsics, so, likewise, there's nothing to do.
9162     // - generic load/store instructions: the alignment is specified as an
9163     //   explicit operand, rather than implicitly as the standard alignment
9164     //   of the memory type (like the intrisics).  We need to change the
9165     //   memory type to match the explicit alignment.  That way, we don't
9166     //   generate non-standard-aligned ARMISD::VLDx nodes.
9167     if (isa<LSBaseSDNode>(N)) {
9168       if (Alignment == 0)
9169         Alignment = 1;
9170       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9171         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9172         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9173         assert(!isLaneOp && "Unexpected generic load/store lane.");
9174         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9175         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9176       }
9177       // Don't set an explicit alignment on regular load/stores that we want
9178       // to transform to VLD/VST 1_UPD nodes.
9179       // This matches the behavior of regular load/stores, which only get an
9180       // explicit alignment if the MMO alignment is larger than the standard
9181       // alignment of the memory type.
9182       // Intrinsics, however, always get an explicit alignment, set to the
9183       // alignment of the MMO.
9184       Alignment = 1;
9185     }
9186
9187     // Create the new updating load/store node.
9188     // First, create an SDVTList for the new updating node's results.
9189     EVT Tys[6];
9190     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9191     unsigned n;
9192     for (n = 0; n < NumResultVecs; ++n)
9193       Tys[n] = AlignedVecTy;
9194     Tys[n++] = MVT::i32;
9195     Tys[n] = MVT::Other;
9196     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9197
9198     // Then, gather the new node's operands.
9199     SmallVector<SDValue, 8> Ops;
9200     Ops.push_back(N->getOperand(0)); // incoming chain
9201     Ops.push_back(N->getOperand(AddrOpIdx));
9202     Ops.push_back(Inc);
9203
9204     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9205       // Try to match the intrinsic's signature
9206       Ops.push_back(StN->getValue());
9207     } else {
9208       // Loads (and of course intrinsics) match the intrinsics' signature,
9209       // so just add all but the alignment operand.
9210       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9211         Ops.push_back(N->getOperand(i));
9212     }
9213
9214     // For all node types, the alignment operand is always the last one.
9215     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9216
9217     // If this is a non-standard-aligned STORE, the penultimate operand is the
9218     // stored value.  Bitcast it to the aligned type.
9219     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9220       SDValue &StVal = Ops[Ops.size()-2];
9221       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9222     }
9223
9224     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9225                                            Ops, AlignedVecTy,
9226                                            MemN->getMemOperand());
9227
9228     // Update the uses.
9229     SmallVector<SDValue, 5> NewResults;
9230     for (unsigned i = 0; i < NumResultVecs; ++i)
9231       NewResults.push_back(SDValue(UpdN.getNode(), i));
9232
9233     // If this is an non-standard-aligned LOAD, the first result is the loaded
9234     // value.  Bitcast it to the expected result type.
9235     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9236       SDValue &LdVal = NewResults[0];
9237       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9238     }
9239
9240     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9241     DCI.CombineTo(N, NewResults);
9242     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9243
9244     break;
9245   }
9246   return SDValue();
9247 }
9248
9249 static SDValue PerformVLDCombine(SDNode *N,
9250                                  TargetLowering::DAGCombinerInfo &DCI) {
9251   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9252     return SDValue();
9253
9254   return CombineBaseUpdate(N, DCI);
9255 }
9256
9257 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9258 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9259 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9260 /// return true.
9261 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9262   SelectionDAG &DAG = DCI.DAG;
9263   EVT VT = N->getValueType(0);
9264   // vldN-dup instructions only support 64-bit vectors for N > 1.
9265   if (!VT.is64BitVector())
9266     return false;
9267
9268   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9269   SDNode *VLD = N->getOperand(0).getNode();
9270   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9271     return false;
9272   unsigned NumVecs = 0;
9273   unsigned NewOpc = 0;
9274   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9275   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9276     NumVecs = 2;
9277     NewOpc = ARMISD::VLD2DUP;
9278   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9279     NumVecs = 3;
9280     NewOpc = ARMISD::VLD3DUP;
9281   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9282     NumVecs = 4;
9283     NewOpc = ARMISD::VLD4DUP;
9284   } else {
9285     return false;
9286   }
9287
9288   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9289   // numbers match the load.
9290   unsigned VLDLaneNo =
9291     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9292   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9293        UI != UE; ++UI) {
9294     // Ignore uses of the chain result.
9295     if (UI.getUse().getResNo() == NumVecs)
9296       continue;
9297     SDNode *User = *UI;
9298     if (User->getOpcode() != ARMISD::VDUPLANE ||
9299         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9300       return false;
9301   }
9302
9303   // Create the vldN-dup node.
9304   EVT Tys[5];
9305   unsigned n;
9306   for (n = 0; n < NumVecs; ++n)
9307     Tys[n] = VT;
9308   Tys[n] = MVT::Other;
9309   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9310   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9311   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9312   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9313                                            Ops, VLDMemInt->getMemoryVT(),
9314                                            VLDMemInt->getMemOperand());
9315
9316   // Update the uses.
9317   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9318        UI != UE; ++UI) {
9319     unsigned ResNo = UI.getUse().getResNo();
9320     // Ignore uses of the chain result.
9321     if (ResNo == NumVecs)
9322       continue;
9323     SDNode *User = *UI;
9324     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9325   }
9326
9327   // Now the vldN-lane intrinsic is dead except for its chain result.
9328   // Update uses of the chain.
9329   std::vector<SDValue> VLDDupResults;
9330   for (unsigned n = 0; n < NumVecs; ++n)
9331     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9332   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9333   DCI.CombineTo(VLD, VLDDupResults);
9334
9335   return true;
9336 }
9337
9338 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9339 /// ARMISD::VDUPLANE.
9340 static SDValue PerformVDUPLANECombine(SDNode *N,
9341                                       TargetLowering::DAGCombinerInfo &DCI) {
9342   SDValue Op = N->getOperand(0);
9343
9344   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9345   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9346   if (CombineVLDDUP(N, DCI))
9347     return SDValue(N, 0);
9348
9349   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9350   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9351   while (Op.getOpcode() == ISD::BITCAST)
9352     Op = Op.getOperand(0);
9353   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9354     return SDValue();
9355
9356   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9357   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9358   // The canonical VMOV for a zero vector uses a 32-bit element size.
9359   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9360   unsigned EltBits;
9361   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9362     EltSize = 8;
9363   EVT VT = N->getValueType(0);
9364   if (EltSize > VT.getVectorElementType().getSizeInBits())
9365     return SDValue();
9366
9367   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9368 }
9369
9370 static SDValue PerformLOADCombine(SDNode *N,
9371                                   TargetLowering::DAGCombinerInfo &DCI) {
9372   EVT VT = N->getValueType(0);
9373
9374   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9375   if (ISD::isNormalLoad(N) && VT.isVector() &&
9376       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9377     return CombineBaseUpdate(N, DCI);
9378
9379   return SDValue();
9380 }
9381
9382 /// PerformSTORECombine - Target-specific dag combine xforms for
9383 /// ISD::STORE.
9384 static SDValue PerformSTORECombine(SDNode *N,
9385                                    TargetLowering::DAGCombinerInfo &DCI) {
9386   StoreSDNode *St = cast<StoreSDNode>(N);
9387   if (St->isVolatile())
9388     return SDValue();
9389
9390   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9391   // pack all of the elements in one place.  Next, store to memory in fewer
9392   // chunks.
9393   SDValue StVal = St->getValue();
9394   EVT VT = StVal.getValueType();
9395   if (St->isTruncatingStore() && VT.isVector()) {
9396     SelectionDAG &DAG = DCI.DAG;
9397     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9398     EVT StVT = St->getMemoryVT();
9399     unsigned NumElems = VT.getVectorNumElements();
9400     assert(StVT != VT && "Cannot truncate to the same type");
9401     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9402     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9403
9404     // From, To sizes and ElemCount must be pow of two
9405     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9406
9407     // We are going to use the original vector elt for storing.
9408     // Accumulated smaller vector elements must be a multiple of the store size.
9409     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9410
9411     unsigned SizeRatio  = FromEltSz / ToEltSz;
9412     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9413
9414     // Create a type on which we perform the shuffle.
9415     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9416                                      NumElems*SizeRatio);
9417     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9418
9419     SDLoc DL(St);
9420     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9421     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9422     for (unsigned i = 0; i < NumElems; ++i)
9423       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9424                           ? (i + 1) * SizeRatio - 1
9425                           : i * SizeRatio;
9426
9427     // Can't shuffle using an illegal type.
9428     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9429
9430     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9431                                 DAG.getUNDEF(WideVec.getValueType()),
9432                                 ShuffleVec.data());
9433     // At this point all of the data is stored at the bottom of the
9434     // register. We now need to save it to mem.
9435
9436     // Find the largest store unit
9437     MVT StoreType = MVT::i8;
9438     for (MVT Tp : MVT::integer_valuetypes()) {
9439       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9440         StoreType = Tp;
9441     }
9442     // Didn't find a legal store type.
9443     if (!TLI.isTypeLegal(StoreType))
9444       return SDValue();
9445
9446     // Bitcast the original vector into a vector of store-size units
9447     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9448             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9449     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9450     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9451     SmallVector<SDValue, 8> Chains;
9452     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9453                                         TLI.getPointerTy(DAG.getDataLayout()));
9454     SDValue BasePtr = St->getBasePtr();
9455
9456     // Perform one or more big stores into memory.
9457     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9458     for (unsigned I = 0; I < E; I++) {
9459       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9460                                    StoreType, ShuffWide,
9461                                    DAG.getIntPtrConstant(I, DL));
9462       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9463                                 St->getPointerInfo(), St->isVolatile(),
9464                                 St->isNonTemporal(), St->getAlignment());
9465       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9466                             Increment);
9467       Chains.push_back(Ch);
9468     }
9469     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9470   }
9471
9472   if (!ISD::isNormalStore(St))
9473     return SDValue();
9474
9475   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9476   // ARM stores of arguments in the same cache line.
9477   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9478       StVal.getNode()->hasOneUse()) {
9479     SelectionDAG  &DAG = DCI.DAG;
9480     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9481     SDLoc DL(St);
9482     SDValue BasePtr = St->getBasePtr();
9483     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9484                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9485                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9486                                   St->isNonTemporal(), St->getAlignment());
9487
9488     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9489                                     DAG.getConstant(4, DL, MVT::i32));
9490     return DAG.getStore(NewST1.getValue(0), DL,
9491                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9492                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9493                         St->isNonTemporal(),
9494                         std::min(4U, St->getAlignment() / 2));
9495   }
9496
9497   if (StVal.getValueType() == MVT::i64 &&
9498       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9499
9500     // Bitcast an i64 store extracted from a vector to f64.
9501     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9502     SelectionDAG &DAG = DCI.DAG;
9503     SDLoc dl(StVal);
9504     SDValue IntVec = StVal.getOperand(0);
9505     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9506                                    IntVec.getValueType().getVectorNumElements());
9507     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9508     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9509                                  Vec, StVal.getOperand(1));
9510     dl = SDLoc(N);
9511     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9512     // Make the DAGCombiner fold the bitcasts.
9513     DCI.AddToWorklist(Vec.getNode());
9514     DCI.AddToWorklist(ExtElt.getNode());
9515     DCI.AddToWorklist(V.getNode());
9516     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9517                         St->getPointerInfo(), St->isVolatile(),
9518                         St->isNonTemporal(), St->getAlignment(),
9519                         St->getAAInfo());
9520   }
9521
9522   // If this is a legal vector store, try to combine it into a VST1_UPD.
9523   if (ISD::isNormalStore(N) && VT.isVector() &&
9524       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9525     return CombineBaseUpdate(N, DCI);
9526
9527   return SDValue();
9528 }
9529
9530 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9531 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9532 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9533 {
9534   integerPart cN;
9535   integerPart c0 = 0;
9536   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9537        I != E; I++) {
9538     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9539     if (!C)
9540       return false;
9541
9542     bool isExact;
9543     APFloat APF = C->getValueAPF();
9544     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9545         != APFloat::opOK || !isExact)
9546       return false;
9547
9548     c0 = (I == 0) ? cN : c0;
9549     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9550       return false;
9551   }
9552   C = c0;
9553   return true;
9554 }
9555
9556 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9557 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9558 /// when the VMUL has a constant operand that is a power of 2.
9559 ///
9560 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9561 ///  vmul.f32        d16, d17, d16
9562 ///  vcvt.s32.f32    d16, d16
9563 /// becomes:
9564 ///  vcvt.s32.f32    d16, d16, #3
9565 static SDValue PerformVCVTCombine(SDNode *N,
9566                                   TargetLowering::DAGCombinerInfo &DCI,
9567                                   const ARMSubtarget *Subtarget) {
9568   SelectionDAG &DAG = DCI.DAG;
9569   SDValue Op = N->getOperand(0);
9570
9571   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9572       Op.getOpcode() != ISD::FMUL)
9573     return SDValue();
9574
9575   uint64_t C;
9576   SDValue N0 = Op->getOperand(0);
9577   SDValue ConstVec = Op->getOperand(1);
9578   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9579
9580   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9581       !isConstVecPow2(ConstVec, isSigned, C))
9582     return SDValue();
9583
9584   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9585   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9586   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9587   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9588       NumLanes > 4) {
9589     // These instructions only exist converting from f32 to i32. We can handle
9590     // smaller integers by generating an extra truncate, but larger ones would
9591     // be lossy. We also can't handle more then 4 lanes, since these intructions
9592     // only support v2i32/v4i32 types.
9593     return SDValue();
9594   }
9595
9596   SDLoc dl(N);
9597   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9598     Intrinsic::arm_neon_vcvtfp2fxu;
9599   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9600                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9601                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9602                                  N0,
9603                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9604
9605   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9606     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9607
9608   return FixConv;
9609 }
9610
9611 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9612 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9613 /// when the VDIV has a constant operand that is a power of 2.
9614 ///
9615 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9616 ///  vcvt.f32.s32    d16, d16
9617 ///  vdiv.f32        d16, d17, d16
9618 /// becomes:
9619 ///  vcvt.f32.s32    d16, d16, #3
9620 static SDValue PerformVDIVCombine(SDNode *N,
9621                                   TargetLowering::DAGCombinerInfo &DCI,
9622                                   const ARMSubtarget *Subtarget) {
9623   SelectionDAG &DAG = DCI.DAG;
9624   SDValue Op = N->getOperand(0);
9625   unsigned OpOpcode = Op.getNode()->getOpcode();
9626
9627   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9628       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9629     return SDValue();
9630
9631   uint64_t C;
9632   SDValue ConstVec = N->getOperand(1);
9633   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9634
9635   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9636       !isConstVecPow2(ConstVec, isSigned, C))
9637     return SDValue();
9638
9639   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9640   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9641   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9642     // These instructions only exist converting from i32 to f32. We can handle
9643     // smaller integers by generating an extra extend, but larger ones would
9644     // be lossy.
9645     return SDValue();
9646   }
9647
9648   SDLoc dl(N);
9649   SDValue ConvInput = Op.getOperand(0);
9650   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9651   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9652     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9653                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9654                             ConvInput);
9655
9656   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9657     Intrinsic::arm_neon_vcvtfxu2fp;
9658   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9659                      Op.getValueType(),
9660                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9661                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9662 }
9663
9664 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9665 /// operand of a vector shift operation, where all the elements of the
9666 /// build_vector must have the same constant integer value.
9667 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9668   // Ignore bit_converts.
9669   while (Op.getOpcode() == ISD::BITCAST)
9670     Op = Op.getOperand(0);
9671   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9672   APInt SplatBits, SplatUndef;
9673   unsigned SplatBitSize;
9674   bool HasAnyUndefs;
9675   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9676                                       HasAnyUndefs, ElementBits) ||
9677       SplatBitSize > ElementBits)
9678     return false;
9679   Cnt = SplatBits.getSExtValue();
9680   return true;
9681 }
9682
9683 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9684 /// operand of a vector shift left operation.  That value must be in the range:
9685 ///   0 <= Value < ElementBits for a left shift; or
9686 ///   0 <= Value <= ElementBits for a long left shift.
9687 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9688   assert(VT.isVector() && "vector shift count is not a vector type");
9689   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9690   if (! getVShiftImm(Op, ElementBits, Cnt))
9691     return false;
9692   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9693 }
9694
9695 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9696 /// operand of a vector shift right operation.  For a shift opcode, the value
9697 /// is positive, but for an intrinsic the value count must be negative. The
9698 /// absolute value must be in the range:
9699 ///   1 <= |Value| <= ElementBits for a right shift; or
9700 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9701 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9702                          int64_t &Cnt) {
9703   assert(VT.isVector() && "vector shift count is not a vector type");
9704   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9705   if (! getVShiftImm(Op, ElementBits, Cnt))
9706     return false;
9707   if (isIntrinsic)
9708     Cnt = -Cnt;
9709   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9710 }
9711
9712 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9713 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9714   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9715   switch (IntNo) {
9716   default:
9717     // Don't do anything for most intrinsics.
9718     break;
9719
9720   // Vector shifts: check for immediate versions and lower them.
9721   // Note: This is done during DAG combining instead of DAG legalizing because
9722   // the build_vectors for 64-bit vector element shift counts are generally
9723   // not legal, and it is hard to see their values after they get legalized to
9724   // loads from a constant pool.
9725   case Intrinsic::arm_neon_vshifts:
9726   case Intrinsic::arm_neon_vshiftu:
9727   case Intrinsic::arm_neon_vrshifts:
9728   case Intrinsic::arm_neon_vrshiftu:
9729   case Intrinsic::arm_neon_vrshiftn:
9730   case Intrinsic::arm_neon_vqshifts:
9731   case Intrinsic::arm_neon_vqshiftu:
9732   case Intrinsic::arm_neon_vqshiftsu:
9733   case Intrinsic::arm_neon_vqshiftns:
9734   case Intrinsic::arm_neon_vqshiftnu:
9735   case Intrinsic::arm_neon_vqshiftnsu:
9736   case Intrinsic::arm_neon_vqrshiftns:
9737   case Intrinsic::arm_neon_vqrshiftnu:
9738   case Intrinsic::arm_neon_vqrshiftnsu: {
9739     EVT VT = N->getOperand(1).getValueType();
9740     int64_t Cnt;
9741     unsigned VShiftOpc = 0;
9742
9743     switch (IntNo) {
9744     case Intrinsic::arm_neon_vshifts:
9745     case Intrinsic::arm_neon_vshiftu:
9746       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9747         VShiftOpc = ARMISD::VSHL;
9748         break;
9749       }
9750       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9751         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9752                      ARMISD::VSHRs : ARMISD::VSHRu);
9753         break;
9754       }
9755       return SDValue();
9756
9757     case Intrinsic::arm_neon_vrshifts:
9758     case Intrinsic::arm_neon_vrshiftu:
9759       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9760         break;
9761       return SDValue();
9762
9763     case Intrinsic::arm_neon_vqshifts:
9764     case Intrinsic::arm_neon_vqshiftu:
9765       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9766         break;
9767       return SDValue();
9768
9769     case Intrinsic::arm_neon_vqshiftsu:
9770       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9771         break;
9772       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9773
9774     case Intrinsic::arm_neon_vrshiftn:
9775     case Intrinsic::arm_neon_vqshiftns:
9776     case Intrinsic::arm_neon_vqshiftnu:
9777     case Intrinsic::arm_neon_vqshiftnsu:
9778     case Intrinsic::arm_neon_vqrshiftns:
9779     case Intrinsic::arm_neon_vqrshiftnu:
9780     case Intrinsic::arm_neon_vqrshiftnsu:
9781       // Narrowing shifts require an immediate right shift.
9782       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9783         break;
9784       llvm_unreachable("invalid shift count for narrowing vector shift "
9785                        "intrinsic");
9786
9787     default:
9788       llvm_unreachable("unhandled vector shift");
9789     }
9790
9791     switch (IntNo) {
9792     case Intrinsic::arm_neon_vshifts:
9793     case Intrinsic::arm_neon_vshiftu:
9794       // Opcode already set above.
9795       break;
9796     case Intrinsic::arm_neon_vrshifts:
9797       VShiftOpc = ARMISD::VRSHRs; break;
9798     case Intrinsic::arm_neon_vrshiftu:
9799       VShiftOpc = ARMISD::VRSHRu; break;
9800     case Intrinsic::arm_neon_vrshiftn:
9801       VShiftOpc = ARMISD::VRSHRN; break;
9802     case Intrinsic::arm_neon_vqshifts:
9803       VShiftOpc = ARMISD::VQSHLs; break;
9804     case Intrinsic::arm_neon_vqshiftu:
9805       VShiftOpc = ARMISD::VQSHLu; break;
9806     case Intrinsic::arm_neon_vqshiftsu:
9807       VShiftOpc = ARMISD::VQSHLsu; break;
9808     case Intrinsic::arm_neon_vqshiftns:
9809       VShiftOpc = ARMISD::VQSHRNs; break;
9810     case Intrinsic::arm_neon_vqshiftnu:
9811       VShiftOpc = ARMISD::VQSHRNu; break;
9812     case Intrinsic::arm_neon_vqshiftnsu:
9813       VShiftOpc = ARMISD::VQSHRNsu; break;
9814     case Intrinsic::arm_neon_vqrshiftns:
9815       VShiftOpc = ARMISD::VQRSHRNs; break;
9816     case Intrinsic::arm_neon_vqrshiftnu:
9817       VShiftOpc = ARMISD::VQRSHRNu; break;
9818     case Intrinsic::arm_neon_vqrshiftnsu:
9819       VShiftOpc = ARMISD::VQRSHRNsu; break;
9820     }
9821
9822     SDLoc dl(N);
9823     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9824                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9825   }
9826
9827   case Intrinsic::arm_neon_vshiftins: {
9828     EVT VT = N->getOperand(1).getValueType();
9829     int64_t Cnt;
9830     unsigned VShiftOpc = 0;
9831
9832     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9833       VShiftOpc = ARMISD::VSLI;
9834     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9835       VShiftOpc = ARMISD::VSRI;
9836     else {
9837       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9838     }
9839
9840     SDLoc dl(N);
9841     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9842                        N->getOperand(1), N->getOperand(2),
9843                        DAG.getConstant(Cnt, dl, MVT::i32));
9844   }
9845
9846   case Intrinsic::arm_neon_vqrshifts:
9847   case Intrinsic::arm_neon_vqrshiftu:
9848     // No immediate versions of these to check for.
9849     break;
9850   }
9851
9852   return SDValue();
9853 }
9854
9855 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9856 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9857 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9858 /// vector element shift counts are generally not legal, and it is hard to see
9859 /// their values after they get legalized to loads from a constant pool.
9860 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9861                                    const ARMSubtarget *ST) {
9862   EVT VT = N->getValueType(0);
9863   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9864     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9865     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9866     SDValue N1 = N->getOperand(1);
9867     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9868       SDValue N0 = N->getOperand(0);
9869       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9870           DAG.MaskedValueIsZero(N0.getOperand(0),
9871                                 APInt::getHighBitsSet(32, 16)))
9872         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9873     }
9874   }
9875
9876   // Nothing to be done for scalar shifts.
9877   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9878   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9879     return SDValue();
9880
9881   assert(ST->hasNEON() && "unexpected vector shift");
9882   int64_t Cnt;
9883
9884   switch (N->getOpcode()) {
9885   default: llvm_unreachable("unexpected shift opcode");
9886
9887   case ISD::SHL:
9888     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
9889       SDLoc dl(N);
9890       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
9891                          DAG.getConstant(Cnt, dl, MVT::i32));
9892     }
9893     break;
9894
9895   case ISD::SRA:
9896   case ISD::SRL:
9897     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9898       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9899                             ARMISD::VSHRs : ARMISD::VSHRu);
9900       SDLoc dl(N);
9901       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
9902                          DAG.getConstant(Cnt, dl, MVT::i32));
9903     }
9904   }
9905   return SDValue();
9906 }
9907
9908 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9909 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9910 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9911                                     const ARMSubtarget *ST) {
9912   SDValue N0 = N->getOperand(0);
9913
9914   // Check for sign- and zero-extensions of vector extract operations of 8-
9915   // and 16-bit vector elements.  NEON supports these directly.  They are
9916   // handled during DAG combining because type legalization will promote them
9917   // to 32-bit types and it is messy to recognize the operations after that.
9918   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9919     SDValue Vec = N0.getOperand(0);
9920     SDValue Lane = N0.getOperand(1);
9921     EVT VT = N->getValueType(0);
9922     EVT EltVT = N0.getValueType();
9923     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9924
9925     if (VT == MVT::i32 &&
9926         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9927         TLI.isTypeLegal(Vec.getValueType()) &&
9928         isa<ConstantSDNode>(Lane)) {
9929
9930       unsigned Opc = 0;
9931       switch (N->getOpcode()) {
9932       default: llvm_unreachable("unexpected opcode");
9933       case ISD::SIGN_EXTEND:
9934         Opc = ARMISD::VGETLANEs;
9935         break;
9936       case ISD::ZERO_EXTEND:
9937       case ISD::ANY_EXTEND:
9938         Opc = ARMISD::VGETLANEu;
9939         break;
9940       }
9941       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9942     }
9943   }
9944
9945   return SDValue();
9946 }
9947
9948 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9949 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9950 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9951                                        const ARMSubtarget *ST) {
9952   // If the target supports NEON, try to use vmax/vmin instructions for f32
9953   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9954   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9955   // a NaN; only do the transformation when it matches that behavior.
9956
9957   // For now only do this when using NEON for FP operations; if using VFP, it
9958   // is not obvious that the benefit outweighs the cost of switching to the
9959   // NEON pipeline.
9960   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9961       N->getValueType(0) != MVT::f32)
9962     return SDValue();
9963
9964   SDValue CondLHS = N->getOperand(0);
9965   SDValue CondRHS = N->getOperand(1);
9966   SDValue LHS = N->getOperand(2);
9967   SDValue RHS = N->getOperand(3);
9968   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9969
9970   unsigned Opcode = 0;
9971   bool IsReversed;
9972   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9973     IsReversed = false; // x CC y ? x : y
9974   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9975     IsReversed = true ; // x CC y ? y : x
9976   } else {
9977     return SDValue();
9978   }
9979
9980   bool IsUnordered;
9981   switch (CC) {
9982   default: break;
9983   case ISD::SETOLT:
9984   case ISD::SETOLE:
9985   case ISD::SETLT:
9986   case ISD::SETLE:
9987   case ISD::SETULT:
9988   case ISD::SETULE:
9989     // If LHS is NaN, an ordered comparison will be false and the result will
9990     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9991     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9992     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9993     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9994       break;
9995     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9996     // will return -0, so vmin can only be used for unsafe math or if one of
9997     // the operands is known to be nonzero.
9998     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9999         !DAG.getTarget().Options.UnsafeFPMath &&
10000         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10001       break;
10002     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10003     break;
10004
10005   case ISD::SETOGT:
10006   case ISD::SETOGE:
10007   case ISD::SETGT:
10008   case ISD::SETGE:
10009   case ISD::SETUGT:
10010   case ISD::SETUGE:
10011     // If LHS is NaN, an ordered comparison will be false and the result will
10012     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
10013     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10014     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10015     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10016       break;
10017     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10018     // will return +0, so vmax can only be used for unsafe math or if one of
10019     // the operands is known to be nonzero.
10020     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10021         !DAG.getTarget().Options.UnsafeFPMath &&
10022         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10023       break;
10024     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10025     break;
10026   }
10027
10028   if (!Opcode)
10029     return SDValue();
10030   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10031 }
10032
10033 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10034 SDValue
10035 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10036   SDValue Cmp = N->getOperand(4);
10037   if (Cmp.getOpcode() != ARMISD::CMPZ)
10038     // Only looking at EQ and NE cases.
10039     return SDValue();
10040
10041   EVT VT = N->getValueType(0);
10042   SDLoc dl(N);
10043   SDValue LHS = Cmp.getOperand(0);
10044   SDValue RHS = Cmp.getOperand(1);
10045   SDValue FalseVal = N->getOperand(0);
10046   SDValue TrueVal = N->getOperand(1);
10047   SDValue ARMcc = N->getOperand(2);
10048   ARMCC::CondCodes CC =
10049     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10050
10051   // Simplify
10052   //   mov     r1, r0
10053   //   cmp     r1, x
10054   //   mov     r0, y
10055   //   moveq   r0, x
10056   // to
10057   //   cmp     r0, x
10058   //   movne   r0, y
10059   //
10060   //   mov     r1, r0
10061   //   cmp     r1, x
10062   //   mov     r0, x
10063   //   movne   r0, y
10064   // to
10065   //   cmp     r0, x
10066   //   movne   r0, y
10067   /// FIXME: Turn this into a target neutral optimization?
10068   SDValue Res;
10069   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10070     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10071                       N->getOperand(3), Cmp);
10072   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10073     SDValue ARMcc;
10074     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10075     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10076                       N->getOperand(3), NewCmp);
10077   }
10078
10079   if (Res.getNode()) {
10080     APInt KnownZero, KnownOne;
10081     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10082     // Capture demanded bits information that would be otherwise lost.
10083     if (KnownZero == 0xfffffffe)
10084       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10085                         DAG.getValueType(MVT::i1));
10086     else if (KnownZero == 0xffffff00)
10087       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10088                         DAG.getValueType(MVT::i8));
10089     else if (KnownZero == 0xffff0000)
10090       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10091                         DAG.getValueType(MVT::i16));
10092   }
10093
10094   return Res;
10095 }
10096
10097 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10098                                              DAGCombinerInfo &DCI) const {
10099   switch (N->getOpcode()) {
10100   default: break;
10101   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10102   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10103   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10104   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10105   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10106   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10107   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10108   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10109   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10110   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10111   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10112   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10113   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10114   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10115   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10116   case ISD::FP_TO_SINT:
10117   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10118   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10119   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10120   case ISD::SHL:
10121   case ISD::SRA:
10122   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10123   case ISD::SIGN_EXTEND:
10124   case ISD::ZERO_EXTEND:
10125   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10126   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10127   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10128   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10129   case ARMISD::VLD2DUP:
10130   case ARMISD::VLD3DUP:
10131   case ARMISD::VLD4DUP:
10132     return PerformVLDCombine(N, DCI);
10133   case ARMISD::BUILD_VECTOR:
10134     return PerformARMBUILD_VECTORCombine(N, DCI);
10135   case ISD::INTRINSIC_VOID:
10136   case ISD::INTRINSIC_W_CHAIN:
10137     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10138     case Intrinsic::arm_neon_vld1:
10139     case Intrinsic::arm_neon_vld2:
10140     case Intrinsic::arm_neon_vld3:
10141     case Intrinsic::arm_neon_vld4:
10142     case Intrinsic::arm_neon_vld2lane:
10143     case Intrinsic::arm_neon_vld3lane:
10144     case Intrinsic::arm_neon_vld4lane:
10145     case Intrinsic::arm_neon_vst1:
10146     case Intrinsic::arm_neon_vst2:
10147     case Intrinsic::arm_neon_vst3:
10148     case Intrinsic::arm_neon_vst4:
10149     case Intrinsic::arm_neon_vst2lane:
10150     case Intrinsic::arm_neon_vst3lane:
10151     case Intrinsic::arm_neon_vst4lane:
10152       return PerformVLDCombine(N, DCI);
10153     default: break;
10154     }
10155     break;
10156   }
10157   return SDValue();
10158 }
10159
10160 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10161                                                           EVT VT) const {
10162   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10163 }
10164
10165 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10166                                                        unsigned,
10167                                                        unsigned,
10168                                                        bool *Fast) const {
10169   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10170   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10171
10172   switch (VT.getSimpleVT().SimpleTy) {
10173   default:
10174     return false;
10175   case MVT::i8:
10176   case MVT::i16:
10177   case MVT::i32: {
10178     // Unaligned access can use (for example) LRDB, LRDH, LDR
10179     if (AllowsUnaligned) {
10180       if (Fast)
10181         *Fast = Subtarget->hasV7Ops();
10182       return true;
10183     }
10184     return false;
10185   }
10186   case MVT::f64:
10187   case MVT::v2f64: {
10188     // For any little-endian targets with neon, we can support unaligned ld/st
10189     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10190     // A big-endian target may also explicitly support unaligned accesses
10191     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10192       if (Fast)
10193         *Fast = true;
10194       return true;
10195     }
10196     return false;
10197   }
10198   }
10199 }
10200
10201 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10202                        unsigned AlignCheck) {
10203   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10204           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10205 }
10206
10207 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10208                                            unsigned DstAlign, unsigned SrcAlign,
10209                                            bool IsMemset, bool ZeroMemset,
10210                                            bool MemcpyStrSrc,
10211                                            MachineFunction &MF) const {
10212   const Function *F = MF.getFunction();
10213
10214   // See if we can use NEON instructions for this...
10215   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10216       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10217     bool Fast;
10218     if (Size >= 16 &&
10219         (memOpAlign(SrcAlign, DstAlign, 16) ||
10220          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10221       return MVT::v2f64;
10222     } else if (Size >= 8 &&
10223                (memOpAlign(SrcAlign, DstAlign, 8) ||
10224                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10225                  Fast))) {
10226       return MVT::f64;
10227     }
10228   }
10229
10230   // Lowering to i32/i16 if the size permits.
10231   if (Size >= 4)
10232     return MVT::i32;
10233   else if (Size >= 2)
10234     return MVT::i16;
10235
10236   // Let the target-independent logic figure it out.
10237   return MVT::Other;
10238 }
10239
10240 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10241   if (Val.getOpcode() != ISD::LOAD)
10242     return false;
10243
10244   EVT VT1 = Val.getValueType();
10245   if (!VT1.isSimple() || !VT1.isInteger() ||
10246       !VT2.isSimple() || !VT2.isInteger())
10247     return false;
10248
10249   switch (VT1.getSimpleVT().SimpleTy) {
10250   default: break;
10251   case MVT::i1:
10252   case MVT::i8:
10253   case MVT::i16:
10254     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10255     return true;
10256   }
10257
10258   return false;
10259 }
10260
10261 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10262   EVT VT = ExtVal.getValueType();
10263
10264   if (!isTypeLegal(VT))
10265     return false;
10266
10267   // Don't create a loadext if we can fold the extension into a wide/long
10268   // instruction.
10269   // If there's more than one user instruction, the loadext is desirable no
10270   // matter what.  There can be two uses by the same instruction.
10271   if (ExtVal->use_empty() ||
10272       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10273     return true;
10274
10275   SDNode *U = *ExtVal->use_begin();
10276   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10277        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10278     return false;
10279
10280   return true;
10281 }
10282
10283 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10284   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10285     return false;
10286
10287   if (!isTypeLegal(EVT::getEVT(Ty1)))
10288     return false;
10289
10290   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10291
10292   // Assuming the caller doesn't have a zeroext or signext return parameter,
10293   // truncation all the way down to i1 is valid.
10294   return true;
10295 }
10296
10297
10298 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10299   if (V < 0)
10300     return false;
10301
10302   unsigned Scale = 1;
10303   switch (VT.getSimpleVT().SimpleTy) {
10304   default: return false;
10305   case MVT::i1:
10306   case MVT::i8:
10307     // Scale == 1;
10308     break;
10309   case MVT::i16:
10310     // Scale == 2;
10311     Scale = 2;
10312     break;
10313   case MVT::i32:
10314     // Scale == 4;
10315     Scale = 4;
10316     break;
10317   }
10318
10319   if ((V & (Scale - 1)) != 0)
10320     return false;
10321   V /= Scale;
10322   return V == (V & ((1LL << 5) - 1));
10323 }
10324
10325 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10326                                       const ARMSubtarget *Subtarget) {
10327   bool isNeg = false;
10328   if (V < 0) {
10329     isNeg = true;
10330     V = - V;
10331   }
10332
10333   switch (VT.getSimpleVT().SimpleTy) {
10334   default: return false;
10335   case MVT::i1:
10336   case MVT::i8:
10337   case MVT::i16:
10338   case MVT::i32:
10339     // + imm12 or - imm8
10340     if (isNeg)
10341       return V == (V & ((1LL << 8) - 1));
10342     return V == (V & ((1LL << 12) - 1));
10343   case MVT::f32:
10344   case MVT::f64:
10345     // Same as ARM mode. FIXME: NEON?
10346     if (!Subtarget->hasVFP2())
10347       return false;
10348     if ((V & 3) != 0)
10349       return false;
10350     V >>= 2;
10351     return V == (V & ((1LL << 8) - 1));
10352   }
10353 }
10354
10355 /// isLegalAddressImmediate - Return true if the integer value can be used
10356 /// as the offset of the target addressing mode for load / store of the
10357 /// given type.
10358 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10359                                     const ARMSubtarget *Subtarget) {
10360   if (V == 0)
10361     return true;
10362
10363   if (!VT.isSimple())
10364     return false;
10365
10366   if (Subtarget->isThumb1Only())
10367     return isLegalT1AddressImmediate(V, VT);
10368   else if (Subtarget->isThumb2())
10369     return isLegalT2AddressImmediate(V, VT, Subtarget);
10370
10371   // ARM mode.
10372   if (V < 0)
10373     V = - V;
10374   switch (VT.getSimpleVT().SimpleTy) {
10375   default: return false;
10376   case MVT::i1:
10377   case MVT::i8:
10378   case MVT::i32:
10379     // +- imm12
10380     return V == (V & ((1LL << 12) - 1));
10381   case MVT::i16:
10382     // +- imm8
10383     return V == (V & ((1LL << 8) - 1));
10384   case MVT::f32:
10385   case MVT::f64:
10386     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10387       return false;
10388     if ((V & 3) != 0)
10389       return false;
10390     V >>= 2;
10391     return V == (V & ((1LL << 8) - 1));
10392   }
10393 }
10394
10395 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10396                                                       EVT VT) const {
10397   int Scale = AM.Scale;
10398   if (Scale < 0)
10399     return false;
10400
10401   switch (VT.getSimpleVT().SimpleTy) {
10402   default: return false;
10403   case MVT::i1:
10404   case MVT::i8:
10405   case MVT::i16:
10406   case MVT::i32:
10407     if (Scale == 1)
10408       return true;
10409     // r + r << imm
10410     Scale = Scale & ~1;
10411     return Scale == 2 || Scale == 4 || Scale == 8;
10412   case MVT::i64:
10413     // r + r
10414     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10415       return true;
10416     return false;
10417   case MVT::isVoid:
10418     // Note, we allow "void" uses (basically, uses that aren't loads or
10419     // stores), because arm allows folding a scale into many arithmetic
10420     // operations.  This should be made more precise and revisited later.
10421
10422     // Allow r << imm, but the imm has to be a multiple of two.
10423     if (Scale & 1) return false;
10424     return isPowerOf2_32(Scale);
10425   }
10426 }
10427
10428 /// isLegalAddressingMode - Return true if the addressing mode represented
10429 /// by AM is legal for this target, for a load/store of the specified type.
10430 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10431                                               const AddrMode &AM, Type *Ty,
10432                                               unsigned AS) const {
10433   EVT VT = getValueType(DL, Ty, true);
10434   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10435     return false;
10436
10437   // Can never fold addr of global into load/store.
10438   if (AM.BaseGV)
10439     return false;
10440
10441   switch (AM.Scale) {
10442   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10443     break;
10444   case 1:
10445     if (Subtarget->isThumb1Only())
10446       return false;
10447     // FALL THROUGH.
10448   default:
10449     // ARM doesn't support any R+R*scale+imm addr modes.
10450     if (AM.BaseOffs)
10451       return false;
10452
10453     if (!VT.isSimple())
10454       return false;
10455
10456     if (Subtarget->isThumb2())
10457       return isLegalT2ScaledAddressingMode(AM, VT);
10458
10459     int Scale = AM.Scale;
10460     switch (VT.getSimpleVT().SimpleTy) {
10461     default: return false;
10462     case MVT::i1:
10463     case MVT::i8:
10464     case MVT::i32:
10465       if (Scale < 0) Scale = -Scale;
10466       if (Scale == 1)
10467         return true;
10468       // r + r << imm
10469       return isPowerOf2_32(Scale & ~1);
10470     case MVT::i16:
10471     case MVT::i64:
10472       // r + r
10473       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10474         return true;
10475       return false;
10476
10477     case MVT::isVoid:
10478       // Note, we allow "void" uses (basically, uses that aren't loads or
10479       // stores), because arm allows folding a scale into many arithmetic
10480       // operations.  This should be made more precise and revisited later.
10481
10482       // Allow r << imm, but the imm has to be a multiple of two.
10483       if (Scale & 1) return false;
10484       return isPowerOf2_32(Scale);
10485     }
10486   }
10487   return true;
10488 }
10489
10490 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10491 /// icmp immediate, that is the target has icmp instructions which can compare
10492 /// a register against the immediate without having to materialize the
10493 /// immediate into a register.
10494 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10495   // Thumb2 and ARM modes can use cmn for negative immediates.
10496   if (!Subtarget->isThumb())
10497     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10498   if (Subtarget->isThumb2())
10499     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10500   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10501   return Imm >= 0 && Imm <= 255;
10502 }
10503
10504 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10505 /// *or sub* immediate, that is the target has add or sub instructions which can
10506 /// add a register with the immediate without having to materialize the
10507 /// immediate into a register.
10508 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10509   // Same encoding for add/sub, just flip the sign.
10510   int64_t AbsImm = std::abs(Imm);
10511   if (!Subtarget->isThumb())
10512     return ARM_AM::getSOImmVal(AbsImm) != -1;
10513   if (Subtarget->isThumb2())
10514     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10515   // Thumb1 only has 8-bit unsigned immediate.
10516   return AbsImm >= 0 && AbsImm <= 255;
10517 }
10518
10519 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10520                                       bool isSEXTLoad, SDValue &Base,
10521                                       SDValue &Offset, bool &isInc,
10522                                       SelectionDAG &DAG) {
10523   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10524     return false;
10525
10526   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10527     // AddressingMode 3
10528     Base = Ptr->getOperand(0);
10529     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10530       int RHSC = (int)RHS->getZExtValue();
10531       if (RHSC < 0 && RHSC > -256) {
10532         assert(Ptr->getOpcode() == ISD::ADD);
10533         isInc = false;
10534         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10535         return true;
10536       }
10537     }
10538     isInc = (Ptr->getOpcode() == ISD::ADD);
10539     Offset = Ptr->getOperand(1);
10540     return true;
10541   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10542     // AddressingMode 2
10543     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10544       int RHSC = (int)RHS->getZExtValue();
10545       if (RHSC < 0 && RHSC > -0x1000) {
10546         assert(Ptr->getOpcode() == ISD::ADD);
10547         isInc = false;
10548         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10549         Base = Ptr->getOperand(0);
10550         return true;
10551       }
10552     }
10553
10554     if (Ptr->getOpcode() == ISD::ADD) {
10555       isInc = true;
10556       ARM_AM::ShiftOpc ShOpcVal=
10557         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10558       if (ShOpcVal != ARM_AM::no_shift) {
10559         Base = Ptr->getOperand(1);
10560         Offset = Ptr->getOperand(0);
10561       } else {
10562         Base = Ptr->getOperand(0);
10563         Offset = Ptr->getOperand(1);
10564       }
10565       return true;
10566     }
10567
10568     isInc = (Ptr->getOpcode() == ISD::ADD);
10569     Base = Ptr->getOperand(0);
10570     Offset = Ptr->getOperand(1);
10571     return true;
10572   }
10573
10574   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10575   return false;
10576 }
10577
10578 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10579                                      bool isSEXTLoad, SDValue &Base,
10580                                      SDValue &Offset, bool &isInc,
10581                                      SelectionDAG &DAG) {
10582   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10583     return false;
10584
10585   Base = Ptr->getOperand(0);
10586   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10587     int RHSC = (int)RHS->getZExtValue();
10588     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10589       assert(Ptr->getOpcode() == ISD::ADD);
10590       isInc = false;
10591       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10592       return true;
10593     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10594       isInc = Ptr->getOpcode() == ISD::ADD;
10595       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10596       return true;
10597     }
10598   }
10599
10600   return false;
10601 }
10602
10603 /// getPreIndexedAddressParts - returns true by value, base pointer and
10604 /// offset pointer and addressing mode by reference if the node's address
10605 /// can be legally represented as pre-indexed load / store address.
10606 bool
10607 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10608                                              SDValue &Offset,
10609                                              ISD::MemIndexedMode &AM,
10610                                              SelectionDAG &DAG) const {
10611   if (Subtarget->isThumb1Only())
10612     return false;
10613
10614   EVT VT;
10615   SDValue Ptr;
10616   bool isSEXTLoad = false;
10617   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10618     Ptr = LD->getBasePtr();
10619     VT  = LD->getMemoryVT();
10620     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10621   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10622     Ptr = ST->getBasePtr();
10623     VT  = ST->getMemoryVT();
10624   } else
10625     return false;
10626
10627   bool isInc;
10628   bool isLegal = false;
10629   if (Subtarget->isThumb2())
10630     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10631                                        Offset, isInc, DAG);
10632   else
10633     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10634                                         Offset, isInc, DAG);
10635   if (!isLegal)
10636     return false;
10637
10638   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10639   return true;
10640 }
10641
10642 /// getPostIndexedAddressParts - returns true by value, base pointer and
10643 /// offset pointer and addressing mode by reference if this node can be
10644 /// combined with a load / store to form a post-indexed load / store.
10645 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10646                                                    SDValue &Base,
10647                                                    SDValue &Offset,
10648                                                    ISD::MemIndexedMode &AM,
10649                                                    SelectionDAG &DAG) const {
10650   if (Subtarget->isThumb1Only())
10651     return false;
10652
10653   EVT VT;
10654   SDValue Ptr;
10655   bool isSEXTLoad = false;
10656   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10657     VT  = LD->getMemoryVT();
10658     Ptr = LD->getBasePtr();
10659     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10660   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10661     VT  = ST->getMemoryVT();
10662     Ptr = ST->getBasePtr();
10663   } else
10664     return false;
10665
10666   bool isInc;
10667   bool isLegal = false;
10668   if (Subtarget->isThumb2())
10669     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10670                                        isInc, DAG);
10671   else
10672     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10673                                         isInc, DAG);
10674   if (!isLegal)
10675     return false;
10676
10677   if (Ptr != Base) {
10678     // Swap base ptr and offset to catch more post-index load / store when
10679     // it's legal. In Thumb2 mode, offset must be an immediate.
10680     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10681         !Subtarget->isThumb2())
10682       std::swap(Base, Offset);
10683
10684     // Post-indexed load / store update the base pointer.
10685     if (Ptr != Base)
10686       return false;
10687   }
10688
10689   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10690   return true;
10691 }
10692
10693 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10694                                                       APInt &KnownZero,
10695                                                       APInt &KnownOne,
10696                                                       const SelectionDAG &DAG,
10697                                                       unsigned Depth) const {
10698   unsigned BitWidth = KnownOne.getBitWidth();
10699   KnownZero = KnownOne = APInt(BitWidth, 0);
10700   switch (Op.getOpcode()) {
10701   default: break;
10702   case ARMISD::ADDC:
10703   case ARMISD::ADDE:
10704   case ARMISD::SUBC:
10705   case ARMISD::SUBE:
10706     // These nodes' second result is a boolean
10707     if (Op.getResNo() == 0)
10708       break;
10709     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10710     break;
10711   case ARMISD::CMOV: {
10712     // Bits are known zero/one if known on the LHS and RHS.
10713     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10714     if (KnownZero == 0 && KnownOne == 0) return;
10715
10716     APInt KnownZeroRHS, KnownOneRHS;
10717     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10718     KnownZero &= KnownZeroRHS;
10719     KnownOne  &= KnownOneRHS;
10720     return;
10721   }
10722   case ISD::INTRINSIC_W_CHAIN: {
10723     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10724     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10725     switch (IntID) {
10726     default: return;
10727     case Intrinsic::arm_ldaex:
10728     case Intrinsic::arm_ldrex: {
10729       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10730       unsigned MemBits = VT.getScalarType().getSizeInBits();
10731       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10732       return;
10733     }
10734     }
10735   }
10736   }
10737 }
10738
10739 //===----------------------------------------------------------------------===//
10740 //                           ARM Inline Assembly Support
10741 //===----------------------------------------------------------------------===//
10742
10743 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10744   // Looking for "rev" which is V6+.
10745   if (!Subtarget->hasV6Ops())
10746     return false;
10747
10748   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10749   std::string AsmStr = IA->getAsmString();
10750   SmallVector<StringRef, 4> AsmPieces;
10751   SplitString(AsmStr, AsmPieces, ";\n");
10752
10753   switch (AsmPieces.size()) {
10754   default: return false;
10755   case 1:
10756     AsmStr = AsmPieces[0];
10757     AsmPieces.clear();
10758     SplitString(AsmStr, AsmPieces, " \t,");
10759
10760     // rev $0, $1
10761     if (AsmPieces.size() == 3 &&
10762         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10763         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10764       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10765       if (Ty && Ty->getBitWidth() == 32)
10766         return IntrinsicLowering::LowerToByteSwap(CI);
10767     }
10768     break;
10769   }
10770
10771   return false;
10772 }
10773
10774 /// getConstraintType - Given a constraint letter, return the type of
10775 /// constraint it is for this target.
10776 ARMTargetLowering::ConstraintType
10777 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10778   if (Constraint.size() == 1) {
10779     switch (Constraint[0]) {
10780     default:  break;
10781     case 'l': return C_RegisterClass;
10782     case 'w': return C_RegisterClass;
10783     case 'h': return C_RegisterClass;
10784     case 'x': return C_RegisterClass;
10785     case 't': return C_RegisterClass;
10786     case 'j': return C_Other; // Constant for movw.
10787       // An address with a single base register. Due to the way we
10788       // currently handle addresses it is the same as an 'r' memory constraint.
10789     case 'Q': return C_Memory;
10790     }
10791   } else if (Constraint.size() == 2) {
10792     switch (Constraint[0]) {
10793     default: break;
10794     // All 'U+' constraints are addresses.
10795     case 'U': return C_Memory;
10796     }
10797   }
10798   return TargetLowering::getConstraintType(Constraint);
10799 }
10800
10801 /// Examine constraint type and operand type and determine a weight value.
10802 /// This object must already have been set up with the operand type
10803 /// and the current alternative constraint selected.
10804 TargetLowering::ConstraintWeight
10805 ARMTargetLowering::getSingleConstraintMatchWeight(
10806     AsmOperandInfo &info, const char *constraint) const {
10807   ConstraintWeight weight = CW_Invalid;
10808   Value *CallOperandVal = info.CallOperandVal;
10809     // If we don't have a value, we can't do a match,
10810     // but allow it at the lowest weight.
10811   if (!CallOperandVal)
10812     return CW_Default;
10813   Type *type = CallOperandVal->getType();
10814   // Look at the constraint type.
10815   switch (*constraint) {
10816   default:
10817     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10818     break;
10819   case 'l':
10820     if (type->isIntegerTy()) {
10821       if (Subtarget->isThumb())
10822         weight = CW_SpecificReg;
10823       else
10824         weight = CW_Register;
10825     }
10826     break;
10827   case 'w':
10828     if (type->isFloatingPointTy())
10829       weight = CW_Register;
10830     break;
10831   }
10832   return weight;
10833 }
10834
10835 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10836 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
10837     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
10838   if (Constraint.size() == 1) {
10839     // GCC ARM Constraint Letters
10840     switch (Constraint[0]) {
10841     case 'l': // Low regs or general regs.
10842       if (Subtarget->isThumb())
10843         return RCPair(0U, &ARM::tGPRRegClass);
10844       return RCPair(0U, &ARM::GPRRegClass);
10845     case 'h': // High regs or no regs.
10846       if (Subtarget->isThumb())
10847         return RCPair(0U, &ARM::hGPRRegClass);
10848       break;
10849     case 'r':
10850       if (Subtarget->isThumb1Only())
10851         return RCPair(0U, &ARM::tGPRRegClass);
10852       return RCPair(0U, &ARM::GPRRegClass);
10853     case 'w':
10854       if (VT == MVT::Other)
10855         break;
10856       if (VT == MVT::f32)
10857         return RCPair(0U, &ARM::SPRRegClass);
10858       if (VT.getSizeInBits() == 64)
10859         return RCPair(0U, &ARM::DPRRegClass);
10860       if (VT.getSizeInBits() == 128)
10861         return RCPair(0U, &ARM::QPRRegClass);
10862       break;
10863     case 'x':
10864       if (VT == MVT::Other)
10865         break;
10866       if (VT == MVT::f32)
10867         return RCPair(0U, &ARM::SPR_8RegClass);
10868       if (VT.getSizeInBits() == 64)
10869         return RCPair(0U, &ARM::DPR_8RegClass);
10870       if (VT.getSizeInBits() == 128)
10871         return RCPair(0U, &ARM::QPR_8RegClass);
10872       break;
10873     case 't':
10874       if (VT == MVT::f32)
10875         return RCPair(0U, &ARM::SPRRegClass);
10876       break;
10877     }
10878   }
10879   if (StringRef("{cc}").equals_lower(Constraint))
10880     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10881
10882   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10883 }
10884
10885 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10886 /// vector.  If it is invalid, don't add anything to Ops.
10887 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10888                                                      std::string &Constraint,
10889                                                      std::vector<SDValue>&Ops,
10890                                                      SelectionDAG &DAG) const {
10891   SDValue Result;
10892
10893   // Currently only support length 1 constraints.
10894   if (Constraint.length() != 1) return;
10895
10896   char ConstraintLetter = Constraint[0];
10897   switch (ConstraintLetter) {
10898   default: break;
10899   case 'j':
10900   case 'I': case 'J': case 'K': case 'L':
10901   case 'M': case 'N': case 'O':
10902     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10903     if (!C)
10904       return;
10905
10906     int64_t CVal64 = C->getSExtValue();
10907     int CVal = (int) CVal64;
10908     // None of these constraints allow values larger than 32 bits.  Check
10909     // that the value fits in an int.
10910     if (CVal != CVal64)
10911       return;
10912
10913     switch (ConstraintLetter) {
10914       case 'j':
10915         // Constant suitable for movw, must be between 0 and
10916         // 65535.
10917         if (Subtarget->hasV6T2Ops())
10918           if (CVal >= 0 && CVal <= 65535)
10919             break;
10920         return;
10921       case 'I':
10922         if (Subtarget->isThumb1Only()) {
10923           // This must be a constant between 0 and 255, for ADD
10924           // immediates.
10925           if (CVal >= 0 && CVal <= 255)
10926             break;
10927         } else if (Subtarget->isThumb2()) {
10928           // A constant that can be used as an immediate value in a
10929           // data-processing instruction.
10930           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10931             break;
10932         } else {
10933           // A constant that can be used as an immediate value in a
10934           // data-processing instruction.
10935           if (ARM_AM::getSOImmVal(CVal) != -1)
10936             break;
10937         }
10938         return;
10939
10940       case 'J':
10941         if (Subtarget->isThumb()) {  // FIXME thumb2
10942           // This must be a constant between -255 and -1, for negated ADD
10943           // immediates. This can be used in GCC with an "n" modifier that
10944           // prints the negated value, for use with SUB instructions. It is
10945           // not useful otherwise but is implemented for compatibility.
10946           if (CVal >= -255 && CVal <= -1)
10947             break;
10948         } else {
10949           // This must be a constant between -4095 and 4095. It is not clear
10950           // what this constraint is intended for. Implemented for
10951           // compatibility with GCC.
10952           if (CVal >= -4095 && CVal <= 4095)
10953             break;
10954         }
10955         return;
10956
10957       case 'K':
10958         if (Subtarget->isThumb1Only()) {
10959           // A 32-bit value where only one byte has a nonzero value. Exclude
10960           // zero to match GCC. This constraint is used by GCC internally for
10961           // constants that can be loaded with a move/shift combination.
10962           // It is not useful otherwise but is implemented for compatibility.
10963           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10964             break;
10965         } else if (Subtarget->isThumb2()) {
10966           // A constant whose bitwise inverse can be used as an immediate
10967           // value in a data-processing instruction. This can be used in GCC
10968           // with a "B" modifier that prints the inverted value, for use with
10969           // BIC and MVN instructions. It is not useful otherwise but is
10970           // implemented for compatibility.
10971           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10972             break;
10973         } else {
10974           // A constant whose bitwise inverse can be used as an immediate
10975           // value in a data-processing instruction. This can be used in GCC
10976           // with a "B" modifier that prints the inverted value, for use with
10977           // BIC and MVN instructions. It is not useful otherwise but is
10978           // implemented for compatibility.
10979           if (ARM_AM::getSOImmVal(~CVal) != -1)
10980             break;
10981         }
10982         return;
10983
10984       case 'L':
10985         if (Subtarget->isThumb1Only()) {
10986           // This must be a constant between -7 and 7,
10987           // for 3-operand ADD/SUB immediate instructions.
10988           if (CVal >= -7 && CVal < 7)
10989             break;
10990         } else if (Subtarget->isThumb2()) {
10991           // A constant whose negation can be used as an immediate value in a
10992           // data-processing instruction. This can be used in GCC with an "n"
10993           // modifier that prints the negated value, for use with SUB
10994           // instructions. It is not useful otherwise but is implemented for
10995           // compatibility.
10996           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10997             break;
10998         } else {
10999           // A constant whose negation can be used as an immediate value in a
11000           // data-processing instruction. This can be used in GCC with an "n"
11001           // modifier that prints the negated value, for use with SUB
11002           // instructions. It is not useful otherwise but is implemented for
11003           // compatibility.
11004           if (ARM_AM::getSOImmVal(-CVal) != -1)
11005             break;
11006         }
11007         return;
11008
11009       case 'M':
11010         if (Subtarget->isThumb()) { // FIXME thumb2
11011           // This must be a multiple of 4 between 0 and 1020, for
11012           // ADD sp + immediate.
11013           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11014             break;
11015         } else {
11016           // A power of two or a constant between 0 and 32.  This is used in
11017           // GCC for the shift amount on shifted register operands, but it is
11018           // useful in general for any shift amounts.
11019           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11020             break;
11021         }
11022         return;
11023
11024       case 'N':
11025         if (Subtarget->isThumb()) {  // FIXME thumb2
11026           // This must be a constant between 0 and 31, for shift amounts.
11027           if (CVal >= 0 && CVal <= 31)
11028             break;
11029         }
11030         return;
11031
11032       case 'O':
11033         if (Subtarget->isThumb()) {  // FIXME thumb2
11034           // This must be a multiple of 4 between -508 and 508, for
11035           // ADD/SUB sp = sp + immediate.
11036           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11037             break;
11038         }
11039         return;
11040     }
11041     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11042     break;
11043   }
11044
11045   if (Result.getNode()) {
11046     Ops.push_back(Result);
11047     return;
11048   }
11049   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11050 }
11051
11052 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11053   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
11054   unsigned Opcode = Op->getOpcode();
11055   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11056          "Invalid opcode for Div/Rem lowering");
11057   bool isSigned = (Opcode == ISD::SDIVREM);
11058   EVT VT = Op->getValueType(0);
11059   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11060
11061   RTLIB::Libcall LC;
11062   switch (VT.getSimpleVT().SimpleTy) {
11063   default: llvm_unreachable("Unexpected request for libcall!");
11064   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11065   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11066   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11067   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11068   }
11069
11070   SDValue InChain = DAG.getEntryNode();
11071
11072   TargetLowering::ArgListTy Args;
11073   TargetLowering::ArgListEntry Entry;
11074   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11075     EVT ArgVT = Op->getOperand(i).getValueType();
11076     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11077     Entry.Node = Op->getOperand(i);
11078     Entry.Ty = ArgTy;
11079     Entry.isSExt = isSigned;
11080     Entry.isZExt = !isSigned;
11081     Args.push_back(Entry);
11082   }
11083
11084   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11085                                          getPointerTy(DAG.getDataLayout()));
11086
11087   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11088
11089   SDLoc dl(Op);
11090   TargetLowering::CallLoweringInfo CLI(DAG);
11091   CLI.setDebugLoc(dl).setChain(InChain)
11092     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11093     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11094
11095   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11096   return CallInfo.first;
11097 }
11098
11099 SDValue
11100 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11101   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11102   SDLoc DL(Op);
11103
11104   // Get the inputs.
11105   SDValue Chain = Op.getOperand(0);
11106   SDValue Size  = Op.getOperand(1);
11107
11108   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11109                               DAG.getConstant(2, DL, MVT::i32));
11110
11111   SDValue Flag;
11112   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11113   Flag = Chain.getValue(1);
11114
11115   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11116   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11117
11118   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11119   Chain = NewSP.getValue(1);
11120
11121   SDValue Ops[2] = { NewSP, Chain };
11122   return DAG.getMergeValues(Ops, DL);
11123 }
11124
11125 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11126   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11127          "Unexpected type for custom-lowering FP_EXTEND");
11128
11129   RTLIB::Libcall LC;
11130   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11131
11132   SDValue SrcVal = Op.getOperand(0);
11133   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11134                      /*isSigned*/ false, SDLoc(Op)).first;
11135 }
11136
11137 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11138   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11139          Subtarget->isFPOnlySP() &&
11140          "Unexpected type for custom-lowering FP_ROUND");
11141
11142   RTLIB::Libcall LC;
11143   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11144
11145   SDValue SrcVal = Op.getOperand(0);
11146   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11147                      /*isSigned*/ false, SDLoc(Op)).first;
11148 }
11149
11150 bool
11151 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11152   // The ARM target isn't yet aware of offsets.
11153   return false;
11154 }
11155
11156 bool ARM::isBitFieldInvertedMask(unsigned v) {
11157   if (v == 0xffffffff)
11158     return false;
11159
11160   // there can be 1's on either or both "outsides", all the "inside"
11161   // bits must be 0's
11162   return isShiftedMask_32(~v);
11163 }
11164
11165 /// isFPImmLegal - Returns true if the target can instruction select the
11166 /// specified FP immediate natively. If false, the legalizer will
11167 /// materialize the FP immediate as a load from a constant pool.
11168 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11169   if (!Subtarget->hasVFP3())
11170     return false;
11171   if (VT == MVT::f32)
11172     return ARM_AM::getFP32Imm(Imm) != -1;
11173   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11174     return ARM_AM::getFP64Imm(Imm) != -1;
11175   return false;
11176 }
11177
11178 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11179 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11180 /// specified in the intrinsic calls.
11181 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11182                                            const CallInst &I,
11183                                            unsigned Intrinsic) const {
11184   switch (Intrinsic) {
11185   case Intrinsic::arm_neon_vld1:
11186   case Intrinsic::arm_neon_vld2:
11187   case Intrinsic::arm_neon_vld3:
11188   case Intrinsic::arm_neon_vld4:
11189   case Intrinsic::arm_neon_vld2lane:
11190   case Intrinsic::arm_neon_vld3lane:
11191   case Intrinsic::arm_neon_vld4lane: {
11192     Info.opc = ISD::INTRINSIC_W_CHAIN;
11193     // Conservatively set memVT to the entire set of vectors loaded.
11194     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11195     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11196     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11197     Info.ptrVal = I.getArgOperand(0);
11198     Info.offset = 0;
11199     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11200     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11201     Info.vol = false; // volatile loads with NEON intrinsics not supported
11202     Info.readMem = true;
11203     Info.writeMem = false;
11204     return true;
11205   }
11206   case Intrinsic::arm_neon_vst1:
11207   case Intrinsic::arm_neon_vst2:
11208   case Intrinsic::arm_neon_vst3:
11209   case Intrinsic::arm_neon_vst4:
11210   case Intrinsic::arm_neon_vst2lane:
11211   case Intrinsic::arm_neon_vst3lane:
11212   case Intrinsic::arm_neon_vst4lane: {
11213     Info.opc = ISD::INTRINSIC_VOID;
11214     // Conservatively set memVT to the entire set of vectors stored.
11215     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11216     unsigned NumElts = 0;
11217     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11218       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11219       if (!ArgTy->isVectorTy())
11220         break;
11221       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11222     }
11223     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11224     Info.ptrVal = I.getArgOperand(0);
11225     Info.offset = 0;
11226     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11227     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11228     Info.vol = false; // volatile stores with NEON intrinsics not supported
11229     Info.readMem = false;
11230     Info.writeMem = true;
11231     return true;
11232   }
11233   case Intrinsic::arm_ldaex:
11234   case Intrinsic::arm_ldrex: {
11235     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11236     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11237     Info.opc = ISD::INTRINSIC_W_CHAIN;
11238     Info.memVT = MVT::getVT(PtrTy->getElementType());
11239     Info.ptrVal = I.getArgOperand(0);
11240     Info.offset = 0;
11241     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11242     Info.vol = true;
11243     Info.readMem = true;
11244     Info.writeMem = false;
11245     return true;
11246   }
11247   case Intrinsic::arm_stlex:
11248   case Intrinsic::arm_strex: {
11249     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11250     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11251     Info.opc = ISD::INTRINSIC_W_CHAIN;
11252     Info.memVT = MVT::getVT(PtrTy->getElementType());
11253     Info.ptrVal = I.getArgOperand(1);
11254     Info.offset = 0;
11255     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11256     Info.vol = true;
11257     Info.readMem = false;
11258     Info.writeMem = true;
11259     return true;
11260   }
11261   case Intrinsic::arm_stlexd:
11262   case Intrinsic::arm_strexd: {
11263     Info.opc = ISD::INTRINSIC_W_CHAIN;
11264     Info.memVT = MVT::i64;
11265     Info.ptrVal = I.getArgOperand(2);
11266     Info.offset = 0;
11267     Info.align = 8;
11268     Info.vol = true;
11269     Info.readMem = false;
11270     Info.writeMem = true;
11271     return true;
11272   }
11273   case Intrinsic::arm_ldaexd:
11274   case Intrinsic::arm_ldrexd: {
11275     Info.opc = ISD::INTRINSIC_W_CHAIN;
11276     Info.memVT = MVT::i64;
11277     Info.ptrVal = I.getArgOperand(0);
11278     Info.offset = 0;
11279     Info.align = 8;
11280     Info.vol = true;
11281     Info.readMem = true;
11282     Info.writeMem = false;
11283     return true;
11284   }
11285   default:
11286     break;
11287   }
11288
11289   return false;
11290 }
11291
11292 /// \brief Returns true if it is beneficial to convert a load of a constant
11293 /// to just the constant itself.
11294 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11295                                                           Type *Ty) const {
11296   assert(Ty->isIntegerTy());
11297
11298   unsigned Bits = Ty->getPrimitiveSizeInBits();
11299   if (Bits == 0 || Bits > 32)
11300     return false;
11301   return true;
11302 }
11303
11304 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11305
11306 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11307                                         ARM_MB::MemBOpt Domain) const {
11308   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11309
11310   // First, if the target has no DMB, see what fallback we can use.
11311   if (!Subtarget->hasDataBarrier()) {
11312     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11313     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11314     // here.
11315     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11316       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11317       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11318                         Builder.getInt32(0), Builder.getInt32(7),
11319                         Builder.getInt32(10), Builder.getInt32(5)};
11320       return Builder.CreateCall(MCR, args);
11321     } else {
11322       // Instead of using barriers, atomic accesses on these subtargets use
11323       // libcalls.
11324       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11325     }
11326   } else {
11327     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11328     // Only a full system barrier exists in the M-class architectures.
11329     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11330     Constant *CDomain = Builder.getInt32(Domain);
11331     return Builder.CreateCall(DMB, CDomain);
11332   }
11333 }
11334
11335 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11336 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11337                                          AtomicOrdering Ord, bool IsStore,
11338                                          bool IsLoad) const {
11339   if (!getInsertFencesForAtomic())
11340     return nullptr;
11341
11342   switch (Ord) {
11343   case NotAtomic:
11344   case Unordered:
11345     llvm_unreachable("Invalid fence: unordered/non-atomic");
11346   case Monotonic:
11347   case Acquire:
11348     return nullptr; // Nothing to do
11349   case SequentiallyConsistent:
11350     if (!IsStore)
11351       return nullptr; // Nothing to do
11352     /*FALLTHROUGH*/
11353   case Release:
11354   case AcquireRelease:
11355     if (Subtarget->isSwift())
11356       return makeDMB(Builder, ARM_MB::ISHST);
11357     // FIXME: add a comment with a link to documentation justifying this.
11358     else
11359       return makeDMB(Builder, ARM_MB::ISH);
11360   }
11361   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11362 }
11363
11364 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11365                                           AtomicOrdering Ord, bool IsStore,
11366                                           bool IsLoad) const {
11367   if (!getInsertFencesForAtomic())
11368     return nullptr;
11369
11370   switch (Ord) {
11371   case NotAtomic:
11372   case Unordered:
11373     llvm_unreachable("Invalid fence: unordered/not-atomic");
11374   case Monotonic:
11375   case Release:
11376     return nullptr; // Nothing to do
11377   case Acquire:
11378   case AcquireRelease:
11379   case SequentiallyConsistent:
11380     return makeDMB(Builder, ARM_MB::ISH);
11381   }
11382   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11383 }
11384
11385 // Loads and stores less than 64-bits are already atomic; ones above that
11386 // are doomed anyway, so defer to the default libcall and blame the OS when
11387 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11388 // anything for those.
11389 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11390   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11391   return (Size == 64) && !Subtarget->isMClass();
11392 }
11393
11394 // Loads and stores less than 64-bits are already atomic; ones above that
11395 // are doomed anyway, so defer to the default libcall and blame the OS when
11396 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11397 // anything for those.
11398 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11399 // guarantee, see DDI0406C ARM architecture reference manual,
11400 // sections A8.8.72-74 LDRD)
11401 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11402   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11403   return (Size == 64) && !Subtarget->isMClass();
11404 }
11405
11406 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11407 // and up to 64 bits on the non-M profiles
11408 TargetLoweringBase::AtomicRMWExpansionKind
11409 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11410   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11411   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11412              ? AtomicRMWExpansionKind::LLSC
11413              : AtomicRMWExpansionKind::None;
11414 }
11415
11416 // This has so far only been implemented for MachO.
11417 bool ARMTargetLowering::useLoadStackGuardNode() const {
11418   return Subtarget->isTargetMachO();
11419 }
11420
11421 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11422                                                   unsigned &Cost) const {
11423   // If we do not have NEON, vector types are not natively supported.
11424   if (!Subtarget->hasNEON())
11425     return false;
11426
11427   // Floating point values and vector values map to the same register file.
11428   // Therefore, althought we could do a store extract of a vector type, this is
11429   // better to leave at float as we have more freedom in the addressing mode for
11430   // those.
11431   if (VectorTy->isFPOrFPVectorTy())
11432     return false;
11433
11434   // If the index is unknown at compile time, this is very expensive to lower
11435   // and it is not possible to combine the store with the extract.
11436   if (!isa<ConstantInt>(Idx))
11437     return false;
11438
11439   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11440   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11441   // We can do a store + vector extract on any vector that fits perfectly in a D
11442   // or Q register.
11443   if (BitWidth == 64 || BitWidth == 128) {
11444     Cost = 0;
11445     return true;
11446   }
11447   return false;
11448 }
11449
11450 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11451                                          AtomicOrdering Ord) const {
11452   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11453   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11454   bool IsAcquire = isAtLeastAcquire(Ord);
11455
11456   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11457   // intrinsic must return {i32, i32} and we have to recombine them into a
11458   // single i64 here.
11459   if (ValTy->getPrimitiveSizeInBits() == 64) {
11460     Intrinsic::ID Int =
11461         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11462     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11463
11464     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11465     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11466
11467     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11468     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11469     if (!Subtarget->isLittle())
11470       std::swap (Lo, Hi);
11471     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11472     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11473     return Builder.CreateOr(
11474         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11475   }
11476
11477   Type *Tys[] = { Addr->getType() };
11478   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11479   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11480
11481   return Builder.CreateTruncOrBitCast(
11482       Builder.CreateCall(Ldrex, Addr),
11483       cast<PointerType>(Addr->getType())->getElementType());
11484 }
11485
11486 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11487                                                Value *Addr,
11488                                                AtomicOrdering Ord) const {
11489   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11490   bool IsRelease = isAtLeastRelease(Ord);
11491
11492   // Since the intrinsics must have legal type, the i64 intrinsics take two
11493   // parameters: "i32, i32". We must marshal Val into the appropriate form
11494   // before the call.
11495   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11496     Intrinsic::ID Int =
11497         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11498     Function *Strex = Intrinsic::getDeclaration(M, Int);
11499     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11500
11501     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11502     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11503     if (!Subtarget->isLittle())
11504       std::swap (Lo, Hi);
11505     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11506     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11507   }
11508
11509   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11510   Type *Tys[] = { Addr->getType() };
11511   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11512
11513   return Builder.CreateCall(
11514       Strex, {Builder.CreateZExtOrBitCast(
11515                   Val, Strex->getFunctionType()->getParamType(0)),
11516               Addr});
11517 }
11518
11519 /// \brief Lower an interleaved load into a vldN intrinsic.
11520 ///
11521 /// E.g. Lower an interleaved load (Factor = 2):
11522 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11523 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11524 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11525 ///
11526 ///      Into:
11527 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11528 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11529 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11530 bool ARMTargetLowering::lowerInterleavedLoad(
11531     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11532     ArrayRef<unsigned> Indices, unsigned Factor) const {
11533   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11534          "Invalid interleave factor");
11535   assert(!Shuffles.empty() && "Empty shufflevector input");
11536   assert(Shuffles.size() == Indices.size() &&
11537          "Unmatched number of shufflevectors and indices");
11538
11539   VectorType *VecTy = Shuffles[0]->getType();
11540   Type *EltTy = VecTy->getVectorElementType();
11541
11542   const DataLayout &DL = LI->getModule()->getDataLayout();
11543   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11544   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11545
11546   // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11547   // support i64/f64 element).
11548   if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11549     return false;
11550
11551   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11552   // load integer vectors first and then convert to pointer vectors.
11553   if (EltTy->isPointerTy())
11554     VecTy =
11555         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11556
11557   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11558                                             Intrinsic::arm_neon_vld3,
11559                                             Intrinsic::arm_neon_vld4};
11560
11561   Function *VldnFunc =
11562       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11563
11564   IRBuilder<> Builder(LI);
11565   SmallVector<Value *, 2> Ops;
11566
11567   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11568   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11569   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11570
11571   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11572
11573   // Replace uses of each shufflevector with the corresponding vector loaded
11574   // by ldN.
11575   for (unsigned i = 0; i < Shuffles.size(); i++) {
11576     ShuffleVectorInst *SV = Shuffles[i];
11577     unsigned Index = Indices[i];
11578
11579     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11580
11581     // Convert the integer vector to pointer vector if the element is pointer.
11582     if (EltTy->isPointerTy())
11583       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11584
11585     SV->replaceAllUsesWith(SubVec);
11586   }
11587
11588   return true;
11589 }
11590
11591 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11592 ///
11593 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11594 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11595                                    unsigned NumElts) {
11596   SmallVector<Constant *, 16> Mask;
11597   for (unsigned i = 0; i < NumElts; i++)
11598     Mask.push_back(Builder.getInt32(Start + i));
11599
11600   return ConstantVector::get(Mask);
11601 }
11602
11603 /// \brief Lower an interleaved store into a vstN intrinsic.
11604 ///
11605 /// E.g. Lower an interleaved store (Factor = 3):
11606 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11607 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11608 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11609 ///
11610 ///      Into:
11611 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11612 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11613 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11614 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11615 ///
11616 /// Note that the new shufflevectors will be removed and we'll only generate one
11617 /// vst3 instruction in CodeGen.
11618 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11619                                               ShuffleVectorInst *SVI,
11620                                               unsigned Factor) const {
11621   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11622          "Invalid interleave factor");
11623
11624   VectorType *VecTy = SVI->getType();
11625   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11626          "Invalid interleaved store");
11627
11628   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11629   Type *EltTy = VecTy->getVectorElementType();
11630   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11631
11632   const DataLayout &DL = SI->getModule()->getDataLayout();
11633   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11634   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11635
11636   // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11637   // doesn't support i64/f64 element).
11638   if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11639     return false;
11640
11641   Value *Op0 = SVI->getOperand(0);
11642   Value *Op1 = SVI->getOperand(1);
11643   IRBuilder<> Builder(SI);
11644
11645   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11646   // vectors to integer vectors.
11647   if (EltTy->isPointerTy()) {
11648     Type *IntTy = DL.getIntPtrType(EltTy);
11649
11650     // Convert to the corresponding integer vector.
11651     Type *IntVecTy =
11652         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11653     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11654     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11655
11656     SubVecTy = VectorType::get(IntTy, NumSubElts);
11657   }
11658
11659   static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11660                                        Intrinsic::arm_neon_vst3,
11661                                        Intrinsic::arm_neon_vst4};
11662   Function *VstNFunc = Intrinsic::getDeclaration(
11663       SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11664
11665   SmallVector<Value *, 6> Ops;
11666
11667   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11668   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11669
11670   // Split the shufflevector operands into sub vectors for the new vstN call.
11671   for (unsigned i = 0; i < Factor; i++)
11672     Ops.push_back(Builder.CreateShuffleVector(
11673         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11674
11675   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11676   Builder.CreateCall(VstNFunc, Ops);
11677   return true;
11678 }
11679
11680 enum HABaseType {
11681   HA_UNKNOWN = 0,
11682   HA_FLOAT,
11683   HA_DOUBLE,
11684   HA_VECT64,
11685   HA_VECT128
11686 };
11687
11688 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11689                                    uint64_t &Members) {
11690   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11691     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11692       uint64_t SubMembers = 0;
11693       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11694         return false;
11695       Members += SubMembers;
11696     }
11697   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11698     uint64_t SubMembers = 0;
11699     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11700       return false;
11701     Members += SubMembers * AT->getNumElements();
11702   } else if (Ty->isFloatTy()) {
11703     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11704       return false;
11705     Members = 1;
11706     Base = HA_FLOAT;
11707   } else if (Ty->isDoubleTy()) {
11708     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11709       return false;
11710     Members = 1;
11711     Base = HA_DOUBLE;
11712   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11713     Members = 1;
11714     switch (Base) {
11715     case HA_FLOAT:
11716     case HA_DOUBLE:
11717       return false;
11718     case HA_VECT64:
11719       return VT->getBitWidth() == 64;
11720     case HA_VECT128:
11721       return VT->getBitWidth() == 128;
11722     case HA_UNKNOWN:
11723       switch (VT->getBitWidth()) {
11724       case 64:
11725         Base = HA_VECT64;
11726         return true;
11727       case 128:
11728         Base = HA_VECT128;
11729         return true;
11730       default:
11731         return false;
11732       }
11733     }
11734   }
11735
11736   return (Members > 0 && Members <= 4);
11737 }
11738
11739 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11740 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11741 /// passing according to AAPCS rules.
11742 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11743     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11744   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11745       CallingConv::ARM_AAPCS_VFP)
11746     return false;
11747
11748   HABaseType Base = HA_UNKNOWN;
11749   uint64_t Members = 0;
11750   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11751   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11752
11753   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11754   return IsHA || IsIntArray;
11755 }