[ARM] Minor refactoring. NFC.
[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   if (VT.isInteger()) {
147     setOperationAction(ISD::SABSDIFF, VT, Legal);
148     setOperationAction(ISD::UABSDIFF, VT, Legal);
149   }
150   if (!VT.isFloatingPoint() &&
151       VT != MVT::v2i64 && VT != MVT::v1i64)
152     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
153       setOperationAction(Opcode, VT, Legal);
154
155 }
156
157 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::DPRRegClass);
159   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
160 }
161
162 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
163   addRegisterClass(VT, &ARM::DPairRegClass);
164   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
165 }
166
167 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
168                                      const ARMSubtarget &STI)
169     : TargetLowering(TM), Subtarget(&STI) {
170   RegInfo = Subtarget->getRegisterInfo();
171   Itins = Subtarget->getInstrItineraryData();
172
173   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174
175   if (Subtarget->isTargetMachO()) {
176     // Uses VFP for Thumb libfuncs if available.
177     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
178         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
179       static const struct {
180         const RTLIB::Libcall Op;
181         const char * const Name;
182         const ISD::CondCode Cond;
183       } LibraryCalls[] = {
184         // Single-precision floating-point arithmetic.
185         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
186         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
187         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
188         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
189
190         // Double-precision floating-point arithmetic.
191         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
192         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
193         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
194         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
195
196         // Single-precision comparisons.
197         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
198         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
199         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
200         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
201         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
202         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
203         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
204         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
205
206         // Double-precision comparisons.
207         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
208         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
209         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
210         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
211         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
212         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
213         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
214         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
215
216         // Floating-point to integer conversions.
217         // i64 conversions are done via library routines even when generating VFP
218         // instructions, so use the same ones.
219         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
220         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
221         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
222         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
223
224         // Conversions between floating types.
225         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
226         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
227
228         // Integer to floating-point conversions.
229         // i64 conversions are done via library routines even when generating VFP
230         // instructions, so use the same ones.
231         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
232         // e.g., __floatunsidf vs. __floatunssidfvfp.
233         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
234         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
235         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
236         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
237       };
238
239       for (const auto &LC : LibraryCalls) {
240         setLibcallName(LC.Op, LC.Name);
241         if (LC.Cond != ISD::SETCC_INVALID)
242           setCmpLibcallCC(LC.Op, LC.Cond);
243       }
244     }
245   }
246
247   // These libcalls are not available in 32-bit.
248   setLibcallName(RTLIB::SHL_I128, nullptr);
249   setLibcallName(RTLIB::SRL_I128, nullptr);
250   setLibcallName(RTLIB::SRA_I128, nullptr);
251
252   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
253       !Subtarget->isTargetWindows()) {
254     static const struct {
255       const RTLIB::Libcall Op;
256       const char * const Name;
257       const CallingConv::ID CC;
258       const ISD::CondCode Cond;
259     } LibraryCalls[] = {
260       // Double-precision floating-point arithmetic helper functions
261       // RTABI chapter 4.1.2, Table 2
262       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
263       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
266
267       // Double-precision floating-point comparison helper functions
268       // RTABI chapter 4.1.2, Table 3
269       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
270       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
271       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
272       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
273       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
274       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
276       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
277
278       // Single-precision floating-point arithmetic helper functions
279       // RTABI chapter 4.1.2, Table 4
280       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
281       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
284
285       // Single-precision floating-point comparison helper functions
286       // RTABI chapter 4.1.2, Table 5
287       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
288       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
289       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
290       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
291       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
292       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
294       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
295
296       // Floating-point to integer conversions.
297       // RTABI chapter 4.1.2, Table 6
298       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306
307       // Conversions between floating types.
308       // RTABI chapter 4.1.2, Table 7
309       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312
313       // Integer to floating-point conversions.
314       // RTABI chapter 4.1.2, Table 8
315       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323
324       // Long long helper functions
325       // RTABI chapter 4.2, Table 9
326       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330
331       // Integer division functions
332       // RTABI chapter 4.3.1
333       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341
342       // Memory operations
343       // RTABI chapter 4.3.4
344       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347     };
348
349     for (const auto &LC : LibraryCalls) {
350       setLibcallName(LC.Op, LC.Name);
351       setLibcallCallingConv(LC.Op, LC.CC);
352       if (LC.Cond != ISD::SETCC_INVALID)
353         setCmpLibcallCC(LC.Op, LC.Cond);
354     }
355   }
356
357   if (Subtarget->isTargetWindows()) {
358     static const struct {
359       const RTLIB::Libcall Op;
360       const char * const Name;
361       const CallingConv::ID CC;
362     } LibraryCalls[] = {
363       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
364       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
366       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
367       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
371     };
372
373     for (const auto &LC : LibraryCalls) {
374       setLibcallName(LC.Op, LC.Name);
375       setLibcallCallingConv(LC.Op, LC.CC);
376     }
377   }
378
379   // Use divmod compiler-rt calls for iOS 5.0 and later.
380   if (Subtarget->getTargetTriple().isiOS() &&
381       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
382     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
383     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
384   }
385
386   // The half <-> float conversion functions are always soft-float, but are
387   // needed for some targets which use a hard-float calling convention by
388   // default.
389   if (Subtarget->isAAPCS_ABI()) {
390     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
393   } else {
394     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
395     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
396     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
397   }
398
399   if (Subtarget->isThumb1Only())
400     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
401   else
402     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
403   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
404       !Subtarget->isThumb1Only()) {
405     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
406     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
407   }
408
409   for (MVT VT : MVT::vector_valuetypes()) {
410     for (MVT InnerVT : MVT::vector_valuetypes()) {
411       setTruncStoreAction(VT, InnerVT, Expand);
412       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
413       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
414       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
415     }
416
417     setOperationAction(ISD::MULHS, VT, Expand);
418     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
419     setOperationAction(ISD::MULHU, VT, Expand);
420     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
421
422     setOperationAction(ISD::BSWAP, VT, Expand);
423   }
424
425   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
426   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
427
428   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
429   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
430
431   if (Subtarget->hasNEON()) {
432     addDRTypeForNEON(MVT::v2f32);
433     addDRTypeForNEON(MVT::v8i8);
434     addDRTypeForNEON(MVT::v4i16);
435     addDRTypeForNEON(MVT::v2i32);
436     addDRTypeForNEON(MVT::v1i64);
437
438     addQRTypeForNEON(MVT::v4f32);
439     addQRTypeForNEON(MVT::v2f64);
440     addQRTypeForNEON(MVT::v16i8);
441     addQRTypeForNEON(MVT::v8i16);
442     addQRTypeForNEON(MVT::v4i32);
443     addQRTypeForNEON(MVT::v2i64);
444
445     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
446     // neither Neon nor VFP support any arithmetic operations on it.
447     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
448     // supported for v4f32.
449     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
450     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
451     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
452     // FIXME: Code duplication: FDIV and FREM are expanded always, see
453     // ARMTargetLowering::addTypeForNEON method for details.
454     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
455     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
456     // FIXME: Create unittest.
457     // In another words, find a way when "copysign" appears in DAG with vector
458     // operands.
459     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
460     // FIXME: Code duplication: SETCC has custom operation action, see
461     // ARMTargetLowering::addTypeForNEON method for details.
462     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
463     // FIXME: Create unittest for FNEG and for FABS.
464     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
465     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
466     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
467     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
468     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
469     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
470     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
471     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
472     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
473     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
474     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
475     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
476     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
477     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
478     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
479     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
480     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
481     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
482     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
483
484     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
485     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
486     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
487     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
488     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
489     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
490     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
491     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
492     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
493     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
494     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
495     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
496     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
497     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
498     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
499
500     // Mark v2f32 intrinsics.
501     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
502     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
503     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
504     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
505     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
506     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
507     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
508     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
509     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
510     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
511     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
512     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
513     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
514     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
515     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
516
517     // Neon does not support some operations on v1i64 and v2i64 types.
518     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
519     // Custom handling for some quad-vector types to detect VMULL.
520     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
521     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
522     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
523     // Custom handling for some vector types to avoid expensive expansions
524     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
525     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
526     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
527     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
528     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
529     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
530     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
531     // a destination type that is wider than the source, and nor does
532     // it have a FP_TO_[SU]INT instruction with a narrower destination than
533     // source.
534     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
535     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
536     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
537     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
538
539     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
540     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
541
542     // NEON does not have single instruction CTPOP for vectors with element
543     // types wider than 8-bits.  However, custom lowering can leverage the
544     // v8i8/v16i8 vcnt instruction.
545     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
546     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
547     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
548     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
549
550     // NEON does not have single instruction CTTZ for vectors.
551     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
552     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
553     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
554     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
555
556     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
557     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
558     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
559     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
560
561     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
562     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
563     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
564     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
565
566     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
567     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
568     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
569     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
570
571     // NEON only has FMA instructions as of VFP4.
572     if (!Subtarget->hasVFP4()) {
573       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
574       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
575     }
576
577     setTargetDAGCombine(ISD::INTRINSIC_VOID);
578     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
579     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
580     setTargetDAGCombine(ISD::SHL);
581     setTargetDAGCombine(ISD::SRL);
582     setTargetDAGCombine(ISD::SRA);
583     setTargetDAGCombine(ISD::SIGN_EXTEND);
584     setTargetDAGCombine(ISD::ZERO_EXTEND);
585     setTargetDAGCombine(ISD::ANY_EXTEND);
586     setTargetDAGCombine(ISD::BUILD_VECTOR);
587     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
588     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
589     setTargetDAGCombine(ISD::STORE);
590     setTargetDAGCombine(ISD::FP_TO_SINT);
591     setTargetDAGCombine(ISD::FP_TO_UINT);
592     setTargetDAGCombine(ISD::FDIV);
593     setTargetDAGCombine(ISD::LOAD);
594
595     // It is legal to extload from v4i8 to v4i16 or v4i32.
596     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
597                    MVT::v2i32}) {
598       for (MVT VT : MVT::integer_vector_valuetypes()) {
599         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
600         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
601         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
602       }
603     }
604   }
605
606   // ARM and Thumb2 support UMLAL/SMLAL.
607   if (!Subtarget->isThumb1Only())
608     setTargetDAGCombine(ISD::ADDC);
609
610   if (Subtarget->isFPOnlySP()) {
611     // When targeting a floating-point unit with only single-precision
612     // operations, f64 is legal for the few double-precision instructions which
613     // are present However, no double-precision operations other than moves,
614     // loads and stores are provided by the hardware.
615     setOperationAction(ISD::FADD,       MVT::f64, Expand);
616     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
617     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
618     setOperationAction(ISD::FMA,        MVT::f64, Expand);
619     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
620     setOperationAction(ISD::FREM,       MVT::f64, Expand);
621     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
622     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
623     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
624     setOperationAction(ISD::FABS,       MVT::f64, Expand);
625     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
626     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
627     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
628     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
629     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
630     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
631     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
632     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
633     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
634     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
635     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
636     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
637     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
638     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
639     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
640     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
641     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
642     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
643     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
644     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
645     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
646     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
647     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
648   }
649
650   computeRegisterProperties(Subtarget->getRegisterInfo());
651
652   // ARM does not have floating-point extending loads.
653   for (MVT VT : MVT::fp_valuetypes()) {
654     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
655     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
656   }
657
658   // ... or truncating stores
659   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
660   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
661   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
662
663   // ARM does not have i1 sign extending load.
664   for (MVT VT : MVT::integer_valuetypes())
665     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
666
667   // ARM supports all 4 flavors of integer indexed load / store.
668   if (!Subtarget->isThumb1Only()) {
669     for (unsigned im = (unsigned)ISD::PRE_INC;
670          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
671       setIndexedLoadAction(im,  MVT::i1,  Legal);
672       setIndexedLoadAction(im,  MVT::i8,  Legal);
673       setIndexedLoadAction(im,  MVT::i16, Legal);
674       setIndexedLoadAction(im,  MVT::i32, Legal);
675       setIndexedStoreAction(im, MVT::i1,  Legal);
676       setIndexedStoreAction(im, MVT::i8,  Legal);
677       setIndexedStoreAction(im, MVT::i16, Legal);
678       setIndexedStoreAction(im, MVT::i32, Legal);
679     }
680   }
681
682   setOperationAction(ISD::SADDO, MVT::i32, Custom);
683   setOperationAction(ISD::UADDO, MVT::i32, Custom);
684   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
685   setOperationAction(ISD::USUBO, MVT::i32, Custom);
686
687   // i64 operation support.
688   setOperationAction(ISD::MUL,     MVT::i64, Expand);
689   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
690   if (Subtarget->isThumb1Only()) {
691     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
692     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
693   }
694   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
695       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
696     setOperationAction(ISD::MULHS, MVT::i32, Expand);
697
698   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
699   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
700   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
701   setOperationAction(ISD::SRL,       MVT::i64, Custom);
702   setOperationAction(ISD::SRA,       MVT::i64, Custom);
703
704   if (!Subtarget->isThumb1Only()) {
705     // FIXME: We should do this for Thumb1 as well.
706     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
707     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
708     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
709     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
710   }
711
712   // ARM does not have ROTL.
713   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
714   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
715   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
716   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
717     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
718
719   // These just redirect to CTTZ and CTLZ on ARM.
720   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
721   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
722
723   // @llvm.readcyclecounter requires the Performance Monitors extension.
724   // Default to the 0 expansion on unsupported platforms.
725   // FIXME: Technically there are older ARM CPUs that have
726   // implementation-specific ways of obtaining this information.
727   if (Subtarget->hasPerfMon())
728     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
729
730   // Only ARMv6 has BSWAP.
731   if (!Subtarget->hasV6Ops())
732     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
733
734   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
735       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
736     // These are expanded into libcalls if the cpu doesn't have HW divider.
737     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
738     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
739   }
740
741   if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
742     setOperationAction(ISD::SDIV, MVT::i32, Custom);
743     setOperationAction(ISD::UDIV, MVT::i32, Custom);
744
745     setOperationAction(ISD::SDIV, MVT::i64, Custom);
746     setOperationAction(ISD::UDIV, MVT::i64, Custom);
747   }
748
749   setOperationAction(ISD::SREM,  MVT::i32, Expand);
750   setOperationAction(ISD::UREM,  MVT::i32, Expand);
751   // Register based DivRem for AEABI (RTABI 4.2)
752   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
753     setOperationAction(ISD::SREM, MVT::i64, Custom);
754     setOperationAction(ISD::UREM, MVT::i64, Custom);
755
756     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
757     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
758     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
759     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
760     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
761     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
762     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
763     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
764
765     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
766     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
767     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
768     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
769     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
770     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
771     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
772     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
773
774     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
775     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
776   } else {
777     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
778     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
779   }
780
781   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
782   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
783   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
784   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
785   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
786
787   setOperationAction(ISD::TRAP, MVT::Other, Legal);
788
789   // Use the default implementation.
790   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
791   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
792   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
793   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
794   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
795   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
796
797   if (!Subtarget->isTargetMachO()) {
798     // Non-MachO platforms may return values in these registers via the
799     // personality function.
800     setExceptionPointerRegister(ARM::R0);
801     setExceptionSelectorRegister(ARM::R1);
802   }
803
804   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
805     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
806   else
807     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
808
809   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
810   // the default expansion. If we are targeting a single threaded system,
811   // then set them all for expand so we can lower them later into their
812   // non-atomic form.
813   if (TM.Options.ThreadModel == ThreadModel::Single)
814     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
815   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
816     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
817     // to ldrex/strex loops already.
818     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
819
820     // On v8, we have particularly efficient implementations of atomic fences
821     // if they can be combined with nearby atomic loads and stores.
822     if (!Subtarget->hasV8Ops()) {
823       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
824       setInsertFencesForAtomic(true);
825     }
826   } else {
827     // If there's anything we can use as a barrier, go through custom lowering
828     // for ATOMIC_FENCE.
829     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
830                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
831
832     // Set them all for expansion, which will force libcalls.
833     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
834     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
835     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
836     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
837     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
838     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
839     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
840     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
841     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
842     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
843     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
844     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
845     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
846     // Unordered/Monotonic case.
847     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
848     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
849   }
850
851   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
852
853   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
854   if (!Subtarget->hasV6Ops()) {
855     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
856     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
857   }
858   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
859
860   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
861       !Subtarget->isThumb1Only()) {
862     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
863     // iff target supports vfp2.
864     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
865     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
866   }
867
868   // We want to custom lower some of our intrinsics.
869   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
870   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
871   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
872   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
873   if (Subtarget->isTargetDarwin())
874     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
875
876   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
877   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
878   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
879   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
880   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
881   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
882   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
883   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
884   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
885
886   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
887   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
888   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
889   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
890   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
891
892   // We don't support sin/cos/fmod/copysign/pow
893   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
894   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
895   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
896   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
897   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
898   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
899   setOperationAction(ISD::FREM,      MVT::f64, Expand);
900   setOperationAction(ISD::FREM,      MVT::f32, Expand);
901   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
902       !Subtarget->isThumb1Only()) {
903     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
904     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
905   }
906   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
907   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
908
909   if (!Subtarget->hasVFP4()) {
910     setOperationAction(ISD::FMA, MVT::f64, Expand);
911     setOperationAction(ISD::FMA, MVT::f32, Expand);
912   }
913
914   // Various VFP goodness
915   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
916     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
917     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
918       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
919       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
920     }
921
922     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
923     if (!Subtarget->hasFP16()) {
924       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
925       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
926     }
927   }
928
929   // Combine sin / cos into one node or libcall if possible.
930   if (Subtarget->hasSinCos()) {
931     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
932     setLibcallName(RTLIB::SINCOS_F64, "sincos");
933     if (Subtarget->getTargetTriple().isiOS()) {
934       // For iOS, we don't want to the normal expansion of a libcall to
935       // sincos. We want to issue a libcall to __sincos_stret.
936       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
937       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
938     }
939   }
940
941   // FP-ARMv8 implements a lot of rounding-like FP operations.
942   if (Subtarget->hasFPARMv8()) {
943     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
944     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
945     setOperationAction(ISD::FROUND, MVT::f32, Legal);
946     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
947     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
948     setOperationAction(ISD::FRINT, MVT::f32, Legal);
949     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
950     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
951     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
952     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
953     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
954     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
955
956     if (!Subtarget->isFPOnlySP()) {
957       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
958       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
959       setOperationAction(ISD::FROUND, MVT::f64, Legal);
960       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
961       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
962       setOperationAction(ISD::FRINT, MVT::f64, Legal);
963       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
964       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
965     }
966   }
967
968   if (Subtarget->hasNEON()) {
969     // vmin and vmax aren't available in a scalar form, so we use
970     // a NEON instruction with an undef lane instead.
971     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
972     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
973     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
974     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
975     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
976     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
977   }
978
979   // We have target-specific dag combine patterns for the following nodes:
980   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
981   setTargetDAGCombine(ISD::ADD);
982   setTargetDAGCombine(ISD::SUB);
983   setTargetDAGCombine(ISD::MUL);
984   setTargetDAGCombine(ISD::AND);
985   setTargetDAGCombine(ISD::OR);
986   setTargetDAGCombine(ISD::XOR);
987
988   if (Subtarget->hasV6Ops())
989     setTargetDAGCombine(ISD::SRL);
990
991   setStackPointerRegisterToSaveRestore(ARM::SP);
992
993   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
994       !Subtarget->hasVFP2())
995     setSchedulingPreference(Sched::RegPressure);
996   else
997     setSchedulingPreference(Sched::Hybrid);
998
999   //// temporary - rewrite interface to use type
1000   MaxStoresPerMemset = 8;
1001   MaxStoresPerMemsetOptSize = 4;
1002   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1003   MaxStoresPerMemcpyOptSize = 2;
1004   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1005   MaxStoresPerMemmoveOptSize = 2;
1006
1007   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1008   // are at least 4 bytes aligned.
1009   setMinStackArgumentAlignment(4);
1010
1011   // Prefer likely predicted branches to selects on out-of-order cores.
1012   PredictableSelectIsExpensive = Subtarget->isLikeA9();
1013
1014   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1015 }
1016
1017 bool ARMTargetLowering::useSoftFloat() const {
1018   return Subtarget->useSoftFloat();
1019 }
1020
1021 // FIXME: It might make sense to define the representative register class as the
1022 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1023 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1024 // SPR's representative would be DPR_VFP2. This should work well if register
1025 // pressure tracking were modified such that a register use would increment the
1026 // pressure of the register class's representative and all of it's super
1027 // classes' representatives transitively. We have not implemented this because
1028 // of the difficulty prior to coalescing of modeling operand register classes
1029 // due to the common occurrence of cross class copies and subregister insertions
1030 // and extractions.
1031 std::pair<const TargetRegisterClass *, uint8_t>
1032 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1033                                            MVT VT) const {
1034   const TargetRegisterClass *RRC = nullptr;
1035   uint8_t Cost = 1;
1036   switch (VT.SimpleTy) {
1037   default:
1038     return TargetLowering::findRepresentativeClass(TRI, VT);
1039   // Use DPR as representative register class for all floating point
1040   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1041   // the cost is 1 for both f32 and f64.
1042   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1043   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1044     RRC = &ARM::DPRRegClass;
1045     // When NEON is used for SP, only half of the register file is available
1046     // because operations that define both SP and DP results will be constrained
1047     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1048     // coalescing by double-counting the SP regs. See the FIXME above.
1049     if (Subtarget->useNEONForSinglePrecisionFP())
1050       Cost = 2;
1051     break;
1052   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1053   case MVT::v4f32: case MVT::v2f64:
1054     RRC = &ARM::DPRRegClass;
1055     Cost = 2;
1056     break;
1057   case MVT::v4i64:
1058     RRC = &ARM::DPRRegClass;
1059     Cost = 4;
1060     break;
1061   case MVT::v8i64:
1062     RRC = &ARM::DPRRegClass;
1063     Cost = 8;
1064     break;
1065   }
1066   return std::make_pair(RRC, Cost);
1067 }
1068
1069 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1070   switch ((ARMISD::NodeType)Opcode) {
1071   case ARMISD::FIRST_NUMBER:  break;
1072   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1073   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1074   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1075   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1076   case ARMISD::CALL:          return "ARMISD::CALL";
1077   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1078   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1079   case ARMISD::tCALL:         return "ARMISD::tCALL";
1080   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1081   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1082   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1083   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1084   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1085   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1086   case ARMISD::CMP:           return "ARMISD::CMP";
1087   case ARMISD::CMN:           return "ARMISD::CMN";
1088   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1089   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1090   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1091   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1092   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1093
1094   case ARMISD::CMOV:          return "ARMISD::CMOV";
1095
1096   case ARMISD::RBIT:          return "ARMISD::RBIT";
1097
1098   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1099   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1100   case ARMISD::RRX:           return "ARMISD::RRX";
1101
1102   case ARMISD::ADDC:          return "ARMISD::ADDC";
1103   case ARMISD::ADDE:          return "ARMISD::ADDE";
1104   case ARMISD::SUBC:          return "ARMISD::SUBC";
1105   case ARMISD::SUBE:          return "ARMISD::SUBE";
1106
1107   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1108   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1109
1110   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1111   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1112   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1113
1114   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1115
1116   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1117
1118   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1119
1120   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1121
1122   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1123
1124   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1125   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1126
1127   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1128   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1129   case ARMISD::VCGE:          return "ARMISD::VCGE";
1130   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1131   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1132   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1133   case ARMISD::VCGT:          return "ARMISD::VCGT";
1134   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1135   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1136   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1137   case ARMISD::VTST:          return "ARMISD::VTST";
1138
1139   case ARMISD::VSHL:          return "ARMISD::VSHL";
1140   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1141   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1142   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1143   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1144   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1145   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1146   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1147   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1148   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1149   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1150   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1151   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1152   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1153   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1154   case ARMISD::VSLI:          return "ARMISD::VSLI";
1155   case ARMISD::VSRI:          return "ARMISD::VSRI";
1156   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1157   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1158   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1159   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1160   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1161   case ARMISD::VDUP:          return "ARMISD::VDUP";
1162   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1163   case ARMISD::VEXT:          return "ARMISD::VEXT";
1164   case ARMISD::VREV64:        return "ARMISD::VREV64";
1165   case ARMISD::VREV32:        return "ARMISD::VREV32";
1166   case ARMISD::VREV16:        return "ARMISD::VREV16";
1167   case ARMISD::VZIP:          return "ARMISD::VZIP";
1168   case ARMISD::VUZP:          return "ARMISD::VUZP";
1169   case ARMISD::VTRN:          return "ARMISD::VTRN";
1170   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1171   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1172   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1173   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1174   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1175   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1176   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1177   case ARMISD::BFI:           return "ARMISD::BFI";
1178   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1179   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1180   case ARMISD::VBSL:          return "ARMISD::VBSL";
1181   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1182   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1183   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1184   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1185   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1186   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1187   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1188   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1189   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1190   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1191   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1192   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1193   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1194   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1195   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1196   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1197   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1198   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1199   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1200   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1201   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1202   }
1203   return nullptr;
1204 }
1205
1206 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1207                                           EVT VT) const {
1208   if (!VT.isVector())
1209     return getPointerTy(DL);
1210   return VT.changeVectorElementTypeToInteger();
1211 }
1212
1213 /// getRegClassFor - Return the register class that should be used for the
1214 /// specified value type.
1215 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1216   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1217   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1218   // load / store 4 to 8 consecutive D registers.
1219   if (Subtarget->hasNEON()) {
1220     if (VT == MVT::v4i64)
1221       return &ARM::QQPRRegClass;
1222     if (VT == MVT::v8i64)
1223       return &ARM::QQQQPRRegClass;
1224   }
1225   return TargetLowering::getRegClassFor(VT);
1226 }
1227
1228 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1229 // source/dest is aligned and the copy size is large enough. We therefore want
1230 // to align such objects passed to memory intrinsics.
1231 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1232                                                unsigned &PrefAlign) const {
1233   if (!isa<MemIntrinsic>(CI))
1234     return false;
1235   MinSize = 8;
1236   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1237   // cycle faster than 4-byte aligned LDM.
1238   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1239   return true;
1240 }
1241
1242 // Create a fast isel object.
1243 FastISel *
1244 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1245                                   const TargetLibraryInfo *libInfo) const {
1246   return ARM::createFastISel(funcInfo, libInfo);
1247 }
1248
1249 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1250   unsigned NumVals = N->getNumValues();
1251   if (!NumVals)
1252     return Sched::RegPressure;
1253
1254   for (unsigned i = 0; i != NumVals; ++i) {
1255     EVT VT = N->getValueType(i);
1256     if (VT == MVT::Glue || VT == MVT::Other)
1257       continue;
1258     if (VT.isFloatingPoint() || VT.isVector())
1259       return Sched::ILP;
1260   }
1261
1262   if (!N->isMachineOpcode())
1263     return Sched::RegPressure;
1264
1265   // Load are scheduled for latency even if there instruction itinerary
1266   // is not available.
1267   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1268   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1269
1270   if (MCID.getNumDefs() == 0)
1271     return Sched::RegPressure;
1272   if (!Itins->isEmpty() &&
1273       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1274     return Sched::ILP;
1275
1276   return Sched::RegPressure;
1277 }
1278
1279 //===----------------------------------------------------------------------===//
1280 // Lowering Code
1281 //===----------------------------------------------------------------------===//
1282
1283 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1284 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1285   switch (CC) {
1286   default: llvm_unreachable("Unknown condition code!");
1287   case ISD::SETNE:  return ARMCC::NE;
1288   case ISD::SETEQ:  return ARMCC::EQ;
1289   case ISD::SETGT:  return ARMCC::GT;
1290   case ISD::SETGE:  return ARMCC::GE;
1291   case ISD::SETLT:  return ARMCC::LT;
1292   case ISD::SETLE:  return ARMCC::LE;
1293   case ISD::SETUGT: return ARMCC::HI;
1294   case ISD::SETUGE: return ARMCC::HS;
1295   case ISD::SETULT: return ARMCC::LO;
1296   case ISD::SETULE: return ARMCC::LS;
1297   }
1298 }
1299
1300 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1301 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1302                         ARMCC::CondCodes &CondCode2) {
1303   CondCode2 = ARMCC::AL;
1304   switch (CC) {
1305   default: llvm_unreachable("Unknown FP condition!");
1306   case ISD::SETEQ:
1307   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1308   case ISD::SETGT:
1309   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1310   case ISD::SETGE:
1311   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1312   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1313   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1314   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1315   case ISD::SETO:   CondCode = ARMCC::VC; break;
1316   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1317   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1318   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1319   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1320   case ISD::SETLT:
1321   case ISD::SETULT: CondCode = ARMCC::LT; break;
1322   case ISD::SETLE:
1323   case ISD::SETULE: CondCode = ARMCC::LE; break;
1324   case ISD::SETNE:
1325   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1326   }
1327 }
1328
1329 //===----------------------------------------------------------------------===//
1330 //                      Calling Convention Implementation
1331 //===----------------------------------------------------------------------===//
1332
1333 #include "ARMGenCallingConv.inc"
1334
1335 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1336 /// account presence of floating point hardware and calling convention
1337 /// limitations, such as support for variadic functions.
1338 CallingConv::ID
1339 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1340                                            bool isVarArg) const {
1341   switch (CC) {
1342   default:
1343     llvm_unreachable("Unsupported calling convention");
1344   case CallingConv::ARM_AAPCS:
1345   case CallingConv::ARM_APCS:
1346   case CallingConv::GHC:
1347     return CC;
1348   case CallingConv::ARM_AAPCS_VFP:
1349     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1350   case CallingConv::C:
1351     if (!Subtarget->isAAPCS_ABI())
1352       return CallingConv::ARM_APCS;
1353     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1354              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1355              !isVarArg)
1356       return CallingConv::ARM_AAPCS_VFP;
1357     else
1358       return CallingConv::ARM_AAPCS;
1359   case CallingConv::Fast:
1360     if (!Subtarget->isAAPCS_ABI()) {
1361       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1362         return CallingConv::Fast;
1363       return CallingConv::ARM_APCS;
1364     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1365       return CallingConv::ARM_AAPCS_VFP;
1366     else
1367       return CallingConv::ARM_AAPCS;
1368   }
1369 }
1370
1371 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1372 /// CallingConvention.
1373 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1374                                                  bool Return,
1375                                                  bool isVarArg) const {
1376   switch (getEffectiveCallingConv(CC, isVarArg)) {
1377   default:
1378     llvm_unreachable("Unsupported calling convention");
1379   case CallingConv::ARM_APCS:
1380     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1381   case CallingConv::ARM_AAPCS:
1382     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1383   case CallingConv::ARM_AAPCS_VFP:
1384     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1385   case CallingConv::Fast:
1386     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1387   case CallingConv::GHC:
1388     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1389   }
1390 }
1391
1392 /// LowerCallResult - Lower the result values of a call into the
1393 /// appropriate copies out of appropriate physical registers.
1394 SDValue
1395 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1396                                    CallingConv::ID CallConv, bool isVarArg,
1397                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1398                                    SDLoc dl, SelectionDAG &DAG,
1399                                    SmallVectorImpl<SDValue> &InVals,
1400                                    bool isThisReturn, SDValue ThisVal) const {
1401
1402   // Assign locations to each value returned by this call.
1403   SmallVector<CCValAssign, 16> RVLocs;
1404   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1405                     *DAG.getContext(), Call);
1406   CCInfo.AnalyzeCallResult(Ins,
1407                            CCAssignFnForNode(CallConv, /* Return*/ true,
1408                                              isVarArg));
1409
1410   // Copy all of the result registers out of their specified physreg.
1411   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1412     CCValAssign VA = RVLocs[i];
1413
1414     // Pass 'this' value directly from the argument to return value, to avoid
1415     // reg unit interference
1416     if (i == 0 && isThisReturn) {
1417       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1418              "unexpected return calling convention register assignment");
1419       InVals.push_back(ThisVal);
1420       continue;
1421     }
1422
1423     SDValue Val;
1424     if (VA.needsCustom()) {
1425       // Handle f64 or half of a v2f64.
1426       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1427                                       InFlag);
1428       Chain = Lo.getValue(1);
1429       InFlag = Lo.getValue(2);
1430       VA = RVLocs[++i]; // skip ahead to next loc
1431       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1432                                       InFlag);
1433       Chain = Hi.getValue(1);
1434       InFlag = Hi.getValue(2);
1435       if (!Subtarget->isLittle())
1436         std::swap (Lo, Hi);
1437       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1438
1439       if (VA.getLocVT() == MVT::v2f64) {
1440         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1441         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1442                           DAG.getConstant(0, dl, MVT::i32));
1443
1444         VA = RVLocs[++i]; // skip ahead to next loc
1445         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1446         Chain = Lo.getValue(1);
1447         InFlag = Lo.getValue(2);
1448         VA = RVLocs[++i]; // skip ahead to next loc
1449         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1450         Chain = Hi.getValue(1);
1451         InFlag = Hi.getValue(2);
1452         if (!Subtarget->isLittle())
1453           std::swap (Lo, Hi);
1454         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1455         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1456                           DAG.getConstant(1, dl, MVT::i32));
1457       }
1458     } else {
1459       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1460                                InFlag);
1461       Chain = Val.getValue(1);
1462       InFlag = Val.getValue(2);
1463     }
1464
1465     switch (VA.getLocInfo()) {
1466     default: llvm_unreachable("Unknown loc info!");
1467     case CCValAssign::Full: break;
1468     case CCValAssign::BCvt:
1469       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1470       break;
1471     }
1472
1473     InVals.push_back(Val);
1474   }
1475
1476   return Chain;
1477 }
1478
1479 /// LowerMemOpCallTo - Store the argument to the stack.
1480 SDValue
1481 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1482                                     SDValue StackPtr, SDValue Arg,
1483                                     SDLoc dl, SelectionDAG &DAG,
1484                                     const CCValAssign &VA,
1485                                     ISD::ArgFlagsTy Flags) const {
1486   unsigned LocMemOffset = VA.getLocMemOffset();
1487   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1488   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1489                        StackPtr, PtrOff);
1490   return DAG.getStore(
1491       Chain, dl, Arg, PtrOff,
1492       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1493       false, false, 0);
1494 }
1495
1496 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1497                                          SDValue Chain, SDValue &Arg,
1498                                          RegsToPassVector &RegsToPass,
1499                                          CCValAssign &VA, CCValAssign &NextVA,
1500                                          SDValue &StackPtr,
1501                                          SmallVectorImpl<SDValue> &MemOpChains,
1502                                          ISD::ArgFlagsTy Flags) const {
1503
1504   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1505                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1506   unsigned id = Subtarget->isLittle() ? 0 : 1;
1507   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1508
1509   if (NextVA.isRegLoc())
1510     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1511   else {
1512     assert(NextVA.isMemLoc());
1513     if (!StackPtr.getNode())
1514       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1515                                     getPointerTy(DAG.getDataLayout()));
1516
1517     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1518                                            dl, DAG, NextVA,
1519                                            Flags));
1520   }
1521 }
1522
1523 /// LowerCall - Lowering a call into a callseq_start <-
1524 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1525 /// nodes.
1526 SDValue
1527 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1528                              SmallVectorImpl<SDValue> &InVals) const {
1529   SelectionDAG &DAG                     = CLI.DAG;
1530   SDLoc &dl                             = CLI.DL;
1531   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1532   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1533   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1534   SDValue Chain                         = CLI.Chain;
1535   SDValue Callee                        = CLI.Callee;
1536   bool &isTailCall                      = CLI.IsTailCall;
1537   CallingConv::ID CallConv              = CLI.CallConv;
1538   bool doesNotRet                       = CLI.DoesNotReturn;
1539   bool isVarArg                         = CLI.IsVarArg;
1540
1541   MachineFunction &MF = DAG.getMachineFunction();
1542   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1543   bool isThisReturn   = false;
1544   bool isSibCall      = false;
1545   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1546
1547   // Disable tail calls if they're not supported.
1548   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1549     isTailCall = false;
1550
1551   if (isTailCall) {
1552     // Check if it's really possible to do a tail call.
1553     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1554                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1555                                                    Outs, OutVals, Ins, DAG);
1556     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1557       report_fatal_error("failed to perform tail call elimination on a call "
1558                          "site marked musttail");
1559     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1560     // detected sibcalls.
1561     if (isTailCall) {
1562       ++NumTailCalls;
1563       isSibCall = true;
1564     }
1565   }
1566
1567   // Analyze operands of the call, assigning locations to each operand.
1568   SmallVector<CCValAssign, 16> ArgLocs;
1569   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1570                     *DAG.getContext(), Call);
1571   CCInfo.AnalyzeCallOperands(Outs,
1572                              CCAssignFnForNode(CallConv, /* Return*/ false,
1573                                                isVarArg));
1574
1575   // Get a count of how many bytes are to be pushed on the stack.
1576   unsigned NumBytes = CCInfo.getNextStackOffset();
1577
1578   // For tail calls, memory operands are available in our caller's stack.
1579   if (isSibCall)
1580     NumBytes = 0;
1581
1582   // Adjust the stack pointer for the new arguments...
1583   // These operations are automatically eliminated by the prolog/epilog pass
1584   if (!isSibCall)
1585     Chain = DAG.getCALLSEQ_START(Chain,
1586                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1587
1588   SDValue StackPtr =
1589       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1590
1591   RegsToPassVector RegsToPass;
1592   SmallVector<SDValue, 8> MemOpChains;
1593
1594   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1595   // of tail call optimization, arguments are handled later.
1596   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1597        i != e;
1598        ++i, ++realArgIdx) {
1599     CCValAssign &VA = ArgLocs[i];
1600     SDValue Arg = OutVals[realArgIdx];
1601     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1602     bool isByVal = Flags.isByVal();
1603
1604     // Promote the value if needed.
1605     switch (VA.getLocInfo()) {
1606     default: llvm_unreachable("Unknown loc info!");
1607     case CCValAssign::Full: break;
1608     case CCValAssign::SExt:
1609       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1610       break;
1611     case CCValAssign::ZExt:
1612       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1613       break;
1614     case CCValAssign::AExt:
1615       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1616       break;
1617     case CCValAssign::BCvt:
1618       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1619       break;
1620     }
1621
1622     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1623     if (VA.needsCustom()) {
1624       if (VA.getLocVT() == MVT::v2f64) {
1625         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1626                                   DAG.getConstant(0, dl, MVT::i32));
1627         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1628                                   DAG.getConstant(1, dl, MVT::i32));
1629
1630         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1631                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1632
1633         VA = ArgLocs[++i]; // skip ahead to next loc
1634         if (VA.isRegLoc()) {
1635           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1636                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1637         } else {
1638           assert(VA.isMemLoc());
1639
1640           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1641                                                  dl, DAG, VA, Flags));
1642         }
1643       } else {
1644         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1645                          StackPtr, MemOpChains, Flags);
1646       }
1647     } else if (VA.isRegLoc()) {
1648       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1649         assert(VA.getLocVT() == MVT::i32 &&
1650                "unexpected calling convention register assignment");
1651         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1652                "unexpected use of 'returned'");
1653         isThisReturn = true;
1654       }
1655       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1656     } else if (isByVal) {
1657       assert(VA.isMemLoc());
1658       unsigned offset = 0;
1659
1660       // True if this byval aggregate will be split between registers
1661       // and memory.
1662       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1663       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1664
1665       if (CurByValIdx < ByValArgsCount) {
1666
1667         unsigned RegBegin, RegEnd;
1668         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1669
1670         EVT PtrVT =
1671             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1672         unsigned int i, j;
1673         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1674           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1675           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1676           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1677                                      MachinePointerInfo(),
1678                                      false, false, false,
1679                                      DAG.InferPtrAlignment(AddArg));
1680           MemOpChains.push_back(Load.getValue(1));
1681           RegsToPass.push_back(std::make_pair(j, Load));
1682         }
1683
1684         // If parameter size outsides register area, "offset" value
1685         // helps us to calculate stack slot for remained part properly.
1686         offset = RegEnd - RegBegin;
1687
1688         CCInfo.nextInRegsParam();
1689       }
1690
1691       if (Flags.getByValSize() > 4*offset) {
1692         auto PtrVT = getPointerTy(DAG.getDataLayout());
1693         unsigned LocMemOffset = VA.getLocMemOffset();
1694         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1695         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1696         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1697         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1698         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1699                                            MVT::i32);
1700         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1701                                             MVT::i32);
1702
1703         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1704         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1705         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1706                                           Ops));
1707       }
1708     } else if (!isSibCall) {
1709       assert(VA.isMemLoc());
1710
1711       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1712                                              dl, DAG, VA, Flags));
1713     }
1714   }
1715
1716   if (!MemOpChains.empty())
1717     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1718
1719   // Build a sequence of copy-to-reg nodes chained together with token chain
1720   // and flag operands which copy the outgoing args into the appropriate regs.
1721   SDValue InFlag;
1722   // Tail call byval lowering might overwrite argument registers so in case of
1723   // tail call optimization the copies to registers are lowered later.
1724   if (!isTailCall)
1725     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1726       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1727                                RegsToPass[i].second, InFlag);
1728       InFlag = Chain.getValue(1);
1729     }
1730
1731   // For tail calls lower the arguments to the 'real' stack slot.
1732   if (isTailCall) {
1733     // Force all the incoming stack arguments to be loaded from the stack
1734     // before any new outgoing arguments are stored to the stack, because the
1735     // outgoing stack slots may alias the incoming argument stack slots, and
1736     // the alias isn't otherwise explicit. This is slightly more conservative
1737     // than necessary, because it means that each store effectively depends
1738     // on every argument instead of just those arguments it would clobber.
1739
1740     // Do not flag preceding copytoreg stuff together with the following stuff.
1741     InFlag = SDValue();
1742     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1743       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1744                                RegsToPass[i].second, InFlag);
1745       InFlag = Chain.getValue(1);
1746     }
1747     InFlag = SDValue();
1748   }
1749
1750   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1751   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1752   // node so that legalize doesn't hack it.
1753   bool isDirect = false;
1754   bool isARMFunc = false;
1755   bool isLocalARMFunc = false;
1756   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1757   auto PtrVt = getPointerTy(DAG.getDataLayout());
1758
1759   if (Subtarget->genLongCalls()) {
1760     assert((Subtarget->isTargetWindows() ||
1761             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1762            "long-calls with non-static relocation model!");
1763     // Handle a global address or an external symbol. If it's not one of
1764     // those, the target's already in a register, so we don't need to do
1765     // anything extra.
1766     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1767       const GlobalValue *GV = G->getGlobal();
1768       // Create a constant pool entry for the callee address
1769       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1770       ARMConstantPoolValue *CPV =
1771         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1772
1773       // Get the address of the callee into a register
1774       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1775       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1776       Callee = DAG.getLoad(
1777           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1778           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1779           false, false, 0);
1780     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1781       const char *Sym = S->getSymbol();
1782
1783       // Create a constant pool entry for the callee address
1784       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1785       ARMConstantPoolValue *CPV =
1786         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1787                                       ARMPCLabelIndex, 0);
1788       // Get the address of the callee into a register
1789       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1790       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1791       Callee = DAG.getLoad(
1792           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1793           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1794           false, false, 0);
1795     }
1796   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1797     const GlobalValue *GV = G->getGlobal();
1798     isDirect = true;
1799     bool isDef = GV->isStrongDefinitionForLinker();
1800     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1801                    getTargetMachine().getRelocationModel() != Reloc::Static;
1802     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1803     // ARM call to a local ARM function is predicable.
1804     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1805     // tBX takes a register source operand.
1806     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1807       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1808       Callee = DAG.getNode(
1809           ARMISD::WrapperPIC, dl, PtrVt,
1810           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1811       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1812                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1813                            false, false, true, 0);
1814     } else if (Subtarget->isTargetCOFF()) {
1815       assert(Subtarget->isTargetWindows() &&
1816              "Windows is the only supported COFF target");
1817       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1818                                  ? ARMII::MO_DLLIMPORT
1819                                  : ARMII::MO_NO_FLAG;
1820       Callee =
1821           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1822       if (GV->hasDLLImportStorageClass())
1823         Callee =
1824             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1825                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1826                         MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1827                         false, false, false, 0);
1828     } else {
1829       // On ELF targets for PIC code, direct calls should go through the PLT
1830       unsigned OpFlags = 0;
1831       if (Subtarget->isTargetELF() &&
1832           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1833         OpFlags = ARMII::MO_PLT;
1834       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1835     }
1836   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1837     isDirect = true;
1838     bool isStub = Subtarget->isTargetMachO() &&
1839                   getTargetMachine().getRelocationModel() != Reloc::Static;
1840     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1841     // tBX takes a register source operand.
1842     const char *Sym = S->getSymbol();
1843     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1844       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1845       ARMConstantPoolValue *CPV =
1846         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1847                                       ARMPCLabelIndex, 4);
1848       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1849       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1850       Callee = DAG.getLoad(
1851           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1852           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1853           false, false, 0);
1854       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1855       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1856     } else {
1857       unsigned OpFlags = 0;
1858       // On ELF targets for PIC code, direct calls should go through the PLT
1859       if (Subtarget->isTargetELF() &&
1860                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1861         OpFlags = ARMII::MO_PLT;
1862       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1863     }
1864   }
1865
1866   // FIXME: handle tail calls differently.
1867   unsigned CallOpc;
1868   if (Subtarget->isThumb()) {
1869     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1870       CallOpc = ARMISD::CALL_NOLINK;
1871     else
1872       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1873   } else {
1874     if (!isDirect && !Subtarget->hasV5TOps())
1875       CallOpc = ARMISD::CALL_NOLINK;
1876     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1877              // Emit regular call when code size is the priority
1878              !MF.getFunction()->optForMinSize())
1879       // "mov lr, pc; b _foo" to avoid confusing the RSP
1880       CallOpc = ARMISD::CALL_NOLINK;
1881     else
1882       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1883   }
1884
1885   std::vector<SDValue> Ops;
1886   Ops.push_back(Chain);
1887   Ops.push_back(Callee);
1888
1889   // Add argument registers to the end of the list so that they are known live
1890   // into the call.
1891   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1892     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1893                                   RegsToPass[i].second.getValueType()));
1894
1895   // Add a register mask operand representing the call-preserved registers.
1896   if (!isTailCall) {
1897     const uint32_t *Mask;
1898     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1899     if (isThisReturn) {
1900       // For 'this' returns, use the R0-preserving mask if applicable
1901       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1902       if (!Mask) {
1903         // Set isThisReturn to false if the calling convention is not one that
1904         // allows 'returned' to be modeled in this way, so LowerCallResult does
1905         // not try to pass 'this' straight through
1906         isThisReturn = false;
1907         Mask = ARI->getCallPreservedMask(MF, CallConv);
1908       }
1909     } else
1910       Mask = ARI->getCallPreservedMask(MF, CallConv);
1911
1912     assert(Mask && "Missing call preserved mask for calling convention");
1913     Ops.push_back(DAG.getRegisterMask(Mask));
1914   }
1915
1916   if (InFlag.getNode())
1917     Ops.push_back(InFlag);
1918
1919   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1920   if (isTailCall) {
1921     MF.getFrameInfo()->setHasTailCall();
1922     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1923   }
1924
1925   // Returns a chain and a flag for retval copy to use.
1926   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1927   InFlag = Chain.getValue(1);
1928
1929   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1930                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1931   if (!Ins.empty())
1932     InFlag = Chain.getValue(1);
1933
1934   // Handle result values, copying them out of physregs into vregs that we
1935   // return.
1936   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1937                          InVals, isThisReturn,
1938                          isThisReturn ? OutVals[0] : SDValue());
1939 }
1940
1941 /// HandleByVal - Every parameter *after* a byval parameter is passed
1942 /// on the stack.  Remember the next parameter register to allocate,
1943 /// and then confiscate the rest of the parameter registers to insure
1944 /// this.
1945 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1946                                     unsigned Align) const {
1947   assert((State->getCallOrPrologue() == Prologue ||
1948           State->getCallOrPrologue() == Call) &&
1949          "unhandled ParmContext");
1950
1951   // Byval (as with any stack) slots are always at least 4 byte aligned.
1952   Align = std::max(Align, 4U);
1953
1954   unsigned Reg = State->AllocateReg(GPRArgRegs);
1955   if (!Reg)
1956     return;
1957
1958   unsigned AlignInRegs = Align / 4;
1959   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1960   for (unsigned i = 0; i < Waste; ++i)
1961     Reg = State->AllocateReg(GPRArgRegs);
1962
1963   if (!Reg)
1964     return;
1965
1966   unsigned Excess = 4 * (ARM::R4 - Reg);
1967
1968   // Special case when NSAA != SP and parameter size greater than size of
1969   // all remained GPR regs. In that case we can't split parameter, we must
1970   // send it to stack. We also must set NCRN to R4, so waste all
1971   // remained registers.
1972   const unsigned NSAAOffset = State->getNextStackOffset();
1973   if (NSAAOffset != 0 && Size > Excess) {
1974     while (State->AllocateReg(GPRArgRegs))
1975       ;
1976     return;
1977   }
1978
1979   // First register for byval parameter is the first register that wasn't
1980   // allocated before this method call, so it would be "reg".
1981   // If parameter is small enough to be saved in range [reg, r4), then
1982   // the end (first after last) register would be reg + param-size-in-regs,
1983   // else parameter would be splitted between registers and stack,
1984   // end register would be r4 in this case.
1985   unsigned ByValRegBegin = Reg;
1986   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1987   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1988   // Note, first register is allocated in the beginning of function already,
1989   // allocate remained amount of registers we need.
1990   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1991     State->AllocateReg(GPRArgRegs);
1992   // A byval parameter that is split between registers and memory needs its
1993   // size truncated here.
1994   // In the case where the entire structure fits in registers, we set the
1995   // size in memory to zero.
1996   Size = std::max<int>(Size - Excess, 0);
1997 }
1998
1999 /// MatchingStackOffset - Return true if the given stack call argument is
2000 /// already available in the same position (relatively) of the caller's
2001 /// incoming argument stack.
2002 static
2003 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2004                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2005                          const TargetInstrInfo *TII) {
2006   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2007   int FI = INT_MAX;
2008   if (Arg.getOpcode() == ISD::CopyFromReg) {
2009     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2010     if (!TargetRegisterInfo::isVirtualRegister(VR))
2011       return false;
2012     MachineInstr *Def = MRI->getVRegDef(VR);
2013     if (!Def)
2014       return false;
2015     if (!Flags.isByVal()) {
2016       if (!TII->isLoadFromStackSlot(Def, FI))
2017         return false;
2018     } else {
2019       return false;
2020     }
2021   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2022     if (Flags.isByVal())
2023       // ByVal argument is passed in as a pointer but it's now being
2024       // dereferenced. e.g.
2025       // define @foo(%struct.X* %A) {
2026       //   tail call @bar(%struct.X* byval %A)
2027       // }
2028       return false;
2029     SDValue Ptr = Ld->getBasePtr();
2030     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2031     if (!FINode)
2032       return false;
2033     FI = FINode->getIndex();
2034   } else
2035     return false;
2036
2037   assert(FI != INT_MAX);
2038   if (!MFI->isFixedObjectIndex(FI))
2039     return false;
2040   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2041 }
2042
2043 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2044 /// for tail call optimization. Targets which want to do tail call
2045 /// optimization should implement this function.
2046 bool
2047 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2048                                                      CallingConv::ID CalleeCC,
2049                                                      bool isVarArg,
2050                                                      bool isCalleeStructRet,
2051                                                      bool isCallerStructRet,
2052                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2053                                     const SmallVectorImpl<SDValue> &OutVals,
2054                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2055                                                      SelectionDAG& DAG) const {
2056   const Function *CallerF = DAG.getMachineFunction().getFunction();
2057   CallingConv::ID CallerCC = CallerF->getCallingConv();
2058   bool CCMatch = CallerCC == CalleeCC;
2059
2060   assert(Subtarget->supportsTailCall());
2061
2062   // Look for obvious safe cases to perform tail call optimization that do not
2063   // require ABI changes. This is what gcc calls sibcall.
2064
2065   // Do not sibcall optimize vararg calls unless the call site is not passing
2066   // any arguments.
2067   if (isVarArg && !Outs.empty())
2068     return false;
2069
2070   // Exception-handling functions need a special set of instructions to indicate
2071   // a return to the hardware. Tail-calling another function would probably
2072   // break this.
2073   if (CallerF->hasFnAttribute("interrupt"))
2074     return false;
2075
2076   // Also avoid sibcall optimization if either caller or callee uses struct
2077   // return semantics.
2078   if (isCalleeStructRet || isCallerStructRet)
2079     return false;
2080
2081   // Externally-defined functions with weak linkage should not be
2082   // tail-called on ARM when the OS does not support dynamic
2083   // pre-emption of symbols, as the AAELF spec requires normal calls
2084   // to undefined weak functions to be replaced with a NOP or jump to the
2085   // next instruction. The behaviour of branch instructions in this
2086   // situation (as used for tail calls) is implementation-defined, so we
2087   // cannot rely on the linker replacing the tail call with a return.
2088   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2089     const GlobalValue *GV = G->getGlobal();
2090     const Triple &TT = getTargetMachine().getTargetTriple();
2091     if (GV->hasExternalWeakLinkage() &&
2092         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2093       return false;
2094   }
2095
2096   // If the calling conventions do not match, then we'd better make sure the
2097   // results are returned in the same way as what the caller expects.
2098   if (!CCMatch) {
2099     SmallVector<CCValAssign, 16> RVLocs1;
2100     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2101                        *DAG.getContext(), Call);
2102     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2103
2104     SmallVector<CCValAssign, 16> RVLocs2;
2105     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2106                        *DAG.getContext(), Call);
2107     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2108
2109     if (RVLocs1.size() != RVLocs2.size())
2110       return false;
2111     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2112       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2113         return false;
2114       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2115         return false;
2116       if (RVLocs1[i].isRegLoc()) {
2117         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2118           return false;
2119       } else {
2120         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2121           return false;
2122       }
2123     }
2124   }
2125
2126   // If Caller's vararg or byval argument has been split between registers and
2127   // stack, do not perform tail call, since part of the argument is in caller's
2128   // local frame.
2129   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2130                                       getInfo<ARMFunctionInfo>();
2131   if (AFI_Caller->getArgRegsSaveSize())
2132     return false;
2133
2134   // If the callee takes no arguments then go on to check the results of the
2135   // call.
2136   if (!Outs.empty()) {
2137     // Check if stack adjustment is needed. For now, do not do this if any
2138     // argument is passed on the stack.
2139     SmallVector<CCValAssign, 16> ArgLocs;
2140     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2141                       *DAG.getContext(), Call);
2142     CCInfo.AnalyzeCallOperands(Outs,
2143                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2144     if (CCInfo.getNextStackOffset()) {
2145       MachineFunction &MF = DAG.getMachineFunction();
2146
2147       // Check if the arguments are already laid out in the right way as
2148       // the caller's fixed stack objects.
2149       MachineFrameInfo *MFI = MF.getFrameInfo();
2150       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2151       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2152       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2153            i != e;
2154            ++i, ++realArgIdx) {
2155         CCValAssign &VA = ArgLocs[i];
2156         EVT RegVT = VA.getLocVT();
2157         SDValue Arg = OutVals[realArgIdx];
2158         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2159         if (VA.getLocInfo() == CCValAssign::Indirect)
2160           return false;
2161         if (VA.needsCustom()) {
2162           // f64 and vector types are split into multiple registers or
2163           // register/stack-slot combinations.  The types will not match
2164           // the registers; give up on memory f64 refs until we figure
2165           // out what to do about this.
2166           if (!VA.isRegLoc())
2167             return false;
2168           if (!ArgLocs[++i].isRegLoc())
2169             return false;
2170           if (RegVT == MVT::v2f64) {
2171             if (!ArgLocs[++i].isRegLoc())
2172               return false;
2173             if (!ArgLocs[++i].isRegLoc())
2174               return false;
2175           }
2176         } else if (!VA.isRegLoc()) {
2177           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2178                                    MFI, MRI, TII))
2179             return false;
2180         }
2181       }
2182     }
2183   }
2184
2185   return true;
2186 }
2187
2188 bool
2189 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2190                                   MachineFunction &MF, bool isVarArg,
2191                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2192                                   LLVMContext &Context) const {
2193   SmallVector<CCValAssign, 16> RVLocs;
2194   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2195   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2196                                                     isVarArg));
2197 }
2198
2199 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2200                                     SDLoc DL, SelectionDAG &DAG) {
2201   const MachineFunction &MF = DAG.getMachineFunction();
2202   const Function *F = MF.getFunction();
2203
2204   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2205
2206   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2207   // version of the "preferred return address". These offsets affect the return
2208   // instruction if this is a return from PL1 without hypervisor extensions.
2209   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2210   //    SWI:     0      "subs pc, lr, #0"
2211   //    ABORT:   +4     "subs pc, lr, #4"
2212   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2213   // UNDEF varies depending on where the exception came from ARM or Thumb
2214   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2215
2216   int64_t LROffset;
2217   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2218       IntKind == "ABORT")
2219     LROffset = 4;
2220   else if (IntKind == "SWI" || IntKind == "UNDEF")
2221     LROffset = 0;
2222   else
2223     report_fatal_error("Unsupported interrupt attribute. If present, value "
2224                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2225
2226   RetOps.insert(RetOps.begin() + 1,
2227                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2228
2229   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2230 }
2231
2232 SDValue
2233 ARMTargetLowering::LowerReturn(SDValue Chain,
2234                                CallingConv::ID CallConv, bool isVarArg,
2235                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2236                                const SmallVectorImpl<SDValue> &OutVals,
2237                                SDLoc dl, SelectionDAG &DAG) const {
2238
2239   // CCValAssign - represent the assignment of the return value to a location.
2240   SmallVector<CCValAssign, 16> RVLocs;
2241
2242   // CCState - Info about the registers and stack slots.
2243   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2244                     *DAG.getContext(), Call);
2245
2246   // Analyze outgoing return values.
2247   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2248                                                isVarArg));
2249
2250   SDValue Flag;
2251   SmallVector<SDValue, 4> RetOps;
2252   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2253   bool isLittleEndian = Subtarget->isLittle();
2254
2255   MachineFunction &MF = DAG.getMachineFunction();
2256   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2257   AFI->setReturnRegsCount(RVLocs.size());
2258
2259   // Copy the result values into the output registers.
2260   for (unsigned i = 0, realRVLocIdx = 0;
2261        i != RVLocs.size();
2262        ++i, ++realRVLocIdx) {
2263     CCValAssign &VA = RVLocs[i];
2264     assert(VA.isRegLoc() && "Can only return in registers!");
2265
2266     SDValue Arg = OutVals[realRVLocIdx];
2267
2268     switch (VA.getLocInfo()) {
2269     default: llvm_unreachable("Unknown loc info!");
2270     case CCValAssign::Full: break;
2271     case CCValAssign::BCvt:
2272       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2273       break;
2274     }
2275
2276     if (VA.needsCustom()) {
2277       if (VA.getLocVT() == MVT::v2f64) {
2278         // Extract the first half and return it in two registers.
2279         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2280                                    DAG.getConstant(0, dl, MVT::i32));
2281         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2282                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2283
2284         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2285                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2286                                  Flag);
2287         Flag = Chain.getValue(1);
2288         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2289         VA = RVLocs[++i]; // skip ahead to next loc
2290         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2291                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2292                                  Flag);
2293         Flag = Chain.getValue(1);
2294         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2295         VA = RVLocs[++i]; // skip ahead to next loc
2296
2297         // Extract the 2nd half and fall through to handle it as an f64 value.
2298         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2299                           DAG.getConstant(1, dl, MVT::i32));
2300       }
2301       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2302       // available.
2303       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2304                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2305       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2306                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2307                                Flag);
2308       Flag = Chain.getValue(1);
2309       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2310       VA = RVLocs[++i]; // skip ahead to next loc
2311       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2312                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2313                                Flag);
2314     } else
2315       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2316
2317     // Guarantee that all emitted copies are
2318     // stuck together, avoiding something bad.
2319     Flag = Chain.getValue(1);
2320     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2321   }
2322
2323   // Update chain and glue.
2324   RetOps[0] = Chain;
2325   if (Flag.getNode())
2326     RetOps.push_back(Flag);
2327
2328   // CPUs which aren't M-class use a special sequence to return from
2329   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2330   // though we use "subs pc, lr, #N").
2331   //
2332   // M-class CPUs actually use a normal return sequence with a special
2333   // (hardware-provided) value in LR, so the normal code path works.
2334   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2335       !Subtarget->isMClass()) {
2336     if (Subtarget->isThumb1Only())
2337       report_fatal_error("interrupt attribute is not supported in Thumb1");
2338     return LowerInterruptReturn(RetOps, dl, DAG);
2339   }
2340
2341   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2342 }
2343
2344 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2345   if (N->getNumValues() != 1)
2346     return false;
2347   if (!N->hasNUsesOfValue(1, 0))
2348     return false;
2349
2350   SDValue TCChain = Chain;
2351   SDNode *Copy = *N->use_begin();
2352   if (Copy->getOpcode() == ISD::CopyToReg) {
2353     // If the copy has a glue operand, we conservatively assume it isn't safe to
2354     // perform a tail call.
2355     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2356       return false;
2357     TCChain = Copy->getOperand(0);
2358   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2359     SDNode *VMov = Copy;
2360     // f64 returned in a pair of GPRs.
2361     SmallPtrSet<SDNode*, 2> Copies;
2362     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2363          UI != UE; ++UI) {
2364       if (UI->getOpcode() != ISD::CopyToReg)
2365         return false;
2366       Copies.insert(*UI);
2367     }
2368     if (Copies.size() > 2)
2369       return false;
2370
2371     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2372          UI != UE; ++UI) {
2373       SDValue UseChain = UI->getOperand(0);
2374       if (Copies.count(UseChain.getNode()))
2375         // Second CopyToReg
2376         Copy = *UI;
2377       else {
2378         // We are at the top of this chain.
2379         // If the copy has a glue operand, we conservatively assume it
2380         // isn't safe to perform a tail call.
2381         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2382           return false;
2383         // First CopyToReg
2384         TCChain = UseChain;
2385       }
2386     }
2387   } else if (Copy->getOpcode() == ISD::BITCAST) {
2388     // f32 returned in a single GPR.
2389     if (!Copy->hasOneUse())
2390       return false;
2391     Copy = *Copy->use_begin();
2392     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2393       return false;
2394     // If the copy has a glue operand, we conservatively assume it isn't safe to
2395     // perform a tail call.
2396     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2397       return false;
2398     TCChain = Copy->getOperand(0);
2399   } else {
2400     return false;
2401   }
2402
2403   bool HasRet = false;
2404   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2405        UI != UE; ++UI) {
2406     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2407         UI->getOpcode() != ARMISD::INTRET_FLAG)
2408       return false;
2409     HasRet = true;
2410   }
2411
2412   if (!HasRet)
2413     return false;
2414
2415   Chain = TCChain;
2416   return true;
2417 }
2418
2419 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2420   if (!Subtarget->supportsTailCall())
2421     return false;
2422
2423   auto Attr =
2424       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2425   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2426     return false;
2427
2428   return true;
2429 }
2430
2431 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2432 // and pass the lower and high parts through.
2433 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2434   SDLoc DL(Op);
2435   SDValue WriteValue = Op->getOperand(2);
2436
2437   // This function is only supposed to be called for i64 type argument.
2438   assert(WriteValue.getValueType() == MVT::i64
2439           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2440
2441   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2442                            DAG.getConstant(0, DL, MVT::i32));
2443   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2444                            DAG.getConstant(1, DL, MVT::i32));
2445   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2446   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2447 }
2448
2449 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2450 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2451 // one of the above mentioned nodes. It has to be wrapped because otherwise
2452 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2453 // be used to form addressing mode. These wrapped nodes will be selected
2454 // into MOVi.
2455 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2456   EVT PtrVT = Op.getValueType();
2457   // FIXME there is no actual debug info here
2458   SDLoc dl(Op);
2459   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2460   SDValue Res;
2461   if (CP->isMachineConstantPoolEntry())
2462     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2463                                     CP->getAlignment());
2464   else
2465     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2466                                     CP->getAlignment());
2467   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2468 }
2469
2470 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2471   return MachineJumpTableInfo::EK_Inline;
2472 }
2473
2474 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2475                                              SelectionDAG &DAG) const {
2476   MachineFunction &MF = DAG.getMachineFunction();
2477   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2478   unsigned ARMPCLabelIndex = 0;
2479   SDLoc DL(Op);
2480   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2481   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2482   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2483   SDValue CPAddr;
2484   if (RelocM == Reloc::Static) {
2485     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2486   } else {
2487     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2488     ARMPCLabelIndex = AFI->createPICLabelUId();
2489     ARMConstantPoolValue *CPV =
2490       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2491                                       ARMCP::CPBlockAddress, PCAdj);
2492     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2493   }
2494   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2495   SDValue Result =
2496       DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2497                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2498                   false, false, false, 0);
2499   if (RelocM == Reloc::Static)
2500     return Result;
2501   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2502   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2503 }
2504
2505 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2506 SDValue
2507 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2508                                                  SelectionDAG &DAG) const {
2509   SDLoc dl(GA);
2510   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2511   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2512   MachineFunction &MF = DAG.getMachineFunction();
2513   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2514   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2515   ARMConstantPoolValue *CPV =
2516     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2517                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2518   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2519   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2520   Argument =
2521       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2522                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2523                   false, false, false, 0);
2524   SDValue Chain = Argument.getValue(1);
2525
2526   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2527   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2528
2529   // call __tls_get_addr.
2530   ArgListTy Args;
2531   ArgListEntry Entry;
2532   Entry.Node = Argument;
2533   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2534   Args.push_back(Entry);
2535
2536   // FIXME: is there useful debug info available here?
2537   TargetLowering::CallLoweringInfo CLI(DAG);
2538   CLI.setDebugLoc(dl).setChain(Chain)
2539     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2540                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2541                0);
2542
2543   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2544   return CallResult.first;
2545 }
2546
2547 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2548 // "local exec" model.
2549 SDValue
2550 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2551                                         SelectionDAG &DAG,
2552                                         TLSModel::Model model) const {
2553   const GlobalValue *GV = GA->getGlobal();
2554   SDLoc dl(GA);
2555   SDValue Offset;
2556   SDValue Chain = DAG.getEntryNode();
2557   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2558   // Get the Thread Pointer
2559   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2560
2561   if (model == TLSModel::InitialExec) {
2562     MachineFunction &MF = DAG.getMachineFunction();
2563     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2564     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2565     // Initial exec model.
2566     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2567     ARMConstantPoolValue *CPV =
2568       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2569                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2570                                       true);
2571     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2572     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2573     Offset = DAG.getLoad(
2574         PtrVT, dl, Chain, Offset,
2575         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2576         false, false, 0);
2577     Chain = Offset.getValue(1);
2578
2579     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2580     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2581
2582     Offset = DAG.getLoad(
2583         PtrVT, dl, Chain, Offset,
2584         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2585         false, false, 0);
2586   } else {
2587     // local exec model
2588     assert(model == TLSModel::LocalExec);
2589     ARMConstantPoolValue *CPV =
2590       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2591     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2592     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2593     Offset = DAG.getLoad(
2594         PtrVT, dl, Chain, Offset,
2595         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2596         false, false, 0);
2597   }
2598
2599   // The address of the thread local variable is the add of the thread
2600   // pointer with the offset of the variable.
2601   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2602 }
2603
2604 SDValue
2605 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2606   // TODO: implement the "local dynamic" model
2607   assert(Subtarget->isTargetELF() &&
2608          "TLS not implemented for non-ELF targets");
2609   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2610   if (DAG.getTarget().Options.EmulatedTLS)
2611     return LowerToTLSEmulatedModel(GA, DAG);
2612
2613   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2614
2615   switch (model) {
2616     case TLSModel::GeneralDynamic:
2617     case TLSModel::LocalDynamic:
2618       return LowerToTLSGeneralDynamicModel(GA, DAG);
2619     case TLSModel::InitialExec:
2620     case TLSModel::LocalExec:
2621       return LowerToTLSExecModels(GA, DAG, model);
2622   }
2623   llvm_unreachable("bogus TLS model");
2624 }
2625
2626 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2627                                                  SelectionDAG &DAG) const {
2628   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2629   SDLoc dl(Op);
2630   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2631   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2632     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2633     ARMConstantPoolValue *CPV =
2634       ARMConstantPoolConstant::Create(GV,
2635                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2636     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2637     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2638     SDValue Result = DAG.getLoad(
2639         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2640         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2641         false, false, 0);
2642     SDValue Chain = Result.getValue(1);
2643     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2644     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2645     if (!UseGOTOFF)
2646       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2647                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2648                            false, false, false, 0);
2649     return Result;
2650   }
2651
2652   // If we have T2 ops, we can materialize the address directly via movt/movw
2653   // pair. This is always cheaper.
2654   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2655     ++NumMovwMovt;
2656     // FIXME: Once remat is capable of dealing with instructions with register
2657     // operands, expand this into two nodes.
2658     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2659                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2660   } else {
2661     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2662     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2663     return DAG.getLoad(
2664         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2665         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2666         false, false, 0);
2667   }
2668 }
2669
2670 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2671                                                     SelectionDAG &DAG) const {
2672   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2673   SDLoc dl(Op);
2674   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2675   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2676
2677   if (Subtarget->useMovt(DAG.getMachineFunction()))
2678     ++NumMovwMovt;
2679
2680   // FIXME: Once remat is capable of dealing with instructions with register
2681   // operands, expand this into multiple nodes
2682   unsigned Wrapper =
2683       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2684
2685   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2686   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2687
2688   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2689     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2690                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2691                          false, false, false, 0);
2692   return Result;
2693 }
2694
2695 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2696                                                      SelectionDAG &DAG) const {
2697   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2698   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2699          "Windows on ARM expects to use movw/movt");
2700
2701   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2702   const ARMII::TOF TargetFlags =
2703     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2704   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2705   SDValue Result;
2706   SDLoc DL(Op);
2707
2708   ++NumMovwMovt;
2709
2710   // FIXME: Once remat is capable of dealing with instructions with register
2711   // operands, expand this into two nodes.
2712   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2713                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2714                                                   TargetFlags));
2715   if (GV->hasDLLImportStorageClass())
2716     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2717                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2718                          false, false, false, 0);
2719   return Result;
2720 }
2721
2722 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2723                                                     SelectionDAG &DAG) const {
2724   assert(Subtarget->isTargetELF() &&
2725          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2726   MachineFunction &MF = DAG.getMachineFunction();
2727   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2728   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2729   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2730   SDLoc dl(Op);
2731   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2732   ARMConstantPoolValue *CPV =
2733     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2734                                   ARMPCLabelIndex, PCAdj);
2735   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2736   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2737   SDValue Result =
2738       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2739                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2740                   false, false, false, 0);
2741   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2742   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2743 }
2744
2745 SDValue
2746 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2747   SDLoc dl(Op);
2748   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2749   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2750                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2751                      Op.getOperand(1), Val);
2752 }
2753
2754 SDValue
2755 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2756   SDLoc dl(Op);
2757   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2758                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2759 }
2760
2761 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2762                                                       SelectionDAG &DAG) const {
2763   SDLoc dl(Op);
2764   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2765                      Op.getOperand(0));
2766 }
2767
2768 SDValue
2769 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2770                                           const ARMSubtarget *Subtarget) const {
2771   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2772   SDLoc dl(Op);
2773   switch (IntNo) {
2774   default: return SDValue();    // Don't custom lower most intrinsics.
2775   case Intrinsic::arm_rbit: {
2776     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2777            "RBIT intrinsic must have i32 type!");
2778     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2779   }
2780   case Intrinsic::arm_thread_pointer: {
2781     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2782     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2783   }
2784   case Intrinsic::eh_sjlj_lsda: {
2785     MachineFunction &MF = DAG.getMachineFunction();
2786     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2787     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2788     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2789     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2790     SDValue CPAddr;
2791     unsigned PCAdj = (RelocM != Reloc::PIC_)
2792       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2793     ARMConstantPoolValue *CPV =
2794       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2795                                       ARMCP::CPLSDA, PCAdj);
2796     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2797     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2798     SDValue Result = DAG.getLoad(
2799         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2800         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2801         false, false, 0);
2802
2803     if (RelocM == Reloc::PIC_) {
2804       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2805       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2806     }
2807     return Result;
2808   }
2809   case Intrinsic::arm_neon_vmulls:
2810   case Intrinsic::arm_neon_vmullu: {
2811     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2812       ? ARMISD::VMULLs : ARMISD::VMULLu;
2813     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2814                        Op.getOperand(1), Op.getOperand(2));
2815   }
2816   case Intrinsic::arm_neon_vminnm:
2817   case Intrinsic::arm_neon_vmaxnm: {
2818     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2819       ? ISD::FMINNUM : ISD::FMAXNUM;
2820     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2821                        Op.getOperand(1), Op.getOperand(2));
2822   }
2823   case Intrinsic::arm_neon_vminu:
2824   case Intrinsic::arm_neon_vmaxu: {
2825     if (Op.getValueType().isFloatingPoint())
2826       return SDValue();
2827     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2828       ? ISD::UMIN : ISD::UMAX;
2829     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2830                          Op.getOperand(1), Op.getOperand(2));
2831   }
2832   case Intrinsic::arm_neon_vmins:
2833   case Intrinsic::arm_neon_vmaxs: {
2834     // v{min,max}s is overloaded between signed integers and floats.
2835     if (!Op.getValueType().isFloatingPoint()) {
2836       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2837         ? ISD::SMIN : ISD::SMAX;
2838       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2839                          Op.getOperand(1), Op.getOperand(2));
2840     }
2841     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2842       ? ISD::FMINNAN : ISD::FMAXNAN;
2843     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2844                        Op.getOperand(1), Op.getOperand(2));
2845   }
2846   }
2847 }
2848
2849 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2850                                  const ARMSubtarget *Subtarget) {
2851   // FIXME: handle "fence singlethread" more efficiently.
2852   SDLoc dl(Op);
2853   if (!Subtarget->hasDataBarrier()) {
2854     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2855     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2856     // here.
2857     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2858            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2859     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2860                        DAG.getConstant(0, dl, MVT::i32));
2861   }
2862
2863   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2864   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2865   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2866   if (Subtarget->isMClass()) {
2867     // Only a full system barrier exists in the M-class architectures.
2868     Domain = ARM_MB::SY;
2869   } else if (Subtarget->isSwift() && Ord == Release) {
2870     // Swift happens to implement ISHST barriers in a way that's compatible with
2871     // Release semantics but weaker than ISH so we'd be fools not to use
2872     // it. Beware: other processors probably don't!
2873     Domain = ARM_MB::ISHST;
2874   }
2875
2876   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2877                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2878                      DAG.getConstant(Domain, dl, MVT::i32));
2879 }
2880
2881 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2882                              const ARMSubtarget *Subtarget) {
2883   // ARM pre v5TE and Thumb1 does not have preload instructions.
2884   if (!(Subtarget->isThumb2() ||
2885         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2886     // Just preserve the chain.
2887     return Op.getOperand(0);
2888
2889   SDLoc dl(Op);
2890   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2891   if (!isRead &&
2892       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2893     // ARMv7 with MP extension has PLDW.
2894     return Op.getOperand(0);
2895
2896   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2897   if (Subtarget->isThumb()) {
2898     // Invert the bits.
2899     isRead = ~isRead & 1;
2900     isData = ~isData & 1;
2901   }
2902
2903   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2904                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2905                      DAG.getConstant(isData, dl, MVT::i32));
2906 }
2907
2908 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2909   MachineFunction &MF = DAG.getMachineFunction();
2910   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2911
2912   // vastart just stores the address of the VarArgsFrameIndex slot into the
2913   // memory location argument.
2914   SDLoc dl(Op);
2915   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2916   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2917   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2918   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2919                       MachinePointerInfo(SV), false, false, 0);
2920 }
2921
2922 SDValue
2923 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2924                                         SDValue &Root, SelectionDAG &DAG,
2925                                         SDLoc dl) const {
2926   MachineFunction &MF = DAG.getMachineFunction();
2927   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2928
2929   const TargetRegisterClass *RC;
2930   if (AFI->isThumb1OnlyFunction())
2931     RC = &ARM::tGPRRegClass;
2932   else
2933     RC = &ARM::GPRRegClass;
2934
2935   // Transform the arguments stored in physical registers into virtual ones.
2936   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2937   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2938
2939   SDValue ArgValue2;
2940   if (NextVA.isMemLoc()) {
2941     MachineFrameInfo *MFI = MF.getFrameInfo();
2942     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2943
2944     // Create load node to retrieve arguments from the stack.
2945     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2946     ArgValue2 = DAG.getLoad(
2947         MVT::i32, dl, Root, FIN,
2948         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2949         false, false, 0);
2950   } else {
2951     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2952     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2953   }
2954   if (!Subtarget->isLittle())
2955     std::swap (ArgValue, ArgValue2);
2956   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2957 }
2958
2959 // The remaining GPRs hold either the beginning of variable-argument
2960 // data, or the beginning of an aggregate passed by value (usually
2961 // byval).  Either way, we allocate stack slots adjacent to the data
2962 // provided by our caller, and store the unallocated registers there.
2963 // If this is a variadic function, the va_list pointer will begin with
2964 // these values; otherwise, this reassembles a (byval) structure that
2965 // was split between registers and memory.
2966 // Return: The frame index registers were stored into.
2967 int
2968 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2969                                   SDLoc dl, SDValue &Chain,
2970                                   const Value *OrigArg,
2971                                   unsigned InRegsParamRecordIdx,
2972                                   int ArgOffset,
2973                                   unsigned ArgSize) const {
2974   // Currently, two use-cases possible:
2975   // Case #1. Non-var-args function, and we meet first byval parameter.
2976   //          Setup first unallocated register as first byval register;
2977   //          eat all remained registers
2978   //          (these two actions are performed by HandleByVal method).
2979   //          Then, here, we initialize stack frame with
2980   //          "store-reg" instructions.
2981   // Case #2. Var-args function, that doesn't contain byval parameters.
2982   //          The same: eat all remained unallocated registers,
2983   //          initialize stack frame.
2984
2985   MachineFunction &MF = DAG.getMachineFunction();
2986   MachineFrameInfo *MFI = MF.getFrameInfo();
2987   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2988   unsigned RBegin, REnd;
2989   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2990     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2991   } else {
2992     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2993     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2994     REnd = ARM::R4;
2995   }
2996
2997   if (REnd != RBegin)
2998     ArgOffset = -4 * (ARM::R4 - RBegin);
2999
3000   auto PtrVT = getPointerTy(DAG.getDataLayout());
3001   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3002   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3003
3004   SmallVector<SDValue, 4> MemOps;
3005   const TargetRegisterClass *RC =
3006       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3007
3008   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3009     unsigned VReg = MF.addLiveIn(Reg, RC);
3010     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3011     SDValue Store =
3012         DAG.getStore(Val.getValue(1), dl, Val, FIN,
3013                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3014     MemOps.push_back(Store);
3015     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3016   }
3017
3018   if (!MemOps.empty())
3019     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3020   return FrameIndex;
3021 }
3022
3023 // Setup stack frame, the va_list pointer will start from.
3024 void
3025 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3026                                         SDLoc dl, SDValue &Chain,
3027                                         unsigned ArgOffset,
3028                                         unsigned TotalArgRegsSaveSize,
3029                                         bool ForceMutable) const {
3030   MachineFunction &MF = DAG.getMachineFunction();
3031   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3032
3033   // Try to store any remaining integer argument regs
3034   // to their spots on the stack so that they may be loaded by deferencing
3035   // the result of va_next.
3036   // If there is no regs to be stored, just point address after last
3037   // argument passed via stack.
3038   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3039                                   CCInfo.getInRegsParamsCount(),
3040                                   CCInfo.getNextStackOffset(), 4);
3041   AFI->setVarArgsFrameIndex(FrameIndex);
3042 }
3043
3044 SDValue
3045 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3046                                         CallingConv::ID CallConv, bool isVarArg,
3047                                         const SmallVectorImpl<ISD::InputArg>
3048                                           &Ins,
3049                                         SDLoc dl, SelectionDAG &DAG,
3050                                         SmallVectorImpl<SDValue> &InVals)
3051                                           const {
3052   MachineFunction &MF = DAG.getMachineFunction();
3053   MachineFrameInfo *MFI = MF.getFrameInfo();
3054
3055   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3056
3057   // Assign locations to all of the incoming arguments.
3058   SmallVector<CCValAssign, 16> ArgLocs;
3059   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3060                     *DAG.getContext(), Prologue);
3061   CCInfo.AnalyzeFormalArguments(Ins,
3062                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3063                                                   isVarArg));
3064
3065   SmallVector<SDValue, 16> ArgValues;
3066   SDValue ArgValue;
3067   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3068   unsigned CurArgIdx = 0;
3069
3070   // Initially ArgRegsSaveSize is zero.
3071   // Then we increase this value each time we meet byval parameter.
3072   // We also increase this value in case of varargs function.
3073   AFI->setArgRegsSaveSize(0);
3074
3075   // Calculate the amount of stack space that we need to allocate to store
3076   // byval and variadic arguments that are passed in registers.
3077   // We need to know this before we allocate the first byval or variadic
3078   // argument, as they will be allocated a stack slot below the CFA (Canonical
3079   // Frame Address, the stack pointer at entry to the function).
3080   unsigned ArgRegBegin = ARM::R4;
3081   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3082     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3083       break;
3084
3085     CCValAssign &VA = ArgLocs[i];
3086     unsigned Index = VA.getValNo();
3087     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3088     if (!Flags.isByVal())
3089       continue;
3090
3091     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3092     unsigned RBegin, REnd;
3093     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3094     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3095
3096     CCInfo.nextInRegsParam();
3097   }
3098   CCInfo.rewindByValRegsInfo();
3099
3100   int lastInsIndex = -1;
3101   if (isVarArg && MFI->hasVAStart()) {
3102     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3103     if (RegIdx != array_lengthof(GPRArgRegs))
3104       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3105   }
3106
3107   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3108   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3109   auto PtrVT = getPointerTy(DAG.getDataLayout());
3110
3111   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3112     CCValAssign &VA = ArgLocs[i];
3113     if (Ins[VA.getValNo()].isOrigArg()) {
3114       std::advance(CurOrigArg,
3115                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3116       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3117     }
3118     // Arguments stored in registers.
3119     if (VA.isRegLoc()) {
3120       EVT RegVT = VA.getLocVT();
3121
3122       if (VA.needsCustom()) {
3123         // f64 and vector types are split up into multiple registers or
3124         // combinations of registers and stack slots.
3125         if (VA.getLocVT() == MVT::v2f64) {
3126           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3127                                                    Chain, DAG, dl);
3128           VA = ArgLocs[++i]; // skip ahead to next loc
3129           SDValue ArgValue2;
3130           if (VA.isMemLoc()) {
3131             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3132             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3133             ArgValue2 = DAG.getLoad(
3134                 MVT::f64, dl, Chain, FIN,
3135                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3136                 false, false, false, 0);
3137           } else {
3138             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3139                                              Chain, DAG, dl);
3140           }
3141           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3142           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3143                                  ArgValue, ArgValue1,
3144                                  DAG.getIntPtrConstant(0, dl));
3145           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3146                                  ArgValue, ArgValue2,
3147                                  DAG.getIntPtrConstant(1, dl));
3148         } else
3149           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3150
3151       } else {
3152         const TargetRegisterClass *RC;
3153
3154         if (RegVT == MVT::f32)
3155           RC = &ARM::SPRRegClass;
3156         else if (RegVT == MVT::f64)
3157           RC = &ARM::DPRRegClass;
3158         else if (RegVT == MVT::v2f64)
3159           RC = &ARM::QPRRegClass;
3160         else if (RegVT == MVT::i32)
3161           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3162                                            : &ARM::GPRRegClass;
3163         else
3164           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3165
3166         // Transform the arguments in physical registers into virtual ones.
3167         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3168         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3169       }
3170
3171       // If this is an 8 or 16-bit value, it is really passed promoted
3172       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3173       // truncate to the right size.
3174       switch (VA.getLocInfo()) {
3175       default: llvm_unreachable("Unknown loc info!");
3176       case CCValAssign::Full: break;
3177       case CCValAssign::BCvt:
3178         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3179         break;
3180       case CCValAssign::SExt:
3181         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3182                                DAG.getValueType(VA.getValVT()));
3183         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3184         break;
3185       case CCValAssign::ZExt:
3186         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3187                                DAG.getValueType(VA.getValVT()));
3188         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3189         break;
3190       }
3191
3192       InVals.push_back(ArgValue);
3193
3194     } else { // VA.isRegLoc()
3195
3196       // sanity check
3197       assert(VA.isMemLoc());
3198       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3199
3200       int index = VA.getValNo();
3201
3202       // Some Ins[] entries become multiple ArgLoc[] entries.
3203       // Process them only once.
3204       if (index != lastInsIndex)
3205         {
3206           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3207           // FIXME: For now, all byval parameter objects are marked mutable.
3208           // This can be changed with more analysis.
3209           // In case of tail call optimization mark all arguments mutable.
3210           // Since they could be overwritten by lowering of arguments in case of
3211           // a tail call.
3212           if (Flags.isByVal()) {
3213             assert(Ins[index].isOrigArg() &&
3214                    "Byval arguments cannot be implicit");
3215             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3216
3217             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3218                                             CurByValIndex, VA.getLocMemOffset(),
3219                                             Flags.getByValSize());
3220             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3221             CCInfo.nextInRegsParam();
3222           } else {
3223             unsigned FIOffset = VA.getLocMemOffset();
3224             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3225                                             FIOffset, true);
3226
3227             // Create load nodes to retrieve arguments from the stack.
3228             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3229             InVals.push_back(DAG.getLoad(
3230                 VA.getValVT(), dl, Chain, FIN,
3231                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3232                 false, false, false, 0));
3233           }
3234           lastInsIndex = index;
3235         }
3236     }
3237   }
3238
3239   // varargs
3240   if (isVarArg && MFI->hasVAStart())
3241     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3242                          CCInfo.getNextStackOffset(),
3243                          TotalArgRegsSaveSize);
3244
3245   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3246
3247   return Chain;
3248 }
3249
3250 /// isFloatingPointZero - Return true if this is +0.0.
3251 static bool isFloatingPointZero(SDValue Op) {
3252   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3253     return CFP->getValueAPF().isPosZero();
3254   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3255     // Maybe this has already been legalized into the constant pool?
3256     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3257       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3258       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3259         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3260           return CFP->getValueAPF().isPosZero();
3261     }
3262   } else if (Op->getOpcode() == ISD::BITCAST &&
3263              Op->getValueType(0) == MVT::f64) {
3264     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3265     // created by LowerConstantFP().
3266     SDValue BitcastOp = Op->getOperand(0);
3267     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3268       SDValue MoveOp = BitcastOp->getOperand(0);
3269       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3270           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3271         return true;
3272       }
3273     }
3274   }
3275   return false;
3276 }
3277
3278 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3279 /// the given operands.
3280 SDValue
3281 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3282                              SDValue &ARMcc, SelectionDAG &DAG,
3283                              SDLoc dl) const {
3284   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3285     unsigned C = RHSC->getZExtValue();
3286     if (!isLegalICmpImmediate(C)) {
3287       // Constant does not fit, try adjusting it by one?
3288       switch (CC) {
3289       default: break;
3290       case ISD::SETLT:
3291       case ISD::SETGE:
3292         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3293           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3294           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3295         }
3296         break;
3297       case ISD::SETULT:
3298       case ISD::SETUGE:
3299         if (C != 0 && isLegalICmpImmediate(C-1)) {
3300           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3301           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3302         }
3303         break;
3304       case ISD::SETLE:
3305       case ISD::SETGT:
3306         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3307           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3308           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3309         }
3310         break;
3311       case ISD::SETULE:
3312       case ISD::SETUGT:
3313         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3314           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3315           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3316         }
3317         break;
3318       }
3319     }
3320   }
3321
3322   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3323   ARMISD::NodeType CompareType;
3324   switch (CondCode) {
3325   default:
3326     CompareType = ARMISD::CMP;
3327     break;
3328   case ARMCC::EQ:
3329   case ARMCC::NE:
3330     // Uses only Z Flag
3331     CompareType = ARMISD::CMPZ;
3332     break;
3333   }
3334   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3335   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3336 }
3337
3338 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3339 SDValue
3340 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3341                              SDLoc dl) const {
3342   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3343   SDValue Cmp;
3344   if (!isFloatingPointZero(RHS))
3345     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3346   else
3347     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3348   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3349 }
3350
3351 /// duplicateCmp - Glue values can have only one use, so this function
3352 /// duplicates a comparison node.
3353 SDValue
3354 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3355   unsigned Opc = Cmp.getOpcode();
3356   SDLoc DL(Cmp);
3357   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3358     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3359
3360   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3361   Cmp = Cmp.getOperand(0);
3362   Opc = Cmp.getOpcode();
3363   if (Opc == ARMISD::CMPFP)
3364     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3365   else {
3366     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3367     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3368   }
3369   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3370 }
3371
3372 std::pair<SDValue, SDValue>
3373 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3374                                  SDValue &ARMcc) const {
3375   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3376
3377   SDValue Value, OverflowCmp;
3378   SDValue LHS = Op.getOperand(0);
3379   SDValue RHS = Op.getOperand(1);
3380   SDLoc dl(Op);
3381
3382   // FIXME: We are currently always generating CMPs because we don't support
3383   // generating CMN through the backend. This is not as good as the natural
3384   // CMP case because it causes a register dependency and cannot be folded
3385   // later.
3386
3387   switch (Op.getOpcode()) {
3388   default:
3389     llvm_unreachable("Unknown overflow instruction!");
3390   case ISD::SADDO:
3391     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3392     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3393     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3394     break;
3395   case ISD::UADDO:
3396     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3397     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3398     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3399     break;
3400   case ISD::SSUBO:
3401     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3402     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3403     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3404     break;
3405   case ISD::USUBO:
3406     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3407     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3408     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3409     break;
3410   } // switch (...)
3411
3412   return std::make_pair(Value, OverflowCmp);
3413 }
3414
3415
3416 SDValue
3417 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3418   // Let legalize expand this if it isn't a legal type yet.
3419   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3420     return SDValue();
3421
3422   SDValue Value, OverflowCmp;
3423   SDValue ARMcc;
3424   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3425   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3426   SDLoc dl(Op);
3427   // We use 0 and 1 as false and true values.
3428   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3429   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3430   EVT VT = Op.getValueType();
3431
3432   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3433                                  ARMcc, CCR, OverflowCmp);
3434
3435   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3436   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3437 }
3438
3439
3440 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3441   SDValue Cond = Op.getOperand(0);
3442   SDValue SelectTrue = Op.getOperand(1);
3443   SDValue SelectFalse = Op.getOperand(2);
3444   SDLoc dl(Op);
3445   unsigned Opc = Cond.getOpcode();
3446
3447   if (Cond.getResNo() == 1 &&
3448       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3449        Opc == ISD::USUBO)) {
3450     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3451       return SDValue();
3452
3453     SDValue Value, OverflowCmp;
3454     SDValue ARMcc;
3455     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3456     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3457     EVT VT = Op.getValueType();
3458
3459     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3460                    OverflowCmp, DAG);
3461   }
3462
3463   // Convert:
3464   //
3465   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3466   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3467   //
3468   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3469     const ConstantSDNode *CMOVTrue =
3470       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3471     const ConstantSDNode *CMOVFalse =
3472       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3473
3474     if (CMOVTrue && CMOVFalse) {
3475       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3476       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3477
3478       SDValue True;
3479       SDValue False;
3480       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3481         True = SelectTrue;
3482         False = SelectFalse;
3483       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3484         True = SelectFalse;
3485         False = SelectTrue;
3486       }
3487
3488       if (True.getNode() && False.getNode()) {
3489         EVT VT = Op.getValueType();
3490         SDValue ARMcc = Cond.getOperand(2);
3491         SDValue CCR = Cond.getOperand(3);
3492         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3493         assert(True.getValueType() == VT);
3494         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3495       }
3496     }
3497   }
3498
3499   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3500   // undefined bits before doing a full-word comparison with zero.
3501   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3502                      DAG.getConstant(1, dl, Cond.getValueType()));
3503
3504   return DAG.getSelectCC(dl, Cond,
3505                          DAG.getConstant(0, dl, Cond.getValueType()),
3506                          SelectTrue, SelectFalse, ISD::SETNE);
3507 }
3508
3509 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3510                                  bool &swpCmpOps, bool &swpVselOps) {
3511   // Start by selecting the GE condition code for opcodes that return true for
3512   // 'equality'
3513   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3514       CC == ISD::SETULE)
3515     CondCode = ARMCC::GE;
3516
3517   // and GT for opcodes that return false for 'equality'.
3518   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3519            CC == ISD::SETULT)
3520     CondCode = ARMCC::GT;
3521
3522   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3523   // to swap the compare operands.
3524   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3525       CC == ISD::SETULT)
3526     swpCmpOps = true;
3527
3528   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3529   // If we have an unordered opcode, we need to swap the operands to the VSEL
3530   // instruction (effectively negating the condition).
3531   //
3532   // This also has the effect of swapping which one of 'less' or 'greater'
3533   // returns true, so we also swap the compare operands. It also switches
3534   // whether we return true for 'equality', so we compensate by picking the
3535   // opposite condition code to our original choice.
3536   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3537       CC == ISD::SETUGT) {
3538     swpCmpOps = !swpCmpOps;
3539     swpVselOps = !swpVselOps;
3540     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3541   }
3542
3543   // 'ordered' is 'anything but unordered', so use the VS condition code and
3544   // swap the VSEL operands.
3545   if (CC == ISD::SETO) {
3546     CondCode = ARMCC::VS;
3547     swpVselOps = true;
3548   }
3549
3550   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3551   // code and swap the VSEL operands.
3552   if (CC == ISD::SETUNE) {
3553     CondCode = ARMCC::EQ;
3554     swpVselOps = true;
3555   }
3556 }
3557
3558 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3559                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3560                                    SDValue Cmp, SelectionDAG &DAG) const {
3561   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3562     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3563                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3564     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3565                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3566
3567     SDValue TrueLow = TrueVal.getValue(0);
3568     SDValue TrueHigh = TrueVal.getValue(1);
3569     SDValue FalseLow = FalseVal.getValue(0);
3570     SDValue FalseHigh = FalseVal.getValue(1);
3571
3572     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3573                               ARMcc, CCR, Cmp);
3574     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3575                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3576
3577     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3578   } else {
3579     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3580                        Cmp);
3581   }
3582 }
3583
3584 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3585   EVT VT = Op.getValueType();
3586   SDValue LHS = Op.getOperand(0);
3587   SDValue RHS = Op.getOperand(1);
3588   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3589   SDValue TrueVal = Op.getOperand(2);
3590   SDValue FalseVal = Op.getOperand(3);
3591   SDLoc dl(Op);
3592
3593   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3594     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3595                                                     dl);
3596
3597     // If softenSetCCOperands only returned one value, we should compare it to
3598     // zero.
3599     if (!RHS.getNode()) {
3600       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3601       CC = ISD::SETNE;
3602     }
3603   }
3604
3605   if (LHS.getValueType() == MVT::i32) {
3606     // Try to generate VSEL on ARMv8.
3607     // The VSEL instruction can't use all the usual ARM condition
3608     // codes: it only has two bits to select the condition code, so it's
3609     // constrained to use only GE, GT, VS and EQ.
3610     //
3611     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3612     // swap the operands of the previous compare instruction (effectively
3613     // inverting the compare condition, swapping 'less' and 'greater') and
3614     // sometimes need to swap the operands to the VSEL (which inverts the
3615     // condition in the sense of firing whenever the previous condition didn't)
3616     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3617                                     TrueVal.getValueType() == MVT::f64)) {
3618       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3619       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3620           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3621         CC = ISD::getSetCCInverse(CC, true);
3622         std::swap(TrueVal, FalseVal);
3623       }
3624     }
3625
3626     SDValue ARMcc;
3627     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3628     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3629     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3630   }
3631
3632   ARMCC::CondCodes CondCode, CondCode2;
3633   FPCCToARMCC(CC, CondCode, CondCode2);
3634
3635   // Try to generate VMAXNM/VMINNM on ARMv8.
3636   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3637                                   TrueVal.getValueType() == MVT::f64)) {
3638     bool swpCmpOps = false;
3639     bool swpVselOps = false;
3640     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3641
3642     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3643         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3644       if (swpCmpOps)
3645         std::swap(LHS, RHS);
3646       if (swpVselOps)
3647         std::swap(TrueVal, FalseVal);
3648     }
3649   }
3650
3651   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3652   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3653   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3654   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3655   if (CondCode2 != ARMCC::AL) {
3656     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3657     // FIXME: Needs another CMP because flag can have but one use.
3658     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3659     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3660   }
3661   return Result;
3662 }
3663
3664 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3665 /// to morph to an integer compare sequence.
3666 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3667                            const ARMSubtarget *Subtarget) {
3668   SDNode *N = Op.getNode();
3669   if (!N->hasOneUse())
3670     // Otherwise it requires moving the value from fp to integer registers.
3671     return false;
3672   if (!N->getNumValues())
3673     return false;
3674   EVT VT = Op.getValueType();
3675   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3676     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3677     // vmrs are very slow, e.g. cortex-a8.
3678     return false;
3679
3680   if (isFloatingPointZero(Op)) {
3681     SeenZero = true;
3682     return true;
3683   }
3684   return ISD::isNormalLoad(N);
3685 }
3686
3687 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3688   if (isFloatingPointZero(Op))
3689     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3690
3691   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3692     return DAG.getLoad(MVT::i32, SDLoc(Op),
3693                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3694                        Ld->isVolatile(), Ld->isNonTemporal(),
3695                        Ld->isInvariant(), Ld->getAlignment());
3696
3697   llvm_unreachable("Unknown VFP cmp argument!");
3698 }
3699
3700 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3701                            SDValue &RetVal1, SDValue &RetVal2) {
3702   SDLoc dl(Op);
3703
3704   if (isFloatingPointZero(Op)) {
3705     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3706     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3707     return;
3708   }
3709
3710   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3711     SDValue Ptr = Ld->getBasePtr();
3712     RetVal1 = DAG.getLoad(MVT::i32, dl,
3713                           Ld->getChain(), Ptr,
3714                           Ld->getPointerInfo(),
3715                           Ld->isVolatile(), Ld->isNonTemporal(),
3716                           Ld->isInvariant(), Ld->getAlignment());
3717
3718     EVT PtrType = Ptr.getValueType();
3719     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3720     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3721                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3722     RetVal2 = DAG.getLoad(MVT::i32, dl,
3723                           Ld->getChain(), NewPtr,
3724                           Ld->getPointerInfo().getWithOffset(4),
3725                           Ld->isVolatile(), Ld->isNonTemporal(),
3726                           Ld->isInvariant(), NewAlign);
3727     return;
3728   }
3729
3730   llvm_unreachable("Unknown VFP cmp argument!");
3731 }
3732
3733 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3734 /// f32 and even f64 comparisons to integer ones.
3735 SDValue
3736 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3737   SDValue Chain = Op.getOperand(0);
3738   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3739   SDValue LHS = Op.getOperand(2);
3740   SDValue RHS = Op.getOperand(3);
3741   SDValue Dest = Op.getOperand(4);
3742   SDLoc dl(Op);
3743
3744   bool LHSSeenZero = false;
3745   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3746   bool RHSSeenZero = false;
3747   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3748   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3749     // If unsafe fp math optimization is enabled and there are no other uses of
3750     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3751     // to an integer comparison.
3752     if (CC == ISD::SETOEQ)
3753       CC = ISD::SETEQ;
3754     else if (CC == ISD::SETUNE)
3755       CC = ISD::SETNE;
3756
3757     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3758     SDValue ARMcc;
3759     if (LHS.getValueType() == MVT::f32) {
3760       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3761                         bitcastf32Toi32(LHS, DAG), Mask);
3762       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3763                         bitcastf32Toi32(RHS, DAG), Mask);
3764       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3765       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3766       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3767                          Chain, Dest, ARMcc, CCR, Cmp);
3768     }
3769
3770     SDValue LHS1, LHS2;
3771     SDValue RHS1, RHS2;
3772     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3773     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3774     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3775     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3776     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3777     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3778     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3779     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3780     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3781   }
3782
3783   return SDValue();
3784 }
3785
3786 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3787   SDValue Chain = Op.getOperand(0);
3788   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3789   SDValue LHS = Op.getOperand(2);
3790   SDValue RHS = Op.getOperand(3);
3791   SDValue Dest = Op.getOperand(4);
3792   SDLoc dl(Op);
3793
3794   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3795     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3796                                                     dl);
3797
3798     // If softenSetCCOperands only returned one value, we should compare it to
3799     // zero.
3800     if (!RHS.getNode()) {
3801       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3802       CC = ISD::SETNE;
3803     }
3804   }
3805
3806   if (LHS.getValueType() == MVT::i32) {
3807     SDValue ARMcc;
3808     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3809     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3810     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3811                        Chain, Dest, ARMcc, CCR, Cmp);
3812   }
3813
3814   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3815
3816   if (getTargetMachine().Options.UnsafeFPMath &&
3817       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3818        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3819     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3820     if (Result.getNode())
3821       return Result;
3822   }
3823
3824   ARMCC::CondCodes CondCode, CondCode2;
3825   FPCCToARMCC(CC, CondCode, CondCode2);
3826
3827   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3828   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3829   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3830   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3831   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3832   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3833   if (CondCode2 != ARMCC::AL) {
3834     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3835     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3836     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3837   }
3838   return Res;
3839 }
3840
3841 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3842   SDValue Chain = Op.getOperand(0);
3843   SDValue Table = Op.getOperand(1);
3844   SDValue Index = Op.getOperand(2);
3845   SDLoc dl(Op);
3846
3847   EVT PTy = getPointerTy(DAG.getDataLayout());
3848   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3849   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3850   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3851   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3852   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3853   if (Subtarget->isThumb2()) {
3854     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3855     // which does another jump to the destination. This also makes it easier
3856     // to translate it to TBB / TBH later.
3857     // FIXME: This might not work if the function is extremely large.
3858     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3859                        Addr, Op.getOperand(2), JTI);
3860   }
3861   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3862     Addr =
3863         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3864                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3865                     false, false, false, 0);
3866     Chain = Addr.getValue(1);
3867     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3868     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3869   } else {
3870     Addr =
3871         DAG.getLoad(PTy, dl, Chain, Addr,
3872                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3873                     false, false, false, 0);
3874     Chain = Addr.getValue(1);
3875     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3876   }
3877 }
3878
3879 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3880   EVT VT = Op.getValueType();
3881   SDLoc dl(Op);
3882
3883   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3884     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3885       return Op;
3886     return DAG.UnrollVectorOp(Op.getNode());
3887   }
3888
3889   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3890          "Invalid type for custom lowering!");
3891   if (VT != MVT::v4i16)
3892     return DAG.UnrollVectorOp(Op.getNode());
3893
3894   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3895   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3896 }
3897
3898 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3899   EVT VT = Op.getValueType();
3900   if (VT.isVector())
3901     return LowerVectorFP_TO_INT(Op, DAG);
3902   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3903     RTLIB::Libcall LC;
3904     if (Op.getOpcode() == ISD::FP_TO_SINT)
3905       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3906                               Op.getValueType());
3907     else
3908       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3909                               Op.getValueType());
3910     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3911                        /*isSigned*/ false, SDLoc(Op)).first;
3912   }
3913
3914   return Op;
3915 }
3916
3917 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3918   EVT VT = Op.getValueType();
3919   SDLoc dl(Op);
3920
3921   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3922     if (VT.getVectorElementType() == MVT::f32)
3923       return Op;
3924     return DAG.UnrollVectorOp(Op.getNode());
3925   }
3926
3927   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3928          "Invalid type for custom lowering!");
3929   if (VT != MVT::v4f32)
3930     return DAG.UnrollVectorOp(Op.getNode());
3931
3932   unsigned CastOpc;
3933   unsigned Opc;
3934   switch (Op.getOpcode()) {
3935   default: llvm_unreachable("Invalid opcode!");
3936   case ISD::SINT_TO_FP:
3937     CastOpc = ISD::SIGN_EXTEND;
3938     Opc = ISD::SINT_TO_FP;
3939     break;
3940   case ISD::UINT_TO_FP:
3941     CastOpc = ISD::ZERO_EXTEND;
3942     Opc = ISD::UINT_TO_FP;
3943     break;
3944   }
3945
3946   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3947   return DAG.getNode(Opc, dl, VT, Op);
3948 }
3949
3950 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3951   EVT VT = Op.getValueType();
3952   if (VT.isVector())
3953     return LowerVectorINT_TO_FP(Op, DAG);
3954   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3955     RTLIB::Libcall LC;
3956     if (Op.getOpcode() == ISD::SINT_TO_FP)
3957       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3958                               Op.getValueType());
3959     else
3960       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3961                               Op.getValueType());
3962     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3963                        /*isSigned*/ false, SDLoc(Op)).first;
3964   }
3965
3966   return Op;
3967 }
3968
3969 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3970   // Implement fcopysign with a fabs and a conditional fneg.
3971   SDValue Tmp0 = Op.getOperand(0);
3972   SDValue Tmp1 = Op.getOperand(1);
3973   SDLoc dl(Op);
3974   EVT VT = Op.getValueType();
3975   EVT SrcVT = Tmp1.getValueType();
3976   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3977     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3978   bool UseNEON = !InGPR && Subtarget->hasNEON();
3979
3980   if (UseNEON) {
3981     // Use VBSL to copy the sign bit.
3982     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3983     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3984                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3985     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3986     if (VT == MVT::f64)
3987       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3988                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3989                          DAG.getConstant(32, dl, MVT::i32));
3990     else /*if (VT == MVT::f32)*/
3991       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3992     if (SrcVT == MVT::f32) {
3993       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3994       if (VT == MVT::f64)
3995         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3996                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3997                            DAG.getConstant(32, dl, MVT::i32));
3998     } else if (VT == MVT::f32)
3999       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4000                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4001                          DAG.getConstant(32, dl, MVT::i32));
4002     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4003     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4004
4005     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4006                                             dl, MVT::i32);
4007     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4008     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4009                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4010
4011     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4012                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4013                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4014     if (VT == MVT::f32) {
4015       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4016       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4017                         DAG.getConstant(0, dl, MVT::i32));
4018     } else {
4019       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4020     }
4021
4022     return Res;
4023   }
4024
4025   // Bitcast operand 1 to i32.
4026   if (SrcVT == MVT::f64)
4027     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4028                        Tmp1).getValue(1);
4029   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4030
4031   // Or in the signbit with integer operations.
4032   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4033   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4034   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4035   if (VT == MVT::f32) {
4036     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4037                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4038     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4039                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4040   }
4041
4042   // f64: Or the high part with signbit and then combine two parts.
4043   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4044                      Tmp0);
4045   SDValue Lo = Tmp0.getValue(0);
4046   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4047   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4048   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4049 }
4050
4051 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4052   MachineFunction &MF = DAG.getMachineFunction();
4053   MachineFrameInfo *MFI = MF.getFrameInfo();
4054   MFI->setReturnAddressIsTaken(true);
4055
4056   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4057     return SDValue();
4058
4059   EVT VT = Op.getValueType();
4060   SDLoc dl(Op);
4061   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4062   if (Depth) {
4063     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4064     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4065     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4066                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4067                        MachinePointerInfo(), false, false, false, 0);
4068   }
4069
4070   // Return LR, which contains the return address. Mark it an implicit live-in.
4071   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4072   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4073 }
4074
4075 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4076   const ARMBaseRegisterInfo &ARI =
4077     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4078   MachineFunction &MF = DAG.getMachineFunction();
4079   MachineFrameInfo *MFI = MF.getFrameInfo();
4080   MFI->setFrameAddressIsTaken(true);
4081
4082   EVT VT = Op.getValueType();
4083   SDLoc dl(Op);  // FIXME probably not meaningful
4084   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4085   unsigned FrameReg = ARI.getFrameRegister(MF);
4086   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4087   while (Depth--)
4088     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4089                             MachinePointerInfo(),
4090                             false, false, false, 0);
4091   return FrameAddr;
4092 }
4093
4094 // FIXME? Maybe this could be a TableGen attribute on some registers and
4095 // this table could be generated automatically from RegInfo.
4096 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4097                                               SelectionDAG &DAG) const {
4098   unsigned Reg = StringSwitch<unsigned>(RegName)
4099                        .Case("sp", ARM::SP)
4100                        .Default(0);
4101   if (Reg)
4102     return Reg;
4103   report_fatal_error(Twine("Invalid register name \""
4104                               + StringRef(RegName)  + "\"."));
4105 }
4106
4107 // Result is 64 bit value so split into two 32 bit values and return as a
4108 // pair of values.
4109 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4110                                 SelectionDAG &DAG) {
4111   SDLoc DL(N);
4112
4113   // This function is only supposed to be called for i64 type destination.
4114   assert(N->getValueType(0) == MVT::i64
4115           && "ExpandREAD_REGISTER called for non-i64 type result.");
4116
4117   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4118                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4119                              N->getOperand(0),
4120                              N->getOperand(1));
4121
4122   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4123                     Read.getValue(1)));
4124   Results.push_back(Read.getOperand(0));
4125 }
4126
4127 /// ExpandBITCAST - If the target supports VFP, this function is called to
4128 /// expand a bit convert where either the source or destination type is i64 to
4129 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4130 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4131 /// vectors), since the legalizer won't know what to do with that.
4132 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4133   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4134   SDLoc dl(N);
4135   SDValue Op = N->getOperand(0);
4136
4137   // This function is only supposed to be called for i64 types, either as the
4138   // source or destination of the bit convert.
4139   EVT SrcVT = Op.getValueType();
4140   EVT DstVT = N->getValueType(0);
4141   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4142          "ExpandBITCAST called for non-i64 type");
4143
4144   // Turn i64->f64 into VMOVDRR.
4145   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4146     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4147                              DAG.getConstant(0, dl, MVT::i32));
4148     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4149                              DAG.getConstant(1, dl, MVT::i32));
4150     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4151                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4152   }
4153
4154   // Turn f64->i64 into VMOVRRD.
4155   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4156     SDValue Cvt;
4157     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4158         SrcVT.getVectorNumElements() > 1)
4159       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4160                         DAG.getVTList(MVT::i32, MVT::i32),
4161                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4162     else
4163       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4164                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4165     // Merge the pieces into a single i64 value.
4166     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4167   }
4168
4169   return SDValue();
4170 }
4171
4172 /// getZeroVector - Returns a vector of specified type with all zero elements.
4173 /// Zero vectors are used to represent vector negation and in those cases
4174 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4175 /// not support i64 elements, so sometimes the zero vectors will need to be
4176 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4177 /// zero vector.
4178 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4179   assert(VT.isVector() && "Expected a vector type");
4180   // The canonical modified immediate encoding of a zero vector is....0!
4181   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4182   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4183   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4184   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4185 }
4186
4187 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4188 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4189 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4190                                                 SelectionDAG &DAG) const {
4191   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4192   EVT VT = Op.getValueType();
4193   unsigned VTBits = VT.getSizeInBits();
4194   SDLoc dl(Op);
4195   SDValue ShOpLo = Op.getOperand(0);
4196   SDValue ShOpHi = Op.getOperand(1);
4197   SDValue ShAmt  = Op.getOperand(2);
4198   SDValue ARMcc;
4199   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4200
4201   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4202
4203   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4204                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4205   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4206   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4207                                    DAG.getConstant(VTBits, dl, MVT::i32));
4208   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4209   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4210   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4211
4212   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4213   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4214                           ISD::SETGE, ARMcc, DAG, dl);
4215   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4216   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4217                            CCR, Cmp);
4218
4219   SDValue Ops[2] = { Lo, Hi };
4220   return DAG.getMergeValues(Ops, dl);
4221 }
4222
4223 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4224 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4225 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4226                                                SelectionDAG &DAG) const {
4227   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4228   EVT VT = Op.getValueType();
4229   unsigned VTBits = VT.getSizeInBits();
4230   SDLoc dl(Op);
4231   SDValue ShOpLo = Op.getOperand(0);
4232   SDValue ShOpHi = Op.getOperand(1);
4233   SDValue ShAmt  = Op.getOperand(2);
4234   SDValue ARMcc;
4235
4236   assert(Op.getOpcode() == ISD::SHL_PARTS);
4237   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4238                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4239   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4240   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4241                                    DAG.getConstant(VTBits, dl, MVT::i32));
4242   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4243   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4244
4245   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4246   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4247   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4248                           ISD::SETGE, ARMcc, DAG, dl);
4249   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4250   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4251                            CCR, Cmp);
4252
4253   SDValue Ops[2] = { Lo, Hi };
4254   return DAG.getMergeValues(Ops, dl);
4255 }
4256
4257 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4258                                             SelectionDAG &DAG) const {
4259   // The rounding mode is in bits 23:22 of the FPSCR.
4260   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4261   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4262   // so that the shift + and get folded into a bitfield extract.
4263   SDLoc dl(Op);
4264   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4265                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4266                                               MVT::i32));
4267   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4268                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4269   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4270                               DAG.getConstant(22, dl, MVT::i32));
4271   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4272                      DAG.getConstant(3, dl, MVT::i32));
4273 }
4274
4275 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4276                          const ARMSubtarget *ST) {
4277   SDLoc dl(N);
4278   EVT VT = N->getValueType(0);
4279   if (VT.isVector()) {
4280     assert(ST->hasNEON());
4281
4282     // Compute the least significant set bit: LSB = X & -X
4283     SDValue X = N->getOperand(0);
4284     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4285     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4286
4287     EVT ElemTy = VT.getVectorElementType();
4288
4289     if (ElemTy == MVT::i8) {
4290       // Compute with: cttz(x) = ctpop(lsb - 1)
4291       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4292                                 DAG.getTargetConstant(1, dl, ElemTy));
4293       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4294       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4295     }
4296
4297     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4298         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4299       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4300       unsigned NumBits = ElemTy.getSizeInBits();
4301       SDValue WidthMinus1 =
4302           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4303                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4304       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4305       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4306     }
4307
4308     // Compute with: cttz(x) = ctpop(lsb - 1)
4309
4310     // Since we can only compute the number of bits in a byte with vcnt.8, we
4311     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4312     // and i64.
4313
4314     // Compute LSB - 1.
4315     SDValue Bits;
4316     if (ElemTy == MVT::i64) {
4317       // Load constant 0xffff'ffff'ffff'ffff to register.
4318       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4319                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4320       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4321     } else {
4322       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4323                                 DAG.getTargetConstant(1, dl, ElemTy));
4324       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4325     }
4326
4327     // Count #bits with vcnt.8.
4328     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4329     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4330     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4331
4332     // Gather the #bits with vpaddl (pairwise add.)
4333     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4334     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4335         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4336         Cnt8);
4337     if (ElemTy == MVT::i16)
4338       return Cnt16;
4339
4340     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4341     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4342         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4343         Cnt16);
4344     if (ElemTy == MVT::i32)
4345       return Cnt32;
4346
4347     assert(ElemTy == MVT::i64);
4348     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4349         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4350         Cnt32);
4351     return Cnt64;
4352   }
4353
4354   if (!ST->hasV6T2Ops())
4355     return SDValue();
4356
4357   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4358   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4359 }
4360
4361 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4362 /// for each 16-bit element from operand, repeated.  The basic idea is to
4363 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4364 ///
4365 /// Trace for v4i16:
4366 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4367 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4368 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4369 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4370 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4371 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4372 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4373 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4374 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4375   EVT VT = N->getValueType(0);
4376   SDLoc DL(N);
4377
4378   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4379   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4380   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4381   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4382   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4383   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4384 }
4385
4386 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4387 /// bit-count for each 16-bit element from the operand.  We need slightly
4388 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4389 /// 64/128-bit registers.
4390 ///
4391 /// Trace for v4i16:
4392 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4393 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4394 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4395 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4396 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4397   EVT VT = N->getValueType(0);
4398   SDLoc DL(N);
4399
4400   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4401   if (VT.is64BitVector()) {
4402     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4403     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4404                        DAG.getIntPtrConstant(0, DL));
4405   } else {
4406     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4407                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4408     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4409   }
4410 }
4411
4412 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4413 /// bit-count for each 32-bit element from the operand.  The idea here is
4414 /// to split the vector into 16-bit elements, leverage the 16-bit count
4415 /// routine, and then combine the results.
4416 ///
4417 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4418 /// input    = [v0    v1    ] (vi: 32-bit elements)
4419 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4420 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4421 /// vrev: N0 = [k1 k0 k3 k2 ]
4422 ///            [k0 k1 k2 k3 ]
4423 ///       N1 =+[k1 k0 k3 k2 ]
4424 ///            [k0 k2 k1 k3 ]
4425 ///       N2 =+[k1 k3 k0 k2 ]
4426 ///            [k0    k2    k1    k3    ]
4427 /// Extended =+[k1    k3    k0    k2    ]
4428 ///            [k0    k2    ]
4429 /// Extracted=+[k1    k3    ]
4430 ///
4431 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4432   EVT VT = N->getValueType(0);
4433   SDLoc DL(N);
4434
4435   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4436
4437   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4438   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4439   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4440   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4441   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4442
4443   if (VT.is64BitVector()) {
4444     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4445     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4446                        DAG.getIntPtrConstant(0, DL));
4447   } else {
4448     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4449                                     DAG.getIntPtrConstant(0, DL));
4450     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4451   }
4452 }
4453
4454 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4455                           const ARMSubtarget *ST) {
4456   EVT VT = N->getValueType(0);
4457
4458   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4459   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4460           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4461          "Unexpected type for custom ctpop lowering");
4462
4463   if (VT.getVectorElementType() == MVT::i32)
4464     return lowerCTPOP32BitElements(N, DAG);
4465   else
4466     return lowerCTPOP16BitElements(N, DAG);
4467 }
4468
4469 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4470                           const ARMSubtarget *ST) {
4471   EVT VT = N->getValueType(0);
4472   SDLoc dl(N);
4473
4474   if (!VT.isVector())
4475     return SDValue();
4476
4477   // Lower vector shifts on NEON to use VSHL.
4478   assert(ST->hasNEON() && "unexpected vector shift");
4479
4480   // Left shifts translate directly to the vshiftu intrinsic.
4481   if (N->getOpcode() == ISD::SHL)
4482     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4483                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4484                                        MVT::i32),
4485                        N->getOperand(0), N->getOperand(1));
4486
4487   assert((N->getOpcode() == ISD::SRA ||
4488           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4489
4490   // NEON uses the same intrinsics for both left and right shifts.  For
4491   // right shifts, the shift amounts are negative, so negate the vector of
4492   // shift amounts.
4493   EVT ShiftVT = N->getOperand(1).getValueType();
4494   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4495                                      getZeroVector(ShiftVT, DAG, dl),
4496                                      N->getOperand(1));
4497   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4498                              Intrinsic::arm_neon_vshifts :
4499                              Intrinsic::arm_neon_vshiftu);
4500   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4501                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4502                      N->getOperand(0), NegatedCount);
4503 }
4504
4505 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4506                                 const ARMSubtarget *ST) {
4507   EVT VT = N->getValueType(0);
4508   SDLoc dl(N);
4509
4510   // We can get here for a node like i32 = ISD::SHL i32, i64
4511   if (VT != MVT::i64)
4512     return SDValue();
4513
4514   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4515          "Unknown shift to lower!");
4516
4517   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4518   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4519       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4520     return SDValue();
4521
4522   // If we are in thumb mode, we don't have RRX.
4523   if (ST->isThumb1Only()) return SDValue();
4524
4525   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4526   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4527                            DAG.getConstant(0, dl, MVT::i32));
4528   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4529                            DAG.getConstant(1, dl, MVT::i32));
4530
4531   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4532   // captures the result into a carry flag.
4533   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4534   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4535
4536   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4537   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4538
4539   // Merge the pieces into a single i64 value.
4540  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4541 }
4542
4543 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4544   SDValue TmpOp0, TmpOp1;
4545   bool Invert = false;
4546   bool Swap = false;
4547   unsigned Opc = 0;
4548
4549   SDValue Op0 = Op.getOperand(0);
4550   SDValue Op1 = Op.getOperand(1);
4551   SDValue CC = Op.getOperand(2);
4552   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4553   EVT VT = Op.getValueType();
4554   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4555   SDLoc dl(Op);
4556
4557   if (CmpVT.getVectorElementType() == MVT::i64)
4558     // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4559     // but it's possible that our operands are 64-bit but our result is 32-bit.
4560     // Bail in this case.
4561     return SDValue();
4562
4563   if (Op1.getValueType().isFloatingPoint()) {
4564     switch (SetCCOpcode) {
4565     default: llvm_unreachable("Illegal FP comparison");
4566     case ISD::SETUNE:
4567     case ISD::SETNE:  Invert = true; // Fallthrough
4568     case ISD::SETOEQ:
4569     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4570     case ISD::SETOLT:
4571     case ISD::SETLT: Swap = true; // Fallthrough
4572     case ISD::SETOGT:
4573     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4574     case ISD::SETOLE:
4575     case ISD::SETLE:  Swap = true; // Fallthrough
4576     case ISD::SETOGE:
4577     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4578     case ISD::SETUGE: Swap = true; // Fallthrough
4579     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4580     case ISD::SETUGT: Swap = true; // Fallthrough
4581     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4582     case ISD::SETUEQ: Invert = true; // Fallthrough
4583     case ISD::SETONE:
4584       // Expand this to (OLT | OGT).
4585       TmpOp0 = Op0;
4586       TmpOp1 = Op1;
4587       Opc = ISD::OR;
4588       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4589       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4590       break;
4591     case ISD::SETUO: Invert = true; // Fallthrough
4592     case ISD::SETO:
4593       // Expand this to (OLT | OGE).
4594       TmpOp0 = Op0;
4595       TmpOp1 = Op1;
4596       Opc = ISD::OR;
4597       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4598       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4599       break;
4600     }
4601   } else {
4602     // Integer comparisons.
4603     switch (SetCCOpcode) {
4604     default: llvm_unreachable("Illegal integer comparison");
4605     case ISD::SETNE:  Invert = true;
4606     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4607     case ISD::SETLT:  Swap = true;
4608     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4609     case ISD::SETLE:  Swap = true;
4610     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4611     case ISD::SETULT: Swap = true;
4612     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4613     case ISD::SETULE: Swap = true;
4614     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4615     }
4616
4617     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4618     if (Opc == ARMISD::VCEQ) {
4619
4620       SDValue AndOp;
4621       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4622         AndOp = Op0;
4623       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4624         AndOp = Op1;
4625
4626       // Ignore bitconvert.
4627       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4628         AndOp = AndOp.getOperand(0);
4629
4630       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4631         Opc = ARMISD::VTST;
4632         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4633         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4634         Invert = !Invert;
4635       }
4636     }
4637   }
4638
4639   if (Swap)
4640     std::swap(Op0, Op1);
4641
4642   // If one of the operands is a constant vector zero, attempt to fold the
4643   // comparison to a specialized compare-against-zero form.
4644   SDValue SingleOp;
4645   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4646     SingleOp = Op0;
4647   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4648     if (Opc == ARMISD::VCGE)
4649       Opc = ARMISD::VCLEZ;
4650     else if (Opc == ARMISD::VCGT)
4651       Opc = ARMISD::VCLTZ;
4652     SingleOp = Op1;
4653   }
4654
4655   SDValue Result;
4656   if (SingleOp.getNode()) {
4657     switch (Opc) {
4658     case ARMISD::VCEQ:
4659       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4660     case ARMISD::VCGE:
4661       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4662     case ARMISD::VCLEZ:
4663       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4664     case ARMISD::VCGT:
4665       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4666     case ARMISD::VCLTZ:
4667       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4668     default:
4669       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4670     }
4671   } else {
4672      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4673   }
4674
4675   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4676
4677   if (Invert)
4678     Result = DAG.getNOT(dl, Result, VT);
4679
4680   return Result;
4681 }
4682
4683 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4684 /// valid vector constant for a NEON instruction with a "modified immediate"
4685 /// operand (e.g., VMOV).  If so, return the encoded value.
4686 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4687                                  unsigned SplatBitSize, SelectionDAG &DAG,
4688                                  SDLoc dl, EVT &VT, bool is128Bits,
4689                                  NEONModImmType type) {
4690   unsigned OpCmode, Imm;
4691
4692   // SplatBitSize is set to the smallest size that splats the vector, so a
4693   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4694   // immediate instructions others than VMOV do not support the 8-bit encoding
4695   // of a zero vector, and the default encoding of zero is supposed to be the
4696   // 32-bit version.
4697   if (SplatBits == 0)
4698     SplatBitSize = 32;
4699
4700   switch (SplatBitSize) {
4701   case 8:
4702     if (type != VMOVModImm)
4703       return SDValue();
4704     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4705     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4706     OpCmode = 0xe;
4707     Imm = SplatBits;
4708     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4709     break;
4710
4711   case 16:
4712     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4713     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4714     if ((SplatBits & ~0xff) == 0) {
4715       // Value = 0x00nn: Op=x, Cmode=100x.
4716       OpCmode = 0x8;
4717       Imm = SplatBits;
4718       break;
4719     }
4720     if ((SplatBits & ~0xff00) == 0) {
4721       // Value = 0xnn00: Op=x, Cmode=101x.
4722       OpCmode = 0xa;
4723       Imm = SplatBits >> 8;
4724       break;
4725     }
4726     return SDValue();
4727
4728   case 32:
4729     // NEON's 32-bit VMOV supports splat values where:
4730     // * only one byte is nonzero, or
4731     // * the least significant byte is 0xff and the second byte is nonzero, or
4732     // * the least significant 2 bytes are 0xff and the third is nonzero.
4733     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4734     if ((SplatBits & ~0xff) == 0) {
4735       // Value = 0x000000nn: Op=x, Cmode=000x.
4736       OpCmode = 0;
4737       Imm = SplatBits;
4738       break;
4739     }
4740     if ((SplatBits & ~0xff00) == 0) {
4741       // Value = 0x0000nn00: Op=x, Cmode=001x.
4742       OpCmode = 0x2;
4743       Imm = SplatBits >> 8;
4744       break;
4745     }
4746     if ((SplatBits & ~0xff0000) == 0) {
4747       // Value = 0x00nn0000: Op=x, Cmode=010x.
4748       OpCmode = 0x4;
4749       Imm = SplatBits >> 16;
4750       break;
4751     }
4752     if ((SplatBits & ~0xff000000) == 0) {
4753       // Value = 0xnn000000: Op=x, Cmode=011x.
4754       OpCmode = 0x6;
4755       Imm = SplatBits >> 24;
4756       break;
4757     }
4758
4759     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4760     if (type == OtherModImm) return SDValue();
4761
4762     if ((SplatBits & ~0xffff) == 0 &&
4763         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4764       // Value = 0x0000nnff: Op=x, Cmode=1100.
4765       OpCmode = 0xc;
4766       Imm = SplatBits >> 8;
4767       break;
4768     }
4769
4770     if ((SplatBits & ~0xffffff) == 0 &&
4771         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4772       // Value = 0x00nnffff: Op=x, Cmode=1101.
4773       OpCmode = 0xd;
4774       Imm = SplatBits >> 16;
4775       break;
4776     }
4777
4778     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4779     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4780     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4781     // and fall through here to test for a valid 64-bit splat.  But, then the
4782     // caller would also need to check and handle the change in size.
4783     return SDValue();
4784
4785   case 64: {
4786     if (type != VMOVModImm)
4787       return SDValue();
4788     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4789     uint64_t BitMask = 0xff;
4790     uint64_t Val = 0;
4791     unsigned ImmMask = 1;
4792     Imm = 0;
4793     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4794       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4795         Val |= BitMask;
4796         Imm |= ImmMask;
4797       } else if ((SplatBits & BitMask) != 0) {
4798         return SDValue();
4799       }
4800       BitMask <<= 8;
4801       ImmMask <<= 1;
4802     }
4803
4804     if (DAG.getDataLayout().isBigEndian())
4805       // swap higher and lower 32 bit word
4806       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4807
4808     // Op=1, Cmode=1110.
4809     OpCmode = 0x1e;
4810     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4811     break;
4812   }
4813
4814   default:
4815     llvm_unreachable("unexpected size for isNEONModifiedImm");
4816   }
4817
4818   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4819   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4820 }
4821
4822 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4823                                            const ARMSubtarget *ST) const {
4824   if (!ST->hasVFP3())
4825     return SDValue();
4826
4827   bool IsDouble = Op.getValueType() == MVT::f64;
4828   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4829
4830   // Use the default (constant pool) lowering for double constants when we have
4831   // an SP-only FPU
4832   if (IsDouble && Subtarget->isFPOnlySP())
4833     return SDValue();
4834
4835   // Try splatting with a VMOV.f32...
4836   APFloat FPVal = CFP->getValueAPF();
4837   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4838
4839   if (ImmVal != -1) {
4840     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4841       // We have code in place to select a valid ConstantFP already, no need to
4842       // do any mangling.
4843       return Op;
4844     }
4845
4846     // It's a float and we are trying to use NEON operations where
4847     // possible. Lower it to a splat followed by an extract.
4848     SDLoc DL(Op);
4849     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4850     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4851                                       NewVal);
4852     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4853                        DAG.getConstant(0, DL, MVT::i32));
4854   }
4855
4856   // The rest of our options are NEON only, make sure that's allowed before
4857   // proceeding..
4858   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4859     return SDValue();
4860
4861   EVT VMovVT;
4862   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4863
4864   // It wouldn't really be worth bothering for doubles except for one very
4865   // important value, which does happen to match: 0.0. So make sure we don't do
4866   // anything stupid.
4867   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4868     return SDValue();
4869
4870   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4871   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4872                                      VMovVT, false, VMOVModImm);
4873   if (NewVal != SDValue()) {
4874     SDLoc DL(Op);
4875     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4876                                       NewVal);
4877     if (IsDouble)
4878       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4879
4880     // It's a float: cast and extract a vector element.
4881     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4882                                        VecConstant);
4883     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4884                        DAG.getConstant(0, DL, MVT::i32));
4885   }
4886
4887   // Finally, try a VMVN.i32
4888   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4889                              false, VMVNModImm);
4890   if (NewVal != SDValue()) {
4891     SDLoc DL(Op);
4892     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4893
4894     if (IsDouble)
4895       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4896
4897     // It's a float: cast and extract a vector element.
4898     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4899                                        VecConstant);
4900     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4901                        DAG.getConstant(0, DL, MVT::i32));
4902   }
4903
4904   return SDValue();
4905 }
4906
4907 // check if an VEXT instruction can handle the shuffle mask when the
4908 // vector sources of the shuffle are the same.
4909 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4910   unsigned NumElts = VT.getVectorNumElements();
4911
4912   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4913   if (M[0] < 0)
4914     return false;
4915
4916   Imm = M[0];
4917
4918   // If this is a VEXT shuffle, the immediate value is the index of the first
4919   // element.  The other shuffle indices must be the successive elements after
4920   // the first one.
4921   unsigned ExpectedElt = Imm;
4922   for (unsigned i = 1; i < NumElts; ++i) {
4923     // Increment the expected index.  If it wraps around, just follow it
4924     // back to index zero and keep going.
4925     ++ExpectedElt;
4926     if (ExpectedElt == NumElts)
4927       ExpectedElt = 0;
4928
4929     if (M[i] < 0) continue; // ignore UNDEF indices
4930     if (ExpectedElt != static_cast<unsigned>(M[i]))
4931       return false;
4932   }
4933
4934   return true;
4935 }
4936
4937
4938 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4939                        bool &ReverseVEXT, unsigned &Imm) {
4940   unsigned NumElts = VT.getVectorNumElements();
4941   ReverseVEXT = false;
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, it may still be
4955     // a VEXT but the source vectors must be swapped.
4956     ExpectedElt += 1;
4957     if (ExpectedElt == NumElts * 2) {
4958       ExpectedElt = 0;
4959       ReverseVEXT = true;
4960     }
4961
4962     if (M[i] < 0) continue; // ignore UNDEF indices
4963     if (ExpectedElt != static_cast<unsigned>(M[i]))
4964       return false;
4965   }
4966
4967   // Adjust the index value if the source operands will be swapped.
4968   if (ReverseVEXT)
4969     Imm -= NumElts;
4970
4971   return true;
4972 }
4973
4974 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4975 /// instruction with the specified blocksize.  (The order of the elements
4976 /// within each block of the vector is reversed.)
4977 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4978   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4979          "Only possible block sizes for VREV are: 16, 32, 64");
4980
4981   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4982   if (EltSz == 64)
4983     return false;
4984
4985   unsigned NumElts = VT.getVectorNumElements();
4986   unsigned BlockElts = M[0] + 1;
4987   // If the first shuffle index is UNDEF, be optimistic.
4988   if (M[0] < 0)
4989     BlockElts = BlockSize / EltSz;
4990
4991   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4992     return false;
4993
4994   for (unsigned i = 0; i < NumElts; ++i) {
4995     if (M[i] < 0) continue; // ignore UNDEF indices
4996     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4997       return false;
4998   }
4999
5000   return true;
5001 }
5002
5003 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5004   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5005   // range, then 0 is placed into the resulting vector. So pretty much any mask
5006   // of 8 elements can work here.
5007   return VT == MVT::v8i8 && M.size() == 8;
5008 }
5009
5010 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5011 // checking that pairs of elements in the shuffle mask represent the same index
5012 // in each vector, incrementing the expected index by 2 at each step.
5013 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5014 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5015 //  v2={e,f,g,h}
5016 // WhichResult gives the offset for each element in the mask based on which
5017 // of the two results it belongs to.
5018 //
5019 // The transpose can be represented either as:
5020 // result1 = shufflevector v1, v2, result1_shuffle_mask
5021 // result2 = shufflevector v1, v2, result2_shuffle_mask
5022 // where v1/v2 and the shuffle masks have the same number of elements
5023 // (here WhichResult (see below) indicates which result is being checked)
5024 //
5025 // or as:
5026 // results = shufflevector v1, v2, shuffle_mask
5027 // where both results are returned in one vector and the shuffle mask has twice
5028 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5029 // want to check the low half and high half of the shuffle mask as if it were
5030 // the other case
5031 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5032   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5033   if (EltSz == 64)
5034     return false;
5035
5036   unsigned NumElts = VT.getVectorNumElements();
5037   if (M.size() != NumElts && M.size() != NumElts*2)
5038     return false;
5039
5040   // If the mask is twice as long as the input vector then we need to check the
5041   // upper and lower parts of the mask with a matching value for WhichResult
5042   // FIXME: A mask with only even values will be rejected in case the first
5043   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5044   // M[0] is used to determine WhichResult
5045   for (unsigned i = 0; i < M.size(); i += NumElts) {
5046     if (M.size() == NumElts * 2)
5047       WhichResult = i / NumElts;
5048     else
5049       WhichResult = M[i] == 0 ? 0 : 1;
5050     for (unsigned j = 0; j < NumElts; j += 2) {
5051       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5052           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5053         return false;
5054     }
5055   }
5056
5057   if (M.size() == NumElts*2)
5058     WhichResult = 0;
5059
5060   return true;
5061 }
5062
5063 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5064 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5065 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5066 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5067   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5068   if (EltSz == 64)
5069     return false;
5070
5071   unsigned NumElts = VT.getVectorNumElements();
5072   if (M.size() != NumElts && M.size() != NumElts*2)
5073     return false;
5074
5075   for (unsigned i = 0; i < M.size(); i += NumElts) {
5076     if (M.size() == NumElts * 2)
5077       WhichResult = i / NumElts;
5078     else
5079       WhichResult = M[i] == 0 ? 0 : 1;
5080     for (unsigned j = 0; j < NumElts; j += 2) {
5081       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5082           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5083         return false;
5084     }
5085   }
5086
5087   if (M.size() == NumElts*2)
5088     WhichResult = 0;
5089
5090   return true;
5091 }
5092
5093 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5094 // that the mask elements are either all even and in steps of size 2 or all odd
5095 // and in steps of size 2.
5096 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5097 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5098 //  v2={e,f,g,h}
5099 // Requires similar checks to that of isVTRNMask with
5100 // respect the how results are returned.
5101 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5102   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5103   if (EltSz == 64)
5104     return false;
5105
5106   unsigned NumElts = VT.getVectorNumElements();
5107   if (M.size() != NumElts && M.size() != NumElts*2)
5108     return false;
5109
5110   for (unsigned i = 0; i < M.size(); i += NumElts) {
5111     WhichResult = M[i] == 0 ? 0 : 1;
5112     for (unsigned j = 0; j < NumElts; ++j) {
5113       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5114         return false;
5115     }
5116   }
5117
5118   if (M.size() == NumElts*2)
5119     WhichResult = 0;
5120
5121   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5122   if (VT.is64BitVector() && EltSz == 32)
5123     return false;
5124
5125   return true;
5126 }
5127
5128 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5129 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5130 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5131 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5132   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5133   if (EltSz == 64)
5134     return false;
5135
5136   unsigned NumElts = VT.getVectorNumElements();
5137   if (M.size() != NumElts && M.size() != NumElts*2)
5138     return false;
5139
5140   unsigned Half = NumElts / 2;
5141   for (unsigned i = 0; i < M.size(); i += NumElts) {
5142     WhichResult = M[i] == 0 ? 0 : 1;
5143     for (unsigned j = 0; j < NumElts; j += Half) {
5144       unsigned Idx = WhichResult;
5145       for (unsigned k = 0; k < Half; ++k) {
5146         int MIdx = M[i + j + k];
5147         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5148           return false;
5149         Idx += 2;
5150       }
5151     }
5152   }
5153
5154   if (M.size() == NumElts*2)
5155     WhichResult = 0;
5156
5157   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5158   if (VT.is64BitVector() && EltSz == 32)
5159     return false;
5160
5161   return true;
5162 }
5163
5164 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5165 // that pairs of elements of the shufflemask represent the same index in each
5166 // vector incrementing sequentially through the vectors.
5167 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5168 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5169 //  v2={e,f,g,h}
5170 // Requires similar checks to that of isVTRNMask with respect the how results
5171 // are returned.
5172 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5173   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5174   if (EltSz == 64)
5175     return false;
5176
5177   unsigned NumElts = VT.getVectorNumElements();
5178   if (M.size() != NumElts && M.size() != NumElts*2)
5179     return false;
5180
5181   for (unsigned i = 0; i < M.size(); i += NumElts) {
5182     WhichResult = M[i] == 0 ? 0 : 1;
5183     unsigned Idx = WhichResult * NumElts / 2;
5184     for (unsigned j = 0; j < NumElts; j += 2) {
5185       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5186           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5187         return false;
5188       Idx += 1;
5189     }
5190   }
5191
5192   if (M.size() == NumElts*2)
5193     WhichResult = 0;
5194
5195   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5196   if (VT.is64BitVector() && EltSz == 32)
5197     return false;
5198
5199   return true;
5200 }
5201
5202 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5203 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5204 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5205 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5206   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5207   if (EltSz == 64)
5208     return false;
5209
5210   unsigned NumElts = VT.getVectorNumElements();
5211   if (M.size() != NumElts && M.size() != NumElts*2)
5212     return false;
5213
5214   for (unsigned i = 0; i < M.size(); i += NumElts) {
5215     WhichResult = M[i] == 0 ? 0 : 1;
5216     unsigned Idx = WhichResult * NumElts / 2;
5217     for (unsigned j = 0; j < NumElts; j += 2) {
5218       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5219           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5220         return false;
5221       Idx += 1;
5222     }
5223   }
5224
5225   if (M.size() == NumElts*2)
5226     WhichResult = 0;
5227
5228   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5229   if (VT.is64BitVector() && EltSz == 32)
5230     return false;
5231
5232   return true;
5233 }
5234
5235 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5236 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5237 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5238                                            unsigned &WhichResult,
5239                                            bool &isV_UNDEF) {
5240   isV_UNDEF = false;
5241   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5242     return ARMISD::VTRN;
5243   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5244     return ARMISD::VUZP;
5245   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5246     return ARMISD::VZIP;
5247
5248   isV_UNDEF = true;
5249   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5250     return ARMISD::VTRN;
5251   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5252     return ARMISD::VUZP;
5253   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5254     return ARMISD::VZIP;
5255
5256   return 0;
5257 }
5258
5259 /// \return true if this is a reverse operation on an vector.
5260 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5261   unsigned NumElts = VT.getVectorNumElements();
5262   // Make sure the mask has the right size.
5263   if (NumElts != M.size())
5264       return false;
5265
5266   // Look for <15, ..., 3, -1, 1, 0>.
5267   for (unsigned i = 0; i != NumElts; ++i)
5268     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5269       return false;
5270
5271   return true;
5272 }
5273
5274 // If N is an integer constant that can be moved into a register in one
5275 // instruction, return an SDValue of such a constant (will become a MOV
5276 // instruction).  Otherwise return null.
5277 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5278                                      const ARMSubtarget *ST, SDLoc dl) {
5279   uint64_t Val;
5280   if (!isa<ConstantSDNode>(N))
5281     return SDValue();
5282   Val = cast<ConstantSDNode>(N)->getZExtValue();
5283
5284   if (ST->isThumb1Only()) {
5285     if (Val <= 255 || ~Val <= 255)
5286       return DAG.getConstant(Val, dl, MVT::i32);
5287   } else {
5288     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5289       return DAG.getConstant(Val, dl, MVT::i32);
5290   }
5291   return SDValue();
5292 }
5293
5294 // If this is a case we can't handle, return null and let the default
5295 // expansion code take care of it.
5296 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5297                                              const ARMSubtarget *ST) const {
5298   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5299   SDLoc dl(Op);
5300   EVT VT = Op.getValueType();
5301
5302   APInt SplatBits, SplatUndef;
5303   unsigned SplatBitSize;
5304   bool HasAnyUndefs;
5305   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5306     if (SplatBitSize <= 64) {
5307       // Check if an immediate VMOV works.
5308       EVT VmovVT;
5309       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5310                                       SplatUndef.getZExtValue(), SplatBitSize,
5311                                       DAG, dl, VmovVT, VT.is128BitVector(),
5312                                       VMOVModImm);
5313       if (Val.getNode()) {
5314         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5315         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5316       }
5317
5318       // Try an immediate VMVN.
5319       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5320       Val = isNEONModifiedImm(NegatedImm,
5321                                       SplatUndef.getZExtValue(), SplatBitSize,
5322                                       DAG, dl, VmovVT, VT.is128BitVector(),
5323                                       VMVNModImm);
5324       if (Val.getNode()) {
5325         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5326         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5327       }
5328
5329       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5330       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5331         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5332         if (ImmVal != -1) {
5333           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5334           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5335         }
5336       }
5337     }
5338   }
5339
5340   // Scan through the operands to see if only one value is used.
5341   //
5342   // As an optimisation, even if more than one value is used it may be more
5343   // profitable to splat with one value then change some lanes.
5344   //
5345   // Heuristically we decide to do this if the vector has a "dominant" value,
5346   // defined as splatted to more than half of the lanes.
5347   unsigned NumElts = VT.getVectorNumElements();
5348   bool isOnlyLowElement = true;
5349   bool usesOnlyOneValue = true;
5350   bool hasDominantValue = false;
5351   bool isConstant = true;
5352
5353   // Map of the number of times a particular SDValue appears in the
5354   // element list.
5355   DenseMap<SDValue, unsigned> ValueCounts;
5356   SDValue Value;
5357   for (unsigned i = 0; i < NumElts; ++i) {
5358     SDValue V = Op.getOperand(i);
5359     if (V.getOpcode() == ISD::UNDEF)
5360       continue;
5361     if (i > 0)
5362       isOnlyLowElement = false;
5363     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5364       isConstant = false;
5365
5366     ValueCounts.insert(std::make_pair(V, 0));
5367     unsigned &Count = ValueCounts[V];
5368
5369     // Is this value dominant? (takes up more than half of the lanes)
5370     if (++Count > (NumElts / 2)) {
5371       hasDominantValue = true;
5372       Value = V;
5373     }
5374   }
5375   if (ValueCounts.size() != 1)
5376     usesOnlyOneValue = false;
5377   if (!Value.getNode() && ValueCounts.size() > 0)
5378     Value = ValueCounts.begin()->first;
5379
5380   if (ValueCounts.size() == 0)
5381     return DAG.getUNDEF(VT);
5382
5383   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5384   // Keep going if we are hitting this case.
5385   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5386     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5387
5388   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5389
5390   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5391   // i32 and try again.
5392   if (hasDominantValue && EltSize <= 32) {
5393     if (!isConstant) {
5394       SDValue N;
5395
5396       // If we are VDUPing a value that comes directly from a vector, that will
5397       // cause an unnecessary move to and from a GPR, where instead we could
5398       // just use VDUPLANE. We can only do this if the lane being extracted
5399       // is at a constant index, as the VDUP from lane instructions only have
5400       // constant-index forms.
5401       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5402           isa<ConstantSDNode>(Value->getOperand(1))) {
5403         // We need to create a new undef vector to use for the VDUPLANE if the
5404         // size of the vector from which we get the value is different than the
5405         // size of the vector that we need to create. We will insert the element
5406         // such that the register coalescer will remove unnecessary copies.
5407         if (VT != Value->getOperand(0).getValueType()) {
5408           ConstantSDNode *constIndex;
5409           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5410           assert(constIndex && "The index is not a constant!");
5411           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5412                              VT.getVectorNumElements();
5413           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5414                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5415                         Value, DAG.getConstant(index, dl, MVT::i32)),
5416                            DAG.getConstant(index, dl, MVT::i32));
5417         } else
5418           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5419                         Value->getOperand(0), Value->getOperand(1));
5420       } else
5421         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5422
5423       if (!usesOnlyOneValue) {
5424         // The dominant value was splatted as 'N', but we now have to insert
5425         // all differing elements.
5426         for (unsigned I = 0; I < NumElts; ++I) {
5427           if (Op.getOperand(I) == Value)
5428             continue;
5429           SmallVector<SDValue, 3> Ops;
5430           Ops.push_back(N);
5431           Ops.push_back(Op.getOperand(I));
5432           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5433           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5434         }
5435       }
5436       return N;
5437     }
5438     if (VT.getVectorElementType().isFloatingPoint()) {
5439       SmallVector<SDValue, 8> Ops;
5440       for (unsigned i = 0; i < NumElts; ++i)
5441         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5442                                   Op.getOperand(i)));
5443       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5444       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5445       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5446       if (Val.getNode())
5447         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5448     }
5449     if (usesOnlyOneValue) {
5450       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5451       if (isConstant && Val.getNode())
5452         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5453     }
5454   }
5455
5456   // If all elements are constants and the case above didn't get hit, fall back
5457   // to the default expansion, which will generate a load from the constant
5458   // pool.
5459   if (isConstant)
5460     return SDValue();
5461
5462   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5463   if (NumElts >= 4) {
5464     SDValue shuffle = ReconstructShuffle(Op, DAG);
5465     if (shuffle != SDValue())
5466       return shuffle;
5467   }
5468
5469   // Vectors with 32- or 64-bit elements can be built by directly assigning
5470   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5471   // will be legalized.
5472   if (EltSize >= 32) {
5473     // Do the expansion with floating-point types, since that is what the VFP
5474     // registers are defined to use, and since i64 is not legal.
5475     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5476     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5477     SmallVector<SDValue, 8> Ops;
5478     for (unsigned i = 0; i < NumElts; ++i)
5479       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5480     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5481     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5482   }
5483
5484   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5485   // know the default expansion would otherwise fall back on something even
5486   // worse. For a vector with one or two non-undef values, that's
5487   // scalar_to_vector for the elements followed by a shuffle (provided the
5488   // shuffle is valid for the target) and materialization element by element
5489   // on the stack followed by a load for everything else.
5490   if (!isConstant && !usesOnlyOneValue) {
5491     SDValue Vec = DAG.getUNDEF(VT);
5492     for (unsigned i = 0 ; i < NumElts; ++i) {
5493       SDValue V = Op.getOperand(i);
5494       if (V.getOpcode() == ISD::UNDEF)
5495         continue;
5496       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5497       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5498     }
5499     return Vec;
5500   }
5501
5502   return SDValue();
5503 }
5504
5505 // Gather data to see if the operation can be modelled as a
5506 // shuffle in combination with VEXTs.
5507 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5508                                               SelectionDAG &DAG) const {
5509   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5510   SDLoc dl(Op);
5511   EVT VT = Op.getValueType();
5512   unsigned NumElts = VT.getVectorNumElements();
5513
5514   struct ShuffleSourceInfo {
5515     SDValue Vec;
5516     unsigned MinElt;
5517     unsigned MaxElt;
5518
5519     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5520     // be compatible with the shuffle we intend to construct. As a result
5521     // ShuffleVec will be some sliding window into the original Vec.
5522     SDValue ShuffleVec;
5523
5524     // Code should guarantee that element i in Vec starts at element "WindowBase
5525     // + i * WindowScale in ShuffleVec".
5526     int WindowBase;
5527     int WindowScale;
5528
5529     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5530     ShuffleSourceInfo(SDValue Vec)
5531         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5532           WindowScale(1) {}
5533   };
5534
5535   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5536   // node.
5537   SmallVector<ShuffleSourceInfo, 2> Sources;
5538   for (unsigned i = 0; i < NumElts; ++i) {
5539     SDValue V = Op.getOperand(i);
5540     if (V.getOpcode() == ISD::UNDEF)
5541       continue;
5542     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5543       // A shuffle can only come from building a vector from various
5544       // elements of other vectors.
5545       return SDValue();
5546     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5547       // Furthermore, shuffles require a constant mask, whereas extractelts
5548       // accept variable indices.
5549       return SDValue();
5550     }
5551
5552     // Add this element source to the list if it's not already there.
5553     SDValue SourceVec = V.getOperand(0);
5554     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5555     if (Source == Sources.end())
5556       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5557
5558     // Update the minimum and maximum lane number seen.
5559     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5560     Source->MinElt = std::min(Source->MinElt, EltNo);
5561     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5562   }
5563
5564   // Currently only do something sane when at most two source vectors
5565   // are involved.
5566   if (Sources.size() > 2)
5567     return SDValue();
5568
5569   // Find out the smallest element size among result and two sources, and use
5570   // it as element size to build the shuffle_vector.
5571   EVT SmallestEltTy = VT.getVectorElementType();
5572   for (auto &Source : Sources) {
5573     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5574     if (SrcEltTy.bitsLT(SmallestEltTy))
5575       SmallestEltTy = SrcEltTy;
5576   }
5577   unsigned ResMultiplier =
5578       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5579   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5580   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5581
5582   // If the source vector is too wide or too narrow, we may nevertheless be able
5583   // to construct a compatible shuffle either by concatenating it with UNDEF or
5584   // extracting a suitable range of elements.
5585   for (auto &Src : Sources) {
5586     EVT SrcVT = Src.ShuffleVec.getValueType();
5587
5588     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5589       continue;
5590
5591     // This stage of the search produces a source with the same element type as
5592     // the original, but with a total width matching the BUILD_VECTOR output.
5593     EVT EltVT = SrcVT.getVectorElementType();
5594     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5595     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5596
5597     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5598       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5599         return SDValue();
5600       // We can pad out the smaller vector for free, so if it's part of a
5601       // shuffle...
5602       Src.ShuffleVec =
5603           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5604                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5605       continue;
5606     }
5607
5608     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5609       return SDValue();
5610
5611     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5612       // Span too large for a VEXT to cope
5613       return SDValue();
5614     }
5615
5616     if (Src.MinElt >= NumSrcElts) {
5617       // The extraction can just take the second half
5618       Src.ShuffleVec =
5619           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5620                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5621       Src.WindowBase = -NumSrcElts;
5622     } else if (Src.MaxElt < NumSrcElts) {
5623       // The extraction can just take the first half
5624       Src.ShuffleVec =
5625           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5626                       DAG.getConstant(0, dl, MVT::i32));
5627     } else {
5628       // An actual VEXT is needed
5629       SDValue VEXTSrc1 =
5630           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5631                       DAG.getConstant(0, dl, MVT::i32));
5632       SDValue VEXTSrc2 =
5633           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5634                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5635
5636       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5637                                    VEXTSrc2,
5638                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
5639       Src.WindowBase = -Src.MinElt;
5640     }
5641   }
5642
5643   // Another possible incompatibility occurs from the vector element types. We
5644   // can fix this by bitcasting the source vectors to the same type we intend
5645   // for the shuffle.
5646   for (auto &Src : Sources) {
5647     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5648     if (SrcEltTy == SmallestEltTy)
5649       continue;
5650     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5651     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5652     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5653     Src.WindowBase *= Src.WindowScale;
5654   }
5655
5656   // Final sanity check before we try to actually produce a shuffle.
5657   DEBUG(
5658     for (auto Src : Sources)
5659       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5660   );
5661
5662   // The stars all align, our next step is to produce the mask for the shuffle.
5663   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5664   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5665   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5666     SDValue Entry = Op.getOperand(i);
5667     if (Entry.getOpcode() == ISD::UNDEF)
5668       continue;
5669
5670     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5671     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5672
5673     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5674     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5675     // segment.
5676     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5677     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5678                                VT.getVectorElementType().getSizeInBits());
5679     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5680
5681     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5682     // starting at the appropriate offset.
5683     int *LaneMask = &Mask[i * ResMultiplier];
5684
5685     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5686     ExtractBase += NumElts * (Src - Sources.begin());
5687     for (int j = 0; j < LanesDefined; ++j)
5688       LaneMask[j] = ExtractBase + j;
5689   }
5690
5691   // Final check before we try to produce nonsense...
5692   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5693     return SDValue();
5694
5695   // We can't handle more than two sources. This should have already
5696   // been checked before this point.
5697   assert(Sources.size() <= 2 && "Too many sources!");
5698
5699   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5700   for (unsigned i = 0; i < Sources.size(); ++i)
5701     ShuffleOps[i] = Sources[i].ShuffleVec;
5702
5703   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5704                                          ShuffleOps[1], &Mask[0]);
5705   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5706 }
5707
5708 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5709 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5710 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5711 /// are assumed to be legal.
5712 bool
5713 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5714                                       EVT VT) const {
5715   if (VT.getVectorNumElements() == 4 &&
5716       (VT.is128BitVector() || VT.is64BitVector())) {
5717     unsigned PFIndexes[4];
5718     for (unsigned i = 0; i != 4; ++i) {
5719       if (M[i] < 0)
5720         PFIndexes[i] = 8;
5721       else
5722         PFIndexes[i] = M[i];
5723     }
5724
5725     // Compute the index in the perfect shuffle table.
5726     unsigned PFTableIndex =
5727       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5728     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5729     unsigned Cost = (PFEntry >> 30);
5730
5731     if (Cost <= 4)
5732       return true;
5733   }
5734
5735   bool ReverseVEXT, isV_UNDEF;
5736   unsigned Imm, WhichResult;
5737
5738   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5739   return (EltSize >= 32 ||
5740           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5741           isVREVMask(M, VT, 64) ||
5742           isVREVMask(M, VT, 32) ||
5743           isVREVMask(M, VT, 16) ||
5744           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5745           isVTBLMask(M, VT) ||
5746           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5747           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5748 }
5749
5750 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5751 /// the specified operations to build the shuffle.
5752 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5753                                       SDValue RHS, SelectionDAG &DAG,
5754                                       SDLoc dl) {
5755   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5756   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5757   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5758
5759   enum {
5760     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5761     OP_VREV,
5762     OP_VDUP0,
5763     OP_VDUP1,
5764     OP_VDUP2,
5765     OP_VDUP3,
5766     OP_VEXT1,
5767     OP_VEXT2,
5768     OP_VEXT3,
5769     OP_VUZPL, // VUZP, left result
5770     OP_VUZPR, // VUZP, right result
5771     OP_VZIPL, // VZIP, left result
5772     OP_VZIPR, // VZIP, right result
5773     OP_VTRNL, // VTRN, left result
5774     OP_VTRNR  // VTRN, right result
5775   };
5776
5777   if (OpNum == OP_COPY) {
5778     if (LHSID == (1*9+2)*9+3) return LHS;
5779     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5780     return RHS;
5781   }
5782
5783   SDValue OpLHS, OpRHS;
5784   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5785   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5786   EVT VT = OpLHS.getValueType();
5787
5788   switch (OpNum) {
5789   default: llvm_unreachable("Unknown shuffle opcode!");
5790   case OP_VREV:
5791     // VREV divides the vector in half and swaps within the half.
5792     if (VT.getVectorElementType() == MVT::i32 ||
5793         VT.getVectorElementType() == MVT::f32)
5794       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5795     // vrev <4 x i16> -> VREV32
5796     if (VT.getVectorElementType() == MVT::i16)
5797       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5798     // vrev <4 x i8> -> VREV16
5799     assert(VT.getVectorElementType() == MVT::i8);
5800     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5801   case OP_VDUP0:
5802   case OP_VDUP1:
5803   case OP_VDUP2:
5804   case OP_VDUP3:
5805     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5806                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5807   case OP_VEXT1:
5808   case OP_VEXT2:
5809   case OP_VEXT3:
5810     return DAG.getNode(ARMISD::VEXT, dl, VT,
5811                        OpLHS, OpRHS,
5812                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5813   case OP_VUZPL:
5814   case OP_VUZPR:
5815     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5816                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5817   case OP_VZIPL:
5818   case OP_VZIPR:
5819     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5820                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5821   case OP_VTRNL:
5822   case OP_VTRNR:
5823     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5824                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5825   }
5826 }
5827
5828 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5829                                        ArrayRef<int> ShuffleMask,
5830                                        SelectionDAG &DAG) {
5831   // Check to see if we can use the VTBL instruction.
5832   SDValue V1 = Op.getOperand(0);
5833   SDValue V2 = Op.getOperand(1);
5834   SDLoc DL(Op);
5835
5836   SmallVector<SDValue, 8> VTBLMask;
5837   for (ArrayRef<int>::iterator
5838          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5839     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5840
5841   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5842     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5843                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5844
5845   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5846                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5847 }
5848
5849 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5850                                                       SelectionDAG &DAG) {
5851   SDLoc DL(Op);
5852   SDValue OpLHS = Op.getOperand(0);
5853   EVT VT = OpLHS.getValueType();
5854
5855   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5856          "Expect an v8i16/v16i8 type");
5857   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5858   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5859   // extract the first 8 bytes into the top double word and the last 8 bytes
5860   // into the bottom double word. The v8i16 case is similar.
5861   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5862   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5863                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5864 }
5865
5866 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5867   SDValue V1 = Op.getOperand(0);
5868   SDValue V2 = Op.getOperand(1);
5869   SDLoc dl(Op);
5870   EVT VT = Op.getValueType();
5871   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5872
5873   // Convert shuffles that are directly supported on NEON to target-specific
5874   // DAG nodes, instead of keeping them as shuffles and matching them again
5875   // during code selection.  This is more efficient and avoids the possibility
5876   // of inconsistencies between legalization and selection.
5877   // FIXME: floating-point vectors should be canonicalized to integer vectors
5878   // of the same time so that they get CSEd properly.
5879   ArrayRef<int> ShuffleMask = SVN->getMask();
5880
5881   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5882   if (EltSize <= 32) {
5883     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5884       int Lane = SVN->getSplatIndex();
5885       // If this is undef splat, generate it via "just" vdup, if possible.
5886       if (Lane == -1) Lane = 0;
5887
5888       // Test if V1 is a SCALAR_TO_VECTOR.
5889       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5890         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5891       }
5892       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5893       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5894       // reaches it).
5895       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5896           !isa<ConstantSDNode>(V1.getOperand(0))) {
5897         bool IsScalarToVector = true;
5898         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5899           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5900             IsScalarToVector = false;
5901             break;
5902           }
5903         if (IsScalarToVector)
5904           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5905       }
5906       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5907                          DAG.getConstant(Lane, dl, MVT::i32));
5908     }
5909
5910     bool ReverseVEXT;
5911     unsigned Imm;
5912     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5913       if (ReverseVEXT)
5914         std::swap(V1, V2);
5915       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5916                          DAG.getConstant(Imm, dl, MVT::i32));
5917     }
5918
5919     if (isVREVMask(ShuffleMask, VT, 64))
5920       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5921     if (isVREVMask(ShuffleMask, VT, 32))
5922       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5923     if (isVREVMask(ShuffleMask, VT, 16))
5924       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5925
5926     if (V2->getOpcode() == ISD::UNDEF &&
5927         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5928       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5929                          DAG.getConstant(Imm, dl, MVT::i32));
5930     }
5931
5932     // Check for Neon shuffles that modify both input vectors in place.
5933     // If both results are used, i.e., if there are two shuffles with the same
5934     // source operands and with masks corresponding to both results of one of
5935     // these operations, DAG memoization will ensure that a single node is
5936     // used for both shuffles.
5937     unsigned WhichResult;
5938     bool isV_UNDEF;
5939     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5940             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5941       if (isV_UNDEF)
5942         V2 = V1;
5943       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5944           .getValue(WhichResult);
5945     }
5946
5947     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5948     // shuffles that produce a result larger than their operands with:
5949     //   shuffle(concat(v1, undef), concat(v2, undef))
5950     // ->
5951     //   shuffle(concat(v1, v2), undef)
5952     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5953     //
5954     // This is useful in the general case, but there are special cases where
5955     // native shuffles produce larger results: the two-result ops.
5956     //
5957     // Look through the concat when lowering them:
5958     //   shuffle(concat(v1, v2), undef)
5959     // ->
5960     //   concat(VZIP(v1, v2):0, :1)
5961     //
5962     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5963         V2->getOpcode() == ISD::UNDEF) {
5964       SDValue SubV1 = V1->getOperand(0);
5965       SDValue SubV2 = V1->getOperand(1);
5966       EVT SubVT = SubV1.getValueType();
5967
5968       // We expect these to have been canonicalized to -1.
5969       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5970         return i < (int)VT.getVectorNumElements();
5971       }) && "Unexpected shuffle index into UNDEF operand!");
5972
5973       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5974               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5975         if (isV_UNDEF)
5976           SubV2 = SubV1;
5977         assert((WhichResult == 0) &&
5978                "In-place shuffle of concat can only have one result!");
5979         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5980                                   SubV1, SubV2);
5981         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5982                            Res.getValue(1));
5983       }
5984     }
5985   }
5986
5987   // If the shuffle is not directly supported and it has 4 elements, use
5988   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5989   unsigned NumElts = VT.getVectorNumElements();
5990   if (NumElts == 4) {
5991     unsigned PFIndexes[4];
5992     for (unsigned i = 0; i != 4; ++i) {
5993       if (ShuffleMask[i] < 0)
5994         PFIndexes[i] = 8;
5995       else
5996         PFIndexes[i] = ShuffleMask[i];
5997     }
5998
5999     // Compute the index in the perfect shuffle table.
6000     unsigned PFTableIndex =
6001       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6002     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6003     unsigned Cost = (PFEntry >> 30);
6004
6005     if (Cost <= 4)
6006       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6007   }
6008
6009   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6010   if (EltSize >= 32) {
6011     // Do the expansion with floating-point types, since that is what the VFP
6012     // registers are defined to use, and since i64 is not legal.
6013     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6014     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6015     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6016     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6017     SmallVector<SDValue, 8> Ops;
6018     for (unsigned i = 0; i < NumElts; ++i) {
6019       if (ShuffleMask[i] < 0)
6020         Ops.push_back(DAG.getUNDEF(EltVT));
6021       else
6022         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6023                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6024                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6025                                                   dl, MVT::i32)));
6026     }
6027     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6028     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6029   }
6030
6031   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6032     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6033
6034   if (VT == MVT::v8i8) {
6035     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6036     if (NewOp.getNode())
6037       return NewOp;
6038   }
6039
6040   return SDValue();
6041 }
6042
6043 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6044   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6045   SDValue Lane = Op.getOperand(2);
6046   if (!isa<ConstantSDNode>(Lane))
6047     return SDValue();
6048
6049   return Op;
6050 }
6051
6052 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6053   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6054   SDValue Lane = Op.getOperand(1);
6055   if (!isa<ConstantSDNode>(Lane))
6056     return SDValue();
6057
6058   SDValue Vec = Op.getOperand(0);
6059   if (Op.getValueType() == MVT::i32 &&
6060       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6061     SDLoc dl(Op);
6062     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6063   }
6064
6065   return Op;
6066 }
6067
6068 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6069   // The only time a CONCAT_VECTORS operation can have legal types is when
6070   // two 64-bit vectors are concatenated to a 128-bit vector.
6071   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6072          "unexpected CONCAT_VECTORS");
6073   SDLoc dl(Op);
6074   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6075   SDValue Op0 = Op.getOperand(0);
6076   SDValue Op1 = Op.getOperand(1);
6077   if (Op0.getOpcode() != ISD::UNDEF)
6078     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6079                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6080                       DAG.getIntPtrConstant(0, dl));
6081   if (Op1.getOpcode() != ISD::UNDEF)
6082     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6083                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6084                       DAG.getIntPtrConstant(1, dl));
6085   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6086 }
6087
6088 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6089 /// element has been zero/sign-extended, depending on the isSigned parameter,
6090 /// from an integer type half its size.
6091 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6092                                    bool isSigned) {
6093   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6094   EVT VT = N->getValueType(0);
6095   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6096     SDNode *BVN = N->getOperand(0).getNode();
6097     if (BVN->getValueType(0) != MVT::v4i32 ||
6098         BVN->getOpcode() != ISD::BUILD_VECTOR)
6099       return false;
6100     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6101     unsigned HiElt = 1 - LoElt;
6102     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6103     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6104     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6105     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6106     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6107       return false;
6108     if (isSigned) {
6109       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6110           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6111         return true;
6112     } else {
6113       if (Hi0->isNullValue() && Hi1->isNullValue())
6114         return true;
6115     }
6116     return false;
6117   }
6118
6119   if (N->getOpcode() != ISD::BUILD_VECTOR)
6120     return false;
6121
6122   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6123     SDNode *Elt = N->getOperand(i).getNode();
6124     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6125       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6126       unsigned HalfSize = EltSize / 2;
6127       if (isSigned) {
6128         if (!isIntN(HalfSize, C->getSExtValue()))
6129           return false;
6130       } else {
6131         if (!isUIntN(HalfSize, C->getZExtValue()))
6132           return false;
6133       }
6134       continue;
6135     }
6136     return false;
6137   }
6138
6139   return true;
6140 }
6141
6142 /// isSignExtended - Check if a node is a vector value that is sign-extended
6143 /// or a constant BUILD_VECTOR with sign-extended elements.
6144 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6145   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6146     return true;
6147   if (isExtendedBUILD_VECTOR(N, DAG, true))
6148     return true;
6149   return false;
6150 }
6151
6152 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6153 /// or a constant BUILD_VECTOR with zero-extended elements.
6154 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6155   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6156     return true;
6157   if (isExtendedBUILD_VECTOR(N, DAG, false))
6158     return true;
6159   return false;
6160 }
6161
6162 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6163   if (OrigVT.getSizeInBits() >= 64)
6164     return OrigVT;
6165
6166   assert(OrigVT.isSimple() && "Expecting a simple value type");
6167
6168   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6169   switch (OrigSimpleTy) {
6170   default: llvm_unreachable("Unexpected Vector Type");
6171   case MVT::v2i8:
6172   case MVT::v2i16:
6173      return MVT::v2i32;
6174   case MVT::v4i8:
6175     return  MVT::v4i16;
6176   }
6177 }
6178
6179 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6180 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6181 /// We insert the required extension here to get the vector to fill a D register.
6182 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6183                                             const EVT &OrigTy,
6184                                             const EVT &ExtTy,
6185                                             unsigned ExtOpcode) {
6186   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6187   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6188   // 64-bits we need to insert a new extension so that it will be 64-bits.
6189   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6190   if (OrigTy.getSizeInBits() >= 64)
6191     return N;
6192
6193   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6194   EVT NewVT = getExtensionTo64Bits(OrigTy);
6195
6196   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6197 }
6198
6199 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6200 /// does not do any sign/zero extension. If the original vector is less
6201 /// than 64 bits, an appropriate extension will be added after the load to
6202 /// reach a total size of 64 bits. We have to add the extension separately
6203 /// because ARM does not have a sign/zero extending load for vectors.
6204 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6205   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6206
6207   // The load already has the right type.
6208   if (ExtendedTy == LD->getMemoryVT())
6209     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6210                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6211                 LD->isNonTemporal(), LD->isInvariant(),
6212                 LD->getAlignment());
6213
6214   // We need to create a zextload/sextload. We cannot just create a load
6215   // followed by a zext/zext node because LowerMUL is also run during normal
6216   // operation legalization where we can't create illegal types.
6217   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6218                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6219                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6220                         LD->isNonTemporal(), LD->getAlignment());
6221 }
6222
6223 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6224 /// extending load, or BUILD_VECTOR with extended elements, return the
6225 /// unextended value. The unextended vector should be 64 bits so that it can
6226 /// be used as an operand to a VMULL instruction. If the original vector size
6227 /// before extension is less than 64 bits we add a an extension to resize
6228 /// the vector to 64 bits.
6229 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6230   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6231     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6232                                         N->getOperand(0)->getValueType(0),
6233                                         N->getValueType(0),
6234                                         N->getOpcode());
6235
6236   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6237     return SkipLoadExtensionForVMULL(LD, DAG);
6238
6239   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6240   // have been legalized as a BITCAST from v4i32.
6241   if (N->getOpcode() == ISD::BITCAST) {
6242     SDNode *BVN = N->getOperand(0).getNode();
6243     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6244            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6245     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6246     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6247                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6248   }
6249   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6250   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6251   EVT VT = N->getValueType(0);
6252   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6253   unsigned NumElts = VT.getVectorNumElements();
6254   MVT TruncVT = MVT::getIntegerVT(EltSize);
6255   SmallVector<SDValue, 8> Ops;
6256   SDLoc dl(N);
6257   for (unsigned i = 0; i != NumElts; ++i) {
6258     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6259     const APInt &CInt = C->getAPIntValue();
6260     // Element types smaller than 32 bits are not legal, so use i32 elements.
6261     // The values are implicitly truncated so sext vs. zext doesn't matter.
6262     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6263   }
6264   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6265                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6266 }
6267
6268 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6269   unsigned Opcode = N->getOpcode();
6270   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6271     SDNode *N0 = N->getOperand(0).getNode();
6272     SDNode *N1 = N->getOperand(1).getNode();
6273     return N0->hasOneUse() && N1->hasOneUse() &&
6274       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6275   }
6276   return false;
6277 }
6278
6279 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6280   unsigned Opcode = N->getOpcode();
6281   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6282     SDNode *N0 = N->getOperand(0).getNode();
6283     SDNode *N1 = N->getOperand(1).getNode();
6284     return N0->hasOneUse() && N1->hasOneUse() &&
6285       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6286   }
6287   return false;
6288 }
6289
6290 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6291   // Multiplications are only custom-lowered for 128-bit vectors so that
6292   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6293   EVT VT = Op.getValueType();
6294   assert(VT.is128BitVector() && VT.isInteger() &&
6295          "unexpected type for custom-lowering ISD::MUL");
6296   SDNode *N0 = Op.getOperand(0).getNode();
6297   SDNode *N1 = Op.getOperand(1).getNode();
6298   unsigned NewOpc = 0;
6299   bool isMLA = false;
6300   bool isN0SExt = isSignExtended(N0, DAG);
6301   bool isN1SExt = isSignExtended(N1, DAG);
6302   if (isN0SExt && isN1SExt)
6303     NewOpc = ARMISD::VMULLs;
6304   else {
6305     bool isN0ZExt = isZeroExtended(N0, DAG);
6306     bool isN1ZExt = isZeroExtended(N1, DAG);
6307     if (isN0ZExt && isN1ZExt)
6308       NewOpc = ARMISD::VMULLu;
6309     else if (isN1SExt || isN1ZExt) {
6310       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6311       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6312       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6313         NewOpc = ARMISD::VMULLs;
6314         isMLA = true;
6315       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6316         NewOpc = ARMISD::VMULLu;
6317         isMLA = true;
6318       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6319         std::swap(N0, N1);
6320         NewOpc = ARMISD::VMULLu;
6321         isMLA = true;
6322       }
6323     }
6324
6325     if (!NewOpc) {
6326       if (VT == MVT::v2i64)
6327         // Fall through to expand this.  It is not legal.
6328         return SDValue();
6329       else
6330         // Other vector multiplications are legal.
6331         return Op;
6332     }
6333   }
6334
6335   // Legalize to a VMULL instruction.
6336   SDLoc DL(Op);
6337   SDValue Op0;
6338   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6339   if (!isMLA) {
6340     Op0 = SkipExtensionForVMULL(N0, DAG);
6341     assert(Op0.getValueType().is64BitVector() &&
6342            Op1.getValueType().is64BitVector() &&
6343            "unexpected types for extended operands to VMULL");
6344     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6345   }
6346
6347   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6348   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6349   //   vmull q0, d4, d6
6350   //   vmlal q0, d5, d6
6351   // is faster than
6352   //   vaddl q0, d4, d5
6353   //   vmovl q1, d6
6354   //   vmul  q0, q0, q1
6355   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6356   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6357   EVT Op1VT = Op1.getValueType();
6358   return DAG.getNode(N0->getOpcode(), DL, VT,
6359                      DAG.getNode(NewOpc, DL, VT,
6360                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6361                      DAG.getNode(NewOpc, DL, VT,
6362                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6363 }
6364
6365 static SDValue
6366 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6367   // TODO: Should this propagate fast-math-flags?
6368
6369   // Convert to float
6370   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6371   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6372   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6373   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6374   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6375   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6376   // Get reciprocal estimate.
6377   // float4 recip = vrecpeq_f32(yf);
6378   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6379                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6380                    Y);
6381   // Because char has a smaller range than uchar, we can actually get away
6382   // without any newton steps.  This requires that we use a weird bias
6383   // of 0xb000, however (again, this has been exhaustively tested).
6384   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6385   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6386   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6387   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6388   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6389   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6390   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6391   // Convert back to short.
6392   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6393   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6394   return X;
6395 }
6396
6397 static SDValue
6398 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6399   // TODO: Should this propagate fast-math-flags?
6400
6401   SDValue N2;
6402   // Convert to float.
6403   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6404   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6405   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6406   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6407   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6408   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6409
6410   // Use reciprocal estimate and one refinement step.
6411   // float4 recip = vrecpeq_f32(yf);
6412   // recip *= vrecpsq_f32(yf, recip);
6413   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6414                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6415                    N1);
6416   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6417                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6418                    N1, N2);
6419   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6420   // Because short has a smaller range than ushort, we can actually get away
6421   // with only a single newton step.  This requires that we use a weird bias
6422   // of 89, however (again, this has been exhaustively tested).
6423   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6424   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6425   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6426   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6427   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6428   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6429   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6430   // Convert back to integer and return.
6431   // return vmovn_s32(vcvt_s32_f32(result));
6432   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6433   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6434   return N0;
6435 }
6436
6437 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6438   EVT VT = Op.getValueType();
6439   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6440          "unexpected type for custom-lowering ISD::SDIV");
6441
6442   SDLoc dl(Op);
6443   SDValue N0 = Op.getOperand(0);
6444   SDValue N1 = Op.getOperand(1);
6445   SDValue N2, N3;
6446
6447   if (VT == MVT::v8i8) {
6448     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6449     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6450
6451     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6452                      DAG.getIntPtrConstant(4, dl));
6453     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6454                      DAG.getIntPtrConstant(4, dl));
6455     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6456                      DAG.getIntPtrConstant(0, dl));
6457     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6458                      DAG.getIntPtrConstant(0, dl));
6459
6460     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6461     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6462
6463     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6464     N0 = LowerCONCAT_VECTORS(N0, DAG);
6465
6466     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6467     return N0;
6468   }
6469   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6470 }
6471
6472 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6473   // TODO: Should this propagate fast-math-flags?
6474   EVT VT = Op.getValueType();
6475   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6476          "unexpected type for custom-lowering ISD::UDIV");
6477
6478   SDLoc dl(Op);
6479   SDValue N0 = Op.getOperand(0);
6480   SDValue N1 = Op.getOperand(1);
6481   SDValue N2, N3;
6482
6483   if (VT == MVT::v8i8) {
6484     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6485     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6486
6487     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6488                      DAG.getIntPtrConstant(4, dl));
6489     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6490                      DAG.getIntPtrConstant(4, dl));
6491     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6492                      DAG.getIntPtrConstant(0, dl));
6493     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6494                      DAG.getIntPtrConstant(0, dl));
6495
6496     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6497     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6498
6499     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6500     N0 = LowerCONCAT_VECTORS(N0, DAG);
6501
6502     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6503                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6504                                      MVT::i32),
6505                      N0);
6506     return N0;
6507   }
6508
6509   // v4i16 sdiv ... Convert to float.
6510   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6511   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6512   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6513   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6514   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6515   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6516
6517   // Use reciprocal estimate and two refinement steps.
6518   // float4 recip = vrecpeq_f32(yf);
6519   // recip *= vrecpsq_f32(yf, recip);
6520   // recip *= vrecpsq_f32(yf, recip);
6521   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6522                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6523                    BN1);
6524   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6525                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6526                    BN1, N2);
6527   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6528   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6529                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6530                    BN1, N2);
6531   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6532   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6533   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6534   // and that it will never cause us to return an answer too large).
6535   // float4 result = as_float4(as_int4(xf*recip) + 2);
6536   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6537   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6538   N1 = DAG.getConstant(2, dl, MVT::i32);
6539   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6540   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6541   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6542   // Convert back to integer and return.
6543   // return vmovn_u32(vcvt_s32_f32(result));
6544   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6545   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6546   return N0;
6547 }
6548
6549 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6550   EVT VT = Op.getNode()->getValueType(0);
6551   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6552
6553   unsigned Opc;
6554   bool ExtraOp = false;
6555   switch (Op.getOpcode()) {
6556   default: llvm_unreachable("Invalid code");
6557   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6558   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6559   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6560   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6561   }
6562
6563   if (!ExtraOp)
6564     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6565                        Op.getOperand(1));
6566   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6567                      Op.getOperand(1), Op.getOperand(2));
6568 }
6569
6570 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6571   assert(Subtarget->isTargetDarwin());
6572
6573   // For iOS, we want to call an alternative entry point: __sincos_stret,
6574   // return values are passed via sret.
6575   SDLoc dl(Op);
6576   SDValue Arg = Op.getOperand(0);
6577   EVT ArgVT = Arg.getValueType();
6578   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6579   auto PtrVT = getPointerTy(DAG.getDataLayout());
6580
6581   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6582
6583   // Pair of floats / doubles used to pass the result.
6584   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6585
6586   // Create stack object for sret.
6587   auto &DL = DAG.getDataLayout();
6588   const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6589   const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6590   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6591   SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6592
6593   ArgListTy Args;
6594   ArgListEntry Entry;
6595
6596   Entry.Node = SRet;
6597   Entry.Ty = RetTy->getPointerTo();
6598   Entry.isSExt = false;
6599   Entry.isZExt = false;
6600   Entry.isSRet = true;
6601   Args.push_back(Entry);
6602
6603   Entry.Node = Arg;
6604   Entry.Ty = ArgTy;
6605   Entry.isSExt = false;
6606   Entry.isZExt = false;
6607   Args.push_back(Entry);
6608
6609   const char *LibcallName =
6610       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6611   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6612
6613   TargetLowering::CallLoweringInfo CLI(DAG);
6614   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6615     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6616                std::move(Args), 0)
6617     .setDiscardResult();
6618
6619   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6620
6621   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6622                                 MachinePointerInfo(), false, false, false, 0);
6623
6624   // Address of cos field.
6625   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6626                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6627   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6628                                 MachinePointerInfo(), false, false, false, 0);
6629
6630   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6631   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6632                      LoadSin.getValue(0), LoadCos.getValue(0));
6633 }
6634
6635 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6636                                                   bool Signed,
6637                                                   SDValue &Chain) const {
6638   EVT VT = Op.getValueType();
6639   assert((VT == MVT::i32 || VT == MVT::i64) &&
6640          "unexpected type for custom lowering DIV");
6641   SDLoc dl(Op);
6642
6643   const auto &DL = DAG.getDataLayout();
6644   const auto &TLI = DAG.getTargetLoweringInfo();
6645
6646   const char *Name = nullptr;
6647   if (Signed)
6648     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6649   else
6650     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6651
6652   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6653
6654   ARMTargetLowering::ArgListTy Args;
6655
6656   for (auto AI : {1, 0}) {
6657     ArgListEntry Arg;
6658     Arg.Node = Op.getOperand(AI);
6659     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6660     Args.push_back(Arg);
6661   }
6662
6663   CallLoweringInfo CLI(DAG);
6664   CLI.setDebugLoc(dl)
6665     .setChain(Chain)
6666     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6667                ES, std::move(Args), 0);
6668
6669   return LowerCallTo(CLI).first;
6670 }
6671
6672 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
6673                                             bool Signed) const {
6674   assert(Op.getValueType() == MVT::i32 &&
6675          "unexpected type for custom lowering DIV");
6676   SDLoc dl(Op);
6677
6678   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6679                                DAG.getEntryNode(), Op.getOperand(1));
6680
6681   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6682 }
6683
6684 void ARMTargetLowering::ExpandDIV_Windows(
6685     SDValue Op, SelectionDAG &DAG, bool Signed,
6686     SmallVectorImpl<SDValue> &Results) const {
6687   const auto &DL = DAG.getDataLayout();
6688   const auto &TLI = DAG.getTargetLoweringInfo();
6689
6690   assert(Op.getValueType() == MVT::i64 &&
6691          "unexpected type for custom lowering DIV");
6692   SDLoc dl(Op);
6693
6694   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6695                            DAG.getConstant(0, dl, MVT::i32));
6696   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6697                            DAG.getConstant(1, dl, MVT::i32));
6698   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6699
6700   SDValue DBZCHK =
6701       DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6702
6703   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6704
6705   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6706   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6707                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6708   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6709
6710   Results.push_back(Lower);
6711   Results.push_back(Upper);
6712 }
6713
6714 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6715   // Monotonic load/store is legal for all targets
6716   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6717     return Op;
6718
6719   // Acquire/Release load/store is not legal for targets without a
6720   // dmb or equivalent available.
6721   return SDValue();
6722 }
6723
6724 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6725                                     SmallVectorImpl<SDValue> &Results,
6726                                     SelectionDAG &DAG,
6727                                     const ARMSubtarget *Subtarget) {
6728   SDLoc DL(N);
6729   // Under Power Management extensions, the cycle-count is:
6730   //    mrc p15, #0, <Rt>, c9, c13, #0
6731   SDValue Ops[] = { N->getOperand(0), // Chain
6732                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6733                     DAG.getConstant(15, DL, MVT::i32),
6734                     DAG.getConstant(0, DL, MVT::i32),
6735                     DAG.getConstant(9, DL, MVT::i32),
6736                     DAG.getConstant(13, DL, MVT::i32),
6737                     DAG.getConstant(0, DL, MVT::i32)
6738   };
6739
6740   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6741                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
6742   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6743                                 DAG.getConstant(0, DL, MVT::i32)));
6744   Results.push_back(Cycles32.getValue(1));
6745 }
6746
6747 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6748   switch (Op.getOpcode()) {
6749   default: llvm_unreachable("Don't know how to custom lower this!");
6750   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6751   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6752   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6753   case ISD::GlobalAddress:
6754     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6755     default: llvm_unreachable("unknown object format");
6756     case Triple::COFF:
6757       return LowerGlobalAddressWindows(Op, DAG);
6758     case Triple::ELF:
6759       return LowerGlobalAddressELF(Op, DAG);
6760     case Triple::MachO:
6761       return LowerGlobalAddressDarwin(Op, DAG);
6762     }
6763   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6764   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6765   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6766   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6767   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6768   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6769   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6770   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6771   case ISD::SINT_TO_FP:
6772   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6773   case ISD::FP_TO_SINT:
6774   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6775   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6776   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6777   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6778   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6779   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6780   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6781   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6782   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6783                                                                Subtarget);
6784   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6785   case ISD::SHL:
6786   case ISD::SRL:
6787   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6788   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
6789   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
6790   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6791   case ISD::SRL_PARTS:
6792   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6793   case ISD::CTTZ:
6794   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6795   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6796   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6797   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6798   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6799   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6800   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6801   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6802   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6803   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6804   case ISD::MUL:           return LowerMUL(Op, DAG);
6805   case ISD::SDIV:
6806     if (Subtarget->isTargetWindows())
6807       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
6808     return LowerSDIV(Op, DAG);
6809   case ISD::UDIV:
6810     if (Subtarget->isTargetWindows())
6811       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
6812     return LowerUDIV(Op, DAG);
6813   case ISD::ADDC:
6814   case ISD::ADDE:
6815   case ISD::SUBC:
6816   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6817   case ISD::SADDO:
6818   case ISD::UADDO:
6819   case ISD::SSUBO:
6820   case ISD::USUBO:
6821     return LowerXALUO(Op, DAG);
6822   case ISD::ATOMIC_LOAD:
6823   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6824   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6825   case ISD::SDIVREM:
6826   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6827   case ISD::DYNAMIC_STACKALLOC:
6828     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6829       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6830     llvm_unreachable("Don't know how to custom lower this!");
6831   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6832   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6833   case ARMISD::WIN__DBZCHK: return SDValue();
6834   }
6835 }
6836
6837 /// ReplaceNodeResults - Replace the results of node with an illegal result
6838 /// type with new values built out of custom code.
6839 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6840                                            SmallVectorImpl<SDValue> &Results,
6841                                            SelectionDAG &DAG) const {
6842   SDValue Res;
6843   switch (N->getOpcode()) {
6844   default:
6845     llvm_unreachable("Don't know how to custom expand this!");
6846   case ISD::READ_REGISTER:
6847     ExpandREAD_REGISTER(N, Results, DAG);
6848     break;
6849   case ISD::BITCAST:
6850     Res = ExpandBITCAST(N, DAG);
6851     break;
6852   case ISD::SRL:
6853   case ISD::SRA:
6854     Res = Expand64BitShift(N, DAG, Subtarget);
6855     break;
6856   case ISD::SREM:
6857   case ISD::UREM:
6858     Res = LowerREM(N, DAG);
6859     break;
6860   case ISD::READCYCLECOUNTER:
6861     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6862     return;
6863   case ISD::UDIV:
6864   case ISD::SDIV:
6865     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
6866     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
6867                              Results);
6868   }
6869   if (Res.getNode())
6870     Results.push_back(Res);
6871 }
6872
6873 //===----------------------------------------------------------------------===//
6874 //                           ARM Scheduler Hooks
6875 //===----------------------------------------------------------------------===//
6876
6877 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6878 /// registers the function context.
6879 void ARMTargetLowering::
6880 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6881                        MachineBasicBlock *DispatchBB, int FI) const {
6882   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6883   DebugLoc dl = MI->getDebugLoc();
6884   MachineFunction *MF = MBB->getParent();
6885   MachineRegisterInfo *MRI = &MF->getRegInfo();
6886   MachineConstantPool *MCP = MF->getConstantPool();
6887   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6888   const Function *F = MF->getFunction();
6889
6890   bool isThumb = Subtarget->isThumb();
6891   bool isThumb2 = Subtarget->isThumb2();
6892
6893   unsigned PCLabelId = AFI->createPICLabelUId();
6894   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6895   ARMConstantPoolValue *CPV =
6896     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6897   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6898
6899   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6900                                            : &ARM::GPRRegClass;
6901
6902   // Grab constant pool and fixed stack memory operands.
6903   MachineMemOperand *CPMMO =
6904       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6905                                MachineMemOperand::MOLoad, 4, 4);
6906
6907   MachineMemOperand *FIMMOSt =
6908       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6909                                MachineMemOperand::MOStore, 4, 4);
6910
6911   // Load the address of the dispatch MBB into the jump buffer.
6912   if (isThumb2) {
6913     // Incoming value: jbuf
6914     //   ldr.n  r5, LCPI1_1
6915     //   orr    r5, r5, #1
6916     //   add    r5, pc
6917     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6918     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6919     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6920                    .addConstantPoolIndex(CPI)
6921                    .addMemOperand(CPMMO));
6922     // Set the low bit because of thumb mode.
6923     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6924     AddDefaultCC(
6925       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6926                      .addReg(NewVReg1, RegState::Kill)
6927                      .addImm(0x01)));
6928     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6929     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6930       .addReg(NewVReg2, RegState::Kill)
6931       .addImm(PCLabelId);
6932     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6933                    .addReg(NewVReg3, RegState::Kill)
6934                    .addFrameIndex(FI)
6935                    .addImm(36)  // &jbuf[1] :: pc
6936                    .addMemOperand(FIMMOSt));
6937   } else if (isThumb) {
6938     // Incoming value: jbuf
6939     //   ldr.n  r1, LCPI1_4
6940     //   add    r1, pc
6941     //   mov    r2, #1
6942     //   orrs   r1, r2
6943     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6944     //   str    r1, [r2]
6945     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6946     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6947                    .addConstantPoolIndex(CPI)
6948                    .addMemOperand(CPMMO));
6949     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6950     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6951       .addReg(NewVReg1, RegState::Kill)
6952       .addImm(PCLabelId);
6953     // Set the low bit because of thumb mode.
6954     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6955     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6956                    .addReg(ARM::CPSR, RegState::Define)
6957                    .addImm(1));
6958     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6959     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6960                    .addReg(ARM::CPSR, RegState::Define)
6961                    .addReg(NewVReg2, RegState::Kill)
6962                    .addReg(NewVReg3, RegState::Kill));
6963     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6964     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6965             .addFrameIndex(FI)
6966             .addImm(36); // &jbuf[1] :: pc
6967     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6968                    .addReg(NewVReg4, RegState::Kill)
6969                    .addReg(NewVReg5, RegState::Kill)
6970                    .addImm(0)
6971                    .addMemOperand(FIMMOSt));
6972   } else {
6973     // Incoming value: jbuf
6974     //   ldr  r1, LCPI1_1
6975     //   add  r1, pc, r1
6976     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6977     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6978     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6979                    .addConstantPoolIndex(CPI)
6980                    .addImm(0)
6981                    .addMemOperand(CPMMO));
6982     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6983     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6984                    .addReg(NewVReg1, RegState::Kill)
6985                    .addImm(PCLabelId));
6986     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6987                    .addReg(NewVReg2, RegState::Kill)
6988                    .addFrameIndex(FI)
6989                    .addImm(36)  // &jbuf[1] :: pc
6990                    .addMemOperand(FIMMOSt));
6991   }
6992 }
6993
6994 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6995                                               MachineBasicBlock *MBB) const {
6996   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6997   DebugLoc dl = MI->getDebugLoc();
6998   MachineFunction *MF = MBB->getParent();
6999   MachineRegisterInfo *MRI = &MF->getRegInfo();
7000   MachineFrameInfo *MFI = MF->getFrameInfo();
7001   int FI = MFI->getFunctionContextIndex();
7002
7003   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7004                                                         : &ARM::GPRnopcRegClass;
7005
7006   // Get a mapping of the call site numbers to all of the landing pads they're
7007   // associated with.
7008   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7009   unsigned MaxCSNum = 0;
7010   MachineModuleInfo &MMI = MF->getMMI();
7011   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7012        ++BB) {
7013     if (!BB->isEHPad()) continue;
7014
7015     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7016     // pad.
7017     for (MachineBasicBlock::iterator
7018            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7019       if (!II->isEHLabel()) continue;
7020
7021       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7022       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7023
7024       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7025       for (SmallVectorImpl<unsigned>::iterator
7026              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7027            CSI != CSE; ++CSI) {
7028         CallSiteNumToLPad[*CSI].push_back(BB);
7029         MaxCSNum = std::max(MaxCSNum, *CSI);
7030       }
7031       break;
7032     }
7033   }
7034
7035   // Get an ordered list of the machine basic blocks for the jump table.
7036   std::vector<MachineBasicBlock*> LPadList;
7037   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7038   LPadList.reserve(CallSiteNumToLPad.size());
7039   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7040     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7041     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7042            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7043       LPadList.push_back(*II);
7044       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7045     }
7046   }
7047
7048   assert(!LPadList.empty() &&
7049          "No landing pad destinations for the dispatch jump table!");
7050
7051   // Create the jump table and associated information.
7052   MachineJumpTableInfo *JTI =
7053     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7054   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7055   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7056
7057   // Create the MBBs for the dispatch code.
7058
7059   // Shove the dispatch's address into the return slot in the function context.
7060   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7061   DispatchBB->setIsEHPad();
7062
7063   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7064   unsigned trap_opcode;
7065   if (Subtarget->isThumb())
7066     trap_opcode = ARM::tTRAP;
7067   else
7068     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7069
7070   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7071   DispatchBB->addSuccessor(TrapBB);
7072
7073   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7074   DispatchBB->addSuccessor(DispContBB);
7075
7076   // Insert and MBBs.
7077   MF->insert(MF->end(), DispatchBB);
7078   MF->insert(MF->end(), DispContBB);
7079   MF->insert(MF->end(), TrapBB);
7080
7081   // Insert code into the entry block that creates and registers the function
7082   // context.
7083   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7084
7085   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7086       MachinePointerInfo::getFixedStack(*MF, FI),
7087       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7088
7089   MachineInstrBuilder MIB;
7090   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7091
7092   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7093   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7094
7095   // Add a register mask with no preserved registers.  This results in all
7096   // registers being marked as clobbered.
7097   MIB.addRegMask(RI.getNoPreservedMask());
7098
7099   unsigned NumLPads = LPadList.size();
7100   if (Subtarget->isThumb2()) {
7101     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7102     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7103                    .addFrameIndex(FI)
7104                    .addImm(4)
7105                    .addMemOperand(FIMMOLd));
7106
7107     if (NumLPads < 256) {
7108       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7109                      .addReg(NewVReg1)
7110                      .addImm(LPadList.size()));
7111     } else {
7112       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7113       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7114                      .addImm(NumLPads & 0xFFFF));
7115
7116       unsigned VReg2 = VReg1;
7117       if ((NumLPads & 0xFFFF0000) != 0) {
7118         VReg2 = MRI->createVirtualRegister(TRC);
7119         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7120                        .addReg(VReg1)
7121                        .addImm(NumLPads >> 16));
7122       }
7123
7124       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7125                      .addReg(NewVReg1)
7126                      .addReg(VReg2));
7127     }
7128
7129     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7130       .addMBB(TrapBB)
7131       .addImm(ARMCC::HI)
7132       .addReg(ARM::CPSR);
7133
7134     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7135     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7136                    .addJumpTableIndex(MJTI));
7137
7138     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7139     AddDefaultCC(
7140       AddDefaultPred(
7141         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7142         .addReg(NewVReg3, RegState::Kill)
7143         .addReg(NewVReg1)
7144         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7145
7146     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7147       .addReg(NewVReg4, RegState::Kill)
7148       .addReg(NewVReg1)
7149       .addJumpTableIndex(MJTI);
7150   } else if (Subtarget->isThumb()) {
7151     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7152     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7153                    .addFrameIndex(FI)
7154                    .addImm(1)
7155                    .addMemOperand(FIMMOLd));
7156
7157     if (NumLPads < 256) {
7158       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7159                      .addReg(NewVReg1)
7160                      .addImm(NumLPads));
7161     } else {
7162       MachineConstantPool *ConstantPool = MF->getConstantPool();
7163       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7164       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7165
7166       // MachineConstantPool wants an explicit alignment.
7167       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7168       if (Align == 0)
7169         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7170       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7171
7172       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7173       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7174                      .addReg(VReg1, RegState::Define)
7175                      .addConstantPoolIndex(Idx));
7176       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7177                      .addReg(NewVReg1)
7178                      .addReg(VReg1));
7179     }
7180
7181     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7182       .addMBB(TrapBB)
7183       .addImm(ARMCC::HI)
7184       .addReg(ARM::CPSR);
7185
7186     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7187     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7188                    .addReg(ARM::CPSR, RegState::Define)
7189                    .addReg(NewVReg1)
7190                    .addImm(2));
7191
7192     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7193     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7194                    .addJumpTableIndex(MJTI));
7195
7196     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7197     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7198                    .addReg(ARM::CPSR, RegState::Define)
7199                    .addReg(NewVReg2, RegState::Kill)
7200                    .addReg(NewVReg3));
7201
7202     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7203         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7204
7205     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7206     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7207                    .addReg(NewVReg4, RegState::Kill)
7208                    .addImm(0)
7209                    .addMemOperand(JTMMOLd));
7210
7211     unsigned NewVReg6 = NewVReg5;
7212     if (RelocM == Reloc::PIC_) {
7213       NewVReg6 = MRI->createVirtualRegister(TRC);
7214       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7215                      .addReg(ARM::CPSR, RegState::Define)
7216                      .addReg(NewVReg5, RegState::Kill)
7217                      .addReg(NewVReg3));
7218     }
7219
7220     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7221       .addReg(NewVReg6, RegState::Kill)
7222       .addJumpTableIndex(MJTI);
7223   } else {
7224     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7225     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7226                    .addFrameIndex(FI)
7227                    .addImm(4)
7228                    .addMemOperand(FIMMOLd));
7229
7230     if (NumLPads < 256) {
7231       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7232                      .addReg(NewVReg1)
7233                      .addImm(NumLPads));
7234     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7235       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7236       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7237                      .addImm(NumLPads & 0xFFFF));
7238
7239       unsigned VReg2 = VReg1;
7240       if ((NumLPads & 0xFFFF0000) != 0) {
7241         VReg2 = MRI->createVirtualRegister(TRC);
7242         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7243                        .addReg(VReg1)
7244                        .addImm(NumLPads >> 16));
7245       }
7246
7247       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7248                      .addReg(NewVReg1)
7249                      .addReg(VReg2));
7250     } else {
7251       MachineConstantPool *ConstantPool = MF->getConstantPool();
7252       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7253       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7254
7255       // MachineConstantPool wants an explicit alignment.
7256       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7257       if (Align == 0)
7258         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7259       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7260
7261       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7262       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7263                      .addReg(VReg1, RegState::Define)
7264                      .addConstantPoolIndex(Idx)
7265                      .addImm(0));
7266       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7267                      .addReg(NewVReg1)
7268                      .addReg(VReg1, RegState::Kill));
7269     }
7270
7271     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7272       .addMBB(TrapBB)
7273       .addImm(ARMCC::HI)
7274       .addReg(ARM::CPSR);
7275
7276     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7277     AddDefaultCC(
7278       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7279                      .addReg(NewVReg1)
7280                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7281     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7282     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7283                    .addJumpTableIndex(MJTI));
7284
7285     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7286         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7287     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7288     AddDefaultPred(
7289       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7290       .addReg(NewVReg3, RegState::Kill)
7291       .addReg(NewVReg4)
7292       .addImm(0)
7293       .addMemOperand(JTMMOLd));
7294
7295     if (RelocM == Reloc::PIC_) {
7296       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7297         .addReg(NewVReg5, RegState::Kill)
7298         .addReg(NewVReg4)
7299         .addJumpTableIndex(MJTI);
7300     } else {
7301       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7302         .addReg(NewVReg5, RegState::Kill)
7303         .addJumpTableIndex(MJTI);
7304     }
7305   }
7306
7307   // Add the jump table entries as successors to the MBB.
7308   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7309   for (std::vector<MachineBasicBlock*>::iterator
7310          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7311     MachineBasicBlock *CurMBB = *I;
7312     if (SeenMBBs.insert(CurMBB).second)
7313       DispContBB->addSuccessor(CurMBB);
7314   }
7315
7316   // N.B. the order the invoke BBs are processed in doesn't matter here.
7317   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7318   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7319   for (MachineBasicBlock *BB : InvokeBBs) {
7320
7321     // Remove the landing pad successor from the invoke block and replace it
7322     // with the new dispatch block.
7323     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7324                                                   BB->succ_end());
7325     while (!Successors.empty()) {
7326       MachineBasicBlock *SMBB = Successors.pop_back_val();
7327       if (SMBB->isEHPad()) {
7328         BB->removeSuccessor(SMBB);
7329         MBBLPads.push_back(SMBB);
7330       }
7331     }
7332
7333     BB->addSuccessor(DispatchBB);
7334
7335     // Find the invoke call and mark all of the callee-saved registers as
7336     // 'implicit defined' so that they're spilled. This prevents code from
7337     // moving instructions to before the EH block, where they will never be
7338     // executed.
7339     for (MachineBasicBlock::reverse_iterator
7340            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7341       if (!II->isCall()) continue;
7342
7343       DenseMap<unsigned, bool> DefRegs;
7344       for (MachineInstr::mop_iterator
7345              OI = II->operands_begin(), OE = II->operands_end();
7346            OI != OE; ++OI) {
7347         if (!OI->isReg()) continue;
7348         DefRegs[OI->getReg()] = true;
7349       }
7350
7351       MachineInstrBuilder MIB(*MF, &*II);
7352
7353       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7354         unsigned Reg = SavedRegs[i];
7355         if (Subtarget->isThumb2() &&
7356             !ARM::tGPRRegClass.contains(Reg) &&
7357             !ARM::hGPRRegClass.contains(Reg))
7358           continue;
7359         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7360           continue;
7361         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7362           continue;
7363         if (!DefRegs[Reg])
7364           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7365       }
7366
7367       break;
7368     }
7369   }
7370
7371   // Mark all former landing pads as non-landing pads. The dispatch is the only
7372   // landing pad now.
7373   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7374          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7375     (*I)->setIsEHPad(false);
7376
7377   // The instruction is gone now.
7378   MI->eraseFromParent();
7379 }
7380
7381 static
7382 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7383   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7384        E = MBB->succ_end(); I != E; ++I)
7385     if (*I != Succ)
7386       return *I;
7387   llvm_unreachable("Expecting a BB with two successors!");
7388 }
7389
7390 /// Return the load opcode for a given load size. If load size >= 8,
7391 /// neon opcode will be returned.
7392 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7393   if (LdSize >= 8)
7394     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7395                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7396   if (IsThumb1)
7397     return LdSize == 4 ? ARM::tLDRi
7398                        : LdSize == 2 ? ARM::tLDRHi
7399                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7400   if (IsThumb2)
7401     return LdSize == 4 ? ARM::t2LDR_POST
7402                        : LdSize == 2 ? ARM::t2LDRH_POST
7403                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7404   return LdSize == 4 ? ARM::LDR_POST_IMM
7405                      : LdSize == 2 ? ARM::LDRH_POST
7406                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7407 }
7408
7409 /// Return the store opcode for a given store size. If store size >= 8,
7410 /// neon opcode will be returned.
7411 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7412   if (StSize >= 8)
7413     return StSize == 16 ? ARM::VST1q32wb_fixed
7414                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7415   if (IsThumb1)
7416     return StSize == 4 ? ARM::tSTRi
7417                        : StSize == 2 ? ARM::tSTRHi
7418                                      : StSize == 1 ? ARM::tSTRBi : 0;
7419   if (IsThumb2)
7420     return StSize == 4 ? ARM::t2STR_POST
7421                        : StSize == 2 ? ARM::t2STRH_POST
7422                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7423   return StSize == 4 ? ARM::STR_POST_IMM
7424                      : StSize == 2 ? ARM::STRH_POST
7425                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7426 }
7427
7428 /// Emit a post-increment load operation with given size. The instructions
7429 /// will be added to BB at Pos.
7430 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7431                        const TargetInstrInfo *TII, DebugLoc dl,
7432                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7433                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7434   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7435   assert(LdOpc != 0 && "Should have a load opcode");
7436   if (LdSize >= 8) {
7437     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7438                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7439                        .addImm(0));
7440   } else if (IsThumb1) {
7441     // load + update AddrIn
7442     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7443                        .addReg(AddrIn).addImm(0));
7444     MachineInstrBuilder MIB =
7445         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7446     MIB = AddDefaultT1CC(MIB);
7447     MIB.addReg(AddrIn).addImm(LdSize);
7448     AddDefaultPred(MIB);
7449   } else if (IsThumb2) {
7450     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7451                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7452                        .addImm(LdSize));
7453   } else { // arm
7454     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7455                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7456                        .addReg(0).addImm(LdSize));
7457   }
7458 }
7459
7460 /// Emit a post-increment store operation with given size. The instructions
7461 /// will be added to BB at Pos.
7462 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7463                        const TargetInstrInfo *TII, DebugLoc dl,
7464                        unsigned StSize, unsigned Data, unsigned AddrIn,
7465                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7466   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7467   assert(StOpc != 0 && "Should have a store opcode");
7468   if (StSize >= 8) {
7469     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7470                        .addReg(AddrIn).addImm(0).addReg(Data));
7471   } else if (IsThumb1) {
7472     // store + update AddrIn
7473     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7474                        .addReg(AddrIn).addImm(0));
7475     MachineInstrBuilder MIB =
7476         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7477     MIB = AddDefaultT1CC(MIB);
7478     MIB.addReg(AddrIn).addImm(StSize);
7479     AddDefaultPred(MIB);
7480   } else if (IsThumb2) {
7481     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7482                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7483   } else { // arm
7484     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7485                        .addReg(Data).addReg(AddrIn).addReg(0)
7486                        .addImm(StSize));
7487   }
7488 }
7489
7490 MachineBasicBlock *
7491 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7492                                    MachineBasicBlock *BB) const {
7493   // This pseudo instruction has 3 operands: dst, src, size
7494   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7495   // Otherwise, we will generate unrolled scalar copies.
7496   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7497   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7498   MachineFunction::iterator It = BB;
7499   ++It;
7500
7501   unsigned dest = MI->getOperand(0).getReg();
7502   unsigned src = MI->getOperand(1).getReg();
7503   unsigned SizeVal = MI->getOperand(2).getImm();
7504   unsigned Align = MI->getOperand(3).getImm();
7505   DebugLoc dl = MI->getDebugLoc();
7506
7507   MachineFunction *MF = BB->getParent();
7508   MachineRegisterInfo &MRI = MF->getRegInfo();
7509   unsigned UnitSize = 0;
7510   const TargetRegisterClass *TRC = nullptr;
7511   const TargetRegisterClass *VecTRC = nullptr;
7512
7513   bool IsThumb1 = Subtarget->isThumb1Only();
7514   bool IsThumb2 = Subtarget->isThumb2();
7515
7516   if (Align & 1) {
7517     UnitSize = 1;
7518   } else if (Align & 2) {
7519     UnitSize = 2;
7520   } else {
7521     // Check whether we can use NEON instructions.
7522     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7523         Subtarget->hasNEON()) {
7524       if ((Align % 16 == 0) && SizeVal >= 16)
7525         UnitSize = 16;
7526       else if ((Align % 8 == 0) && SizeVal >= 8)
7527         UnitSize = 8;
7528     }
7529     // Can't use NEON instructions.
7530     if (UnitSize == 0)
7531       UnitSize = 4;
7532   }
7533
7534   // Select the correct opcode and register class for unit size load/store
7535   bool IsNeon = UnitSize >= 8;
7536   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7537   if (IsNeon)
7538     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7539                             : UnitSize == 8 ? &ARM::DPRRegClass
7540                                             : nullptr;
7541
7542   unsigned BytesLeft = SizeVal % UnitSize;
7543   unsigned LoopSize = SizeVal - BytesLeft;
7544
7545   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7546     // Use LDR and STR to copy.
7547     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7548     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7549     unsigned srcIn = src;
7550     unsigned destIn = dest;
7551     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7552       unsigned srcOut = MRI.createVirtualRegister(TRC);
7553       unsigned destOut = MRI.createVirtualRegister(TRC);
7554       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7555       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7556                  IsThumb1, IsThumb2);
7557       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7558                  IsThumb1, IsThumb2);
7559       srcIn = srcOut;
7560       destIn = destOut;
7561     }
7562
7563     // Handle the leftover bytes with LDRB and STRB.
7564     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7565     // [destOut] = STRB_POST(scratch, destIn, 1)
7566     for (unsigned i = 0; i < BytesLeft; i++) {
7567       unsigned srcOut = MRI.createVirtualRegister(TRC);
7568       unsigned destOut = MRI.createVirtualRegister(TRC);
7569       unsigned scratch = MRI.createVirtualRegister(TRC);
7570       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7571                  IsThumb1, IsThumb2);
7572       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7573                  IsThumb1, IsThumb2);
7574       srcIn = srcOut;
7575       destIn = destOut;
7576     }
7577     MI->eraseFromParent();   // The instruction is gone now.
7578     return BB;
7579   }
7580
7581   // Expand the pseudo op to a loop.
7582   // thisMBB:
7583   //   ...
7584   //   movw varEnd, # --> with thumb2
7585   //   movt varEnd, #
7586   //   ldrcp varEnd, idx --> without thumb2
7587   //   fallthrough --> loopMBB
7588   // loopMBB:
7589   //   PHI varPhi, varEnd, varLoop
7590   //   PHI srcPhi, src, srcLoop
7591   //   PHI destPhi, dst, destLoop
7592   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7593   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7594   //   subs varLoop, varPhi, #UnitSize
7595   //   bne loopMBB
7596   //   fallthrough --> exitMBB
7597   // exitMBB:
7598   //   epilogue to handle left-over bytes
7599   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7600   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7601   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7602   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7603   MF->insert(It, loopMBB);
7604   MF->insert(It, exitMBB);
7605
7606   // Transfer the remainder of BB and its successor edges to exitMBB.
7607   exitMBB->splice(exitMBB->begin(), BB,
7608                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7609   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7610
7611   // Load an immediate to varEnd.
7612   unsigned varEnd = MRI.createVirtualRegister(TRC);
7613   if (Subtarget->useMovt(*MF)) {
7614     unsigned Vtmp = varEnd;
7615     if ((LoopSize & 0xFFFF0000) != 0)
7616       Vtmp = MRI.createVirtualRegister(TRC);
7617     AddDefaultPred(BuildMI(BB, dl,
7618                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7619                            Vtmp).addImm(LoopSize & 0xFFFF));
7620
7621     if ((LoopSize & 0xFFFF0000) != 0)
7622       AddDefaultPred(BuildMI(BB, dl,
7623                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7624                              varEnd)
7625                          .addReg(Vtmp)
7626                          .addImm(LoopSize >> 16));
7627   } else {
7628     MachineConstantPool *ConstantPool = MF->getConstantPool();
7629     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7630     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7631
7632     // MachineConstantPool wants an explicit alignment.
7633     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7634     if (Align == 0)
7635       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7636     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7637
7638     if (IsThumb1)
7639       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7640           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7641     else
7642       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7643           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7644   }
7645   BB->addSuccessor(loopMBB);
7646
7647   // Generate the loop body:
7648   //   varPhi = PHI(varLoop, varEnd)
7649   //   srcPhi = PHI(srcLoop, src)
7650   //   destPhi = PHI(destLoop, dst)
7651   MachineBasicBlock *entryBB = BB;
7652   BB = loopMBB;
7653   unsigned varLoop = MRI.createVirtualRegister(TRC);
7654   unsigned varPhi = MRI.createVirtualRegister(TRC);
7655   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7656   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7657   unsigned destLoop = MRI.createVirtualRegister(TRC);
7658   unsigned destPhi = MRI.createVirtualRegister(TRC);
7659
7660   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7661     .addReg(varLoop).addMBB(loopMBB)
7662     .addReg(varEnd).addMBB(entryBB);
7663   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7664     .addReg(srcLoop).addMBB(loopMBB)
7665     .addReg(src).addMBB(entryBB);
7666   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7667     .addReg(destLoop).addMBB(loopMBB)
7668     .addReg(dest).addMBB(entryBB);
7669
7670   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7671   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7672   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7673   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7674              IsThumb1, IsThumb2);
7675   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7676              IsThumb1, IsThumb2);
7677
7678   // Decrement loop variable by UnitSize.
7679   if (IsThumb1) {
7680     MachineInstrBuilder MIB =
7681         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7682     MIB = AddDefaultT1CC(MIB);
7683     MIB.addReg(varPhi).addImm(UnitSize);
7684     AddDefaultPred(MIB);
7685   } else {
7686     MachineInstrBuilder MIB =
7687         BuildMI(*BB, BB->end(), dl,
7688                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7689     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7690     MIB->getOperand(5).setReg(ARM::CPSR);
7691     MIB->getOperand(5).setIsDef(true);
7692   }
7693   BuildMI(*BB, BB->end(), dl,
7694           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7695       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7696
7697   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7698   BB->addSuccessor(loopMBB);
7699   BB->addSuccessor(exitMBB);
7700
7701   // Add epilogue to handle BytesLeft.
7702   BB = exitMBB;
7703   MachineInstr *StartOfExit = exitMBB->begin();
7704
7705   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7706   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7707   unsigned srcIn = srcLoop;
7708   unsigned destIn = destLoop;
7709   for (unsigned i = 0; i < BytesLeft; i++) {
7710     unsigned srcOut = MRI.createVirtualRegister(TRC);
7711     unsigned destOut = MRI.createVirtualRegister(TRC);
7712     unsigned scratch = MRI.createVirtualRegister(TRC);
7713     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7714                IsThumb1, IsThumb2);
7715     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7716                IsThumb1, IsThumb2);
7717     srcIn = srcOut;
7718     destIn = destOut;
7719   }
7720
7721   MI->eraseFromParent();   // The instruction is gone now.
7722   return BB;
7723 }
7724
7725 MachineBasicBlock *
7726 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7727                                        MachineBasicBlock *MBB) const {
7728   const TargetMachine &TM = getTargetMachine();
7729   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7730   DebugLoc DL = MI->getDebugLoc();
7731
7732   assert(Subtarget->isTargetWindows() &&
7733          "__chkstk is only supported on Windows");
7734   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7735
7736   // __chkstk takes the number of words to allocate on the stack in R4, and
7737   // returns the stack adjustment in number of bytes in R4.  This will not
7738   // clober any other registers (other than the obvious lr).
7739   //
7740   // Although, technically, IP should be considered a register which may be
7741   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7742   // thumb-2 environment, so there is no interworking required.  As a result, we
7743   // do not expect a veneer to be emitted by the linker, clobbering IP.
7744   //
7745   // Each module receives its own copy of __chkstk, so no import thunk is
7746   // required, again, ensuring that IP is not clobbered.
7747   //
7748   // Finally, although some linkers may theoretically provide a trampoline for
7749   // out of range calls (which is quite common due to a 32M range limitation of
7750   // branches for Thumb), we can generate the long-call version via
7751   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7752   // IP.
7753
7754   switch (TM.getCodeModel()) {
7755   case CodeModel::Small:
7756   case CodeModel::Medium:
7757   case CodeModel::Default:
7758   case CodeModel::Kernel:
7759     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7760       .addImm((unsigned)ARMCC::AL).addReg(0)
7761       .addExternalSymbol("__chkstk")
7762       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7763       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7764       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7765     break;
7766   case CodeModel::Large:
7767   case CodeModel::JITDefault: {
7768     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7769     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7770
7771     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7772       .addExternalSymbol("__chkstk");
7773     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7774       .addImm((unsigned)ARMCC::AL).addReg(0)
7775       .addReg(Reg, RegState::Kill)
7776       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7777       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7778       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7779     break;
7780   }
7781   }
7782
7783   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7784                                       ARM::SP)
7785                               .addReg(ARM::SP).addReg(ARM::R4)));
7786
7787   MI->eraseFromParent();
7788   return MBB;
7789 }
7790
7791 MachineBasicBlock *
7792 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
7793                                        MachineBasicBlock *MBB) const {
7794   DebugLoc DL = MI->getDebugLoc();
7795   MachineFunction *MF = MBB->getParent();
7796   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7797
7798   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
7799   MF->push_back(ContBB);
7800   ContBB->splice(ContBB->begin(), MBB,
7801                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7802   MBB->addSuccessor(ContBB);
7803
7804   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7805   MF->push_back(TrapBB);
7806   BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
7807   MBB->addSuccessor(TrapBB);
7808
7809   BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
7810       .addReg(MI->getOperand(0).getReg())
7811       .addMBB(TrapBB);
7812
7813   MI->eraseFromParent();
7814   return ContBB;
7815 }
7816
7817 MachineBasicBlock *
7818 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7819                                                MachineBasicBlock *BB) const {
7820   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7821   DebugLoc dl = MI->getDebugLoc();
7822   bool isThumb2 = Subtarget->isThumb2();
7823   switch (MI->getOpcode()) {
7824   default: {
7825     MI->dump();
7826     llvm_unreachable("Unexpected instr type to insert");
7827   }
7828   // The Thumb2 pre-indexed stores have the same MI operands, they just
7829   // define them differently in the .td files from the isel patterns, so
7830   // they need pseudos.
7831   case ARM::t2STR_preidx:
7832     MI->setDesc(TII->get(ARM::t2STR_PRE));
7833     return BB;
7834   case ARM::t2STRB_preidx:
7835     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7836     return BB;
7837   case ARM::t2STRH_preidx:
7838     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7839     return BB;
7840
7841   case ARM::STRi_preidx:
7842   case ARM::STRBi_preidx: {
7843     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7844       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7845     // Decode the offset.
7846     unsigned Offset = MI->getOperand(4).getImm();
7847     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7848     Offset = ARM_AM::getAM2Offset(Offset);
7849     if (isSub)
7850       Offset = -Offset;
7851
7852     MachineMemOperand *MMO = *MI->memoperands_begin();
7853     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7854       .addOperand(MI->getOperand(0))  // Rn_wb
7855       .addOperand(MI->getOperand(1))  // Rt
7856       .addOperand(MI->getOperand(2))  // Rn
7857       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7858       .addOperand(MI->getOperand(5))  // pred
7859       .addOperand(MI->getOperand(6))
7860       .addMemOperand(MMO);
7861     MI->eraseFromParent();
7862     return BB;
7863   }
7864   case ARM::STRr_preidx:
7865   case ARM::STRBr_preidx:
7866   case ARM::STRH_preidx: {
7867     unsigned NewOpc;
7868     switch (MI->getOpcode()) {
7869     default: llvm_unreachable("unexpected opcode!");
7870     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7871     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7872     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7873     }
7874     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7875     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7876       MIB.addOperand(MI->getOperand(i));
7877     MI->eraseFromParent();
7878     return BB;
7879   }
7880
7881   case ARM::tMOVCCr_pseudo: {
7882     // To "insert" a SELECT_CC instruction, we actually have to insert the
7883     // diamond control-flow pattern.  The incoming instruction knows the
7884     // destination vreg to set, the condition code register to branch on, the
7885     // true/false values to select between, and a branch opcode to use.
7886     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7887     MachineFunction::iterator It = BB;
7888     ++It;
7889
7890     //  thisMBB:
7891     //  ...
7892     //   TrueVal = ...
7893     //   cmpTY ccX, r1, r2
7894     //   bCC copy1MBB
7895     //   fallthrough --> copy0MBB
7896     MachineBasicBlock *thisMBB  = BB;
7897     MachineFunction *F = BB->getParent();
7898     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7899     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7900     F->insert(It, copy0MBB);
7901     F->insert(It, sinkMBB);
7902
7903     // Transfer the remainder of BB and its successor edges to sinkMBB.
7904     sinkMBB->splice(sinkMBB->begin(), BB,
7905                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7906     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7907
7908     BB->addSuccessor(copy0MBB);
7909     BB->addSuccessor(sinkMBB);
7910
7911     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7912       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7913
7914     //  copy0MBB:
7915     //   %FalseValue = ...
7916     //   # fallthrough to sinkMBB
7917     BB = copy0MBB;
7918
7919     // Update machine-CFG edges
7920     BB->addSuccessor(sinkMBB);
7921
7922     //  sinkMBB:
7923     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7924     //  ...
7925     BB = sinkMBB;
7926     BuildMI(*BB, BB->begin(), dl,
7927             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7928       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7929       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7930
7931     MI->eraseFromParent();   // The pseudo instruction is gone now.
7932     return BB;
7933   }
7934
7935   case ARM::BCCi64:
7936   case ARM::BCCZi64: {
7937     // If there is an unconditional branch to the other successor, remove it.
7938     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7939
7940     // Compare both parts that make up the double comparison separately for
7941     // equality.
7942     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7943
7944     unsigned LHS1 = MI->getOperand(1).getReg();
7945     unsigned LHS2 = MI->getOperand(2).getReg();
7946     if (RHSisZero) {
7947       AddDefaultPred(BuildMI(BB, dl,
7948                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7949                      .addReg(LHS1).addImm(0));
7950       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7951         .addReg(LHS2).addImm(0)
7952         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7953     } else {
7954       unsigned RHS1 = MI->getOperand(3).getReg();
7955       unsigned RHS2 = MI->getOperand(4).getReg();
7956       AddDefaultPred(BuildMI(BB, dl,
7957                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7958                      .addReg(LHS1).addReg(RHS1));
7959       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7960         .addReg(LHS2).addReg(RHS2)
7961         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7962     }
7963
7964     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7965     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7966     if (MI->getOperand(0).getImm() == ARMCC::NE)
7967       std::swap(destMBB, exitMBB);
7968
7969     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7970       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7971     if (isThumb2)
7972       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7973     else
7974       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7975
7976     MI->eraseFromParent();   // The pseudo instruction is gone now.
7977     return BB;
7978   }
7979
7980   case ARM::Int_eh_sjlj_setjmp:
7981   case ARM::Int_eh_sjlj_setjmp_nofp:
7982   case ARM::tInt_eh_sjlj_setjmp:
7983   case ARM::t2Int_eh_sjlj_setjmp:
7984   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7985     return BB;
7986
7987   case ARM::Int_eh_sjlj_setup_dispatch:
7988     EmitSjLjDispatchBlock(MI, BB);
7989     return BB;
7990
7991   case ARM::ABS:
7992   case ARM::t2ABS: {
7993     // To insert an ABS instruction, we have to insert the
7994     // diamond control-flow pattern.  The incoming instruction knows the
7995     // source vreg to test against 0, the destination vreg to set,
7996     // the condition code register to branch on, the
7997     // true/false values to select between, and a branch opcode to use.
7998     // It transforms
7999     //     V1 = ABS V0
8000     // into
8001     //     V2 = MOVS V0
8002     //     BCC                      (branch to SinkBB if V0 >= 0)
8003     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
8004     //     SinkBB: V1 = PHI(V2, V3)
8005     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8006     MachineFunction::iterator BBI = BB;
8007     ++BBI;
8008     MachineFunction *Fn = BB->getParent();
8009     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8010     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
8011     Fn->insert(BBI, RSBBB);
8012     Fn->insert(BBI, SinkBB);
8013
8014     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8015     unsigned int ABSDstReg = MI->getOperand(0).getReg();
8016     bool ABSSrcKIll = MI->getOperand(1).isKill();
8017     bool isThumb2 = Subtarget->isThumb2();
8018     MachineRegisterInfo &MRI = Fn->getRegInfo();
8019     // In Thumb mode S must not be specified if source register is the SP or
8020     // PC and if destination register is the SP, so restrict register class
8021     unsigned NewRsbDstReg =
8022       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8023
8024     // Transfer the remainder of BB and its successor edges to sinkMBB.
8025     SinkBB->splice(SinkBB->begin(), BB,
8026                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
8027     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8028
8029     BB->addSuccessor(RSBBB);
8030     BB->addSuccessor(SinkBB);
8031
8032     // fall through to SinkMBB
8033     RSBBB->addSuccessor(SinkBB);
8034
8035     // insert a cmp at the end of BB
8036     AddDefaultPred(BuildMI(BB, dl,
8037                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8038                    .addReg(ABSSrcReg).addImm(0));
8039
8040     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8041     BuildMI(BB, dl,
8042       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8043       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8044
8045     // insert rsbri in RSBBB
8046     // Note: BCC and rsbri will be converted into predicated rsbmi
8047     // by if-conversion pass
8048     BuildMI(*RSBBB, RSBBB->begin(), dl,
8049       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8050       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8051       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8052
8053     // insert PHI in SinkBB,
8054     // reuse ABSDstReg to not change uses of ABS instruction
8055     BuildMI(*SinkBB, SinkBB->begin(), dl,
8056       TII->get(ARM::PHI), ABSDstReg)
8057       .addReg(NewRsbDstReg).addMBB(RSBBB)
8058       .addReg(ABSSrcReg).addMBB(BB);
8059
8060     // remove ABS instruction
8061     MI->eraseFromParent();
8062
8063     // return last added BB
8064     return SinkBB;
8065   }
8066   case ARM::COPY_STRUCT_BYVAL_I32:
8067     ++NumLoopByVals;
8068     return EmitStructByval(MI, BB);
8069   case ARM::WIN__CHKSTK:
8070     return EmitLowered__chkstk(MI, BB);
8071   case ARM::WIN__DBZCHK:
8072     return EmitLowered__dbzchk(MI, BB);
8073   }
8074 }
8075
8076 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8077 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8078 /// instead of as a custom inserter because we need the use list from the SDNode.
8079 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8080                                    MachineInstr *MI, const SDNode *Node) {
8081   bool isThumb1 = Subtarget->isThumb1Only();
8082
8083   DebugLoc DL = MI->getDebugLoc();
8084   MachineFunction *MF = MI->getParent()->getParent();
8085   MachineRegisterInfo &MRI = MF->getRegInfo();
8086   MachineInstrBuilder MIB(*MF, MI);
8087
8088   // If the new dst/src is unused mark it as dead.
8089   if (!Node->hasAnyUseOfValue(0)) {
8090     MI->getOperand(0).setIsDead(true);
8091   }
8092   if (!Node->hasAnyUseOfValue(1)) {
8093     MI->getOperand(1).setIsDead(true);
8094   }
8095
8096   // The MEMCPY both defines and kills the scratch registers.
8097   for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) {
8098     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8099                                                          : &ARM::GPRRegClass);
8100     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8101   }
8102 }
8103
8104 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8105                                                       SDNode *Node) const {
8106   if (MI->getOpcode() == ARM::MEMCPY) {
8107     attachMEMCPYScratchRegs(Subtarget, MI, Node);
8108     return;
8109   }
8110
8111   const MCInstrDesc *MCID = &MI->getDesc();
8112   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8113   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8114   // operand is still set to noreg. If needed, set the optional operand's
8115   // register to CPSR, and remove the redundant implicit def.
8116   //
8117   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8118
8119   // Rename pseudo opcodes.
8120   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8121   if (NewOpc) {
8122     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8123     MCID = &TII->get(NewOpc);
8124
8125     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8126            "converted opcode should be the same except for cc_out");
8127
8128     MI->setDesc(*MCID);
8129
8130     // Add the optional cc_out operand
8131     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8132   }
8133   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8134
8135   // Any ARM instruction that sets the 's' bit should specify an optional
8136   // "cc_out" operand in the last operand position.
8137   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8138     assert(!NewOpc && "Optional cc_out operand required");
8139     return;
8140   }
8141   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8142   // since we already have an optional CPSR def.
8143   bool definesCPSR = false;
8144   bool deadCPSR = false;
8145   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8146        i != e; ++i) {
8147     const MachineOperand &MO = MI->getOperand(i);
8148     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8149       definesCPSR = true;
8150       if (MO.isDead())
8151         deadCPSR = true;
8152       MI->RemoveOperand(i);
8153       break;
8154     }
8155   }
8156   if (!definesCPSR) {
8157     assert(!NewOpc && "Optional cc_out operand required");
8158     return;
8159   }
8160   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8161   if (deadCPSR) {
8162     assert(!MI->getOperand(ccOutIdx).getReg() &&
8163            "expect uninitialized optional cc_out operand");
8164     return;
8165   }
8166
8167   // If this instruction was defined with an optional CPSR def and its dag node
8168   // had a live implicit CPSR def, then activate the optional CPSR def.
8169   MachineOperand &MO = MI->getOperand(ccOutIdx);
8170   MO.setReg(ARM::CPSR);
8171   MO.setIsDef(true);
8172 }
8173
8174 //===----------------------------------------------------------------------===//
8175 //                           ARM Optimization Hooks
8176 //===----------------------------------------------------------------------===//
8177
8178 // Helper function that checks if N is a null or all ones constant.
8179 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8180   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8181   if (!C)
8182     return false;
8183   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8184 }
8185
8186 // Return true if N is conditionally 0 or all ones.
8187 // Detects these expressions where cc is an i1 value:
8188 //
8189 //   (select cc 0, y)   [AllOnes=0]
8190 //   (select cc y, 0)   [AllOnes=0]
8191 //   (zext cc)          [AllOnes=0]
8192 //   (sext cc)          [AllOnes=0/1]
8193 //   (select cc -1, y)  [AllOnes=1]
8194 //   (select cc y, -1)  [AllOnes=1]
8195 //
8196 // Invert is set when N is the null/all ones constant when CC is false.
8197 // OtherOp is set to the alternative value of N.
8198 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8199                                        SDValue &CC, bool &Invert,
8200                                        SDValue &OtherOp,
8201                                        SelectionDAG &DAG) {
8202   switch (N->getOpcode()) {
8203   default: return false;
8204   case ISD::SELECT: {
8205     CC = N->getOperand(0);
8206     SDValue N1 = N->getOperand(1);
8207     SDValue N2 = N->getOperand(2);
8208     if (isZeroOrAllOnes(N1, AllOnes)) {
8209       Invert = false;
8210       OtherOp = N2;
8211       return true;
8212     }
8213     if (isZeroOrAllOnes(N2, AllOnes)) {
8214       Invert = true;
8215       OtherOp = N1;
8216       return true;
8217     }
8218     return false;
8219   }
8220   case ISD::ZERO_EXTEND:
8221     // (zext cc) can never be the all ones value.
8222     if (AllOnes)
8223       return false;
8224     // Fall through.
8225   case ISD::SIGN_EXTEND: {
8226     SDLoc dl(N);
8227     EVT VT = N->getValueType(0);
8228     CC = N->getOperand(0);
8229     if (CC.getValueType() != MVT::i1)
8230       return false;
8231     Invert = !AllOnes;
8232     if (AllOnes)
8233       // When looking for an AllOnes constant, N is an sext, and the 'other'
8234       // value is 0.
8235       OtherOp = DAG.getConstant(0, dl, VT);
8236     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8237       // When looking for a 0 constant, N can be zext or sext.
8238       OtherOp = DAG.getConstant(1, dl, VT);
8239     else
8240       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8241                                 VT);
8242     return true;
8243   }
8244   }
8245 }
8246
8247 // Combine a constant select operand into its use:
8248 //
8249 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8250 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8251 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8252 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8253 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8254 //
8255 // The transform is rejected if the select doesn't have a constant operand that
8256 // is null, or all ones when AllOnes is set.
8257 //
8258 // Also recognize sext/zext from i1:
8259 //
8260 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8261 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8262 //
8263 // These transformations eventually create predicated instructions.
8264 //
8265 // @param N       The node to transform.
8266 // @param Slct    The N operand that is a select.
8267 // @param OtherOp The other N operand (x above).
8268 // @param DCI     Context.
8269 // @param AllOnes Require the select constant to be all ones instead of null.
8270 // @returns The new node, or SDValue() on failure.
8271 static
8272 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8273                             TargetLowering::DAGCombinerInfo &DCI,
8274                             bool AllOnes = false) {
8275   SelectionDAG &DAG = DCI.DAG;
8276   EVT VT = N->getValueType(0);
8277   SDValue NonConstantVal;
8278   SDValue CCOp;
8279   bool SwapSelectOps;
8280   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8281                                   NonConstantVal, DAG))
8282     return SDValue();
8283
8284   // Slct is now know to be the desired identity constant when CC is true.
8285   SDValue TrueVal = OtherOp;
8286   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8287                                  OtherOp, NonConstantVal);
8288   // Unless SwapSelectOps says CC should be false.
8289   if (SwapSelectOps)
8290     std::swap(TrueVal, FalseVal);
8291
8292   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8293                      CCOp, TrueVal, FalseVal);
8294 }
8295
8296 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8297 static
8298 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8299                                        TargetLowering::DAGCombinerInfo &DCI) {
8300   SDValue N0 = N->getOperand(0);
8301   SDValue N1 = N->getOperand(1);
8302   if (N0.getNode()->hasOneUse()) {
8303     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8304     if (Result.getNode())
8305       return Result;
8306   }
8307   if (N1.getNode()->hasOneUse()) {
8308     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8309     if (Result.getNode())
8310       return Result;
8311   }
8312   return SDValue();
8313 }
8314
8315 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8316 // (only after legalization).
8317 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8318                                  TargetLowering::DAGCombinerInfo &DCI,
8319                                  const ARMSubtarget *Subtarget) {
8320
8321   // Only perform optimization if after legalize, and if NEON is available. We
8322   // also expected both operands to be BUILD_VECTORs.
8323   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8324       || N0.getOpcode() != ISD::BUILD_VECTOR
8325       || N1.getOpcode() != ISD::BUILD_VECTOR)
8326     return SDValue();
8327
8328   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8329   EVT VT = N->getValueType(0);
8330   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8331     return SDValue();
8332
8333   // Check that the vector operands are of the right form.
8334   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8335   // operands, where N is the size of the formed vector.
8336   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8337   // index such that we have a pair wise add pattern.
8338
8339   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8340   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8341     return SDValue();
8342   SDValue Vec = N0->getOperand(0)->getOperand(0);
8343   SDNode *V = Vec.getNode();
8344   unsigned nextIndex = 0;
8345
8346   // For each operands to the ADD which are BUILD_VECTORs,
8347   // check to see if each of their operands are an EXTRACT_VECTOR with
8348   // the same vector and appropriate index.
8349   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8350     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8351         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8352
8353       SDValue ExtVec0 = N0->getOperand(i);
8354       SDValue ExtVec1 = N1->getOperand(i);
8355
8356       // First operand is the vector, verify its the same.
8357       if (V != ExtVec0->getOperand(0).getNode() ||
8358           V != ExtVec1->getOperand(0).getNode())
8359         return SDValue();
8360
8361       // Second is the constant, verify its correct.
8362       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8363       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8364
8365       // For the constant, we want to see all the even or all the odd.
8366       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8367           || C1->getZExtValue() != nextIndex+1)
8368         return SDValue();
8369
8370       // Increment index.
8371       nextIndex+=2;
8372     } else
8373       return SDValue();
8374   }
8375
8376   // Create VPADDL node.
8377   SelectionDAG &DAG = DCI.DAG;
8378   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8379
8380   SDLoc dl(N);
8381
8382   // Build operand list.
8383   SmallVector<SDValue, 8> Ops;
8384   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8385                                 TLI.getPointerTy(DAG.getDataLayout())));
8386
8387   // Input is the vector.
8388   Ops.push_back(Vec);
8389
8390   // Get widened type and narrowed type.
8391   MVT widenType;
8392   unsigned numElem = VT.getVectorNumElements();
8393   
8394   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8395   switch (inputLaneType.getSimpleVT().SimpleTy) {
8396     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8397     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8398     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8399     default:
8400       llvm_unreachable("Invalid vector element type for padd optimization.");
8401   }
8402
8403   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8404   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8405   return DAG.getNode(ExtOp, dl, VT, tmp);
8406 }
8407
8408 static SDValue findMUL_LOHI(SDValue V) {
8409   if (V->getOpcode() == ISD::UMUL_LOHI ||
8410       V->getOpcode() == ISD::SMUL_LOHI)
8411     return V;
8412   return SDValue();
8413 }
8414
8415 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8416                                      TargetLowering::DAGCombinerInfo &DCI,
8417                                      const ARMSubtarget *Subtarget) {
8418
8419   if (Subtarget->isThumb1Only()) return SDValue();
8420
8421   // Only perform the checks after legalize when the pattern is available.
8422   if (DCI.isBeforeLegalize()) return SDValue();
8423
8424   // Look for multiply add opportunities.
8425   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8426   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8427   // a glue link from the first add to the second add.
8428   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8429   // a S/UMLAL instruction.
8430   //                  UMUL_LOHI
8431   //                 / :lo    \ :hi
8432   //                /          \          [no multiline comment]
8433   //    loAdd ->  ADDE         |
8434   //                 \ :glue  /
8435   //                  \      /
8436   //                    ADDC   <- hiAdd
8437   //
8438   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8439   SDValue AddcOp0 = AddcNode->getOperand(0);
8440   SDValue AddcOp1 = AddcNode->getOperand(1);
8441
8442   // Check if the two operands are from the same mul_lohi node.
8443   if (AddcOp0.getNode() == AddcOp1.getNode())
8444     return SDValue();
8445
8446   assert(AddcNode->getNumValues() == 2 &&
8447          AddcNode->getValueType(0) == MVT::i32 &&
8448          "Expect ADDC with two result values. First: i32");
8449
8450   // Check that we have a glued ADDC node.
8451   if (AddcNode->getValueType(1) != MVT::Glue)
8452     return SDValue();
8453
8454   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8455   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8456       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8457       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8458       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8459     return SDValue();
8460
8461   // Look for the glued ADDE.
8462   SDNode* AddeNode = AddcNode->getGluedUser();
8463   if (!AddeNode)
8464     return SDValue();
8465
8466   // Make sure it is really an ADDE.
8467   if (AddeNode->getOpcode() != ISD::ADDE)
8468     return SDValue();
8469
8470   assert(AddeNode->getNumOperands() == 3 &&
8471          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8472          "ADDE node has the wrong inputs");
8473
8474   // Check for the triangle shape.
8475   SDValue AddeOp0 = AddeNode->getOperand(0);
8476   SDValue AddeOp1 = AddeNode->getOperand(1);
8477
8478   // Make sure that the ADDE operands are not coming from the same node.
8479   if (AddeOp0.getNode() == AddeOp1.getNode())
8480     return SDValue();
8481
8482   // Find the MUL_LOHI node walking up ADDE's operands.
8483   bool IsLeftOperandMUL = false;
8484   SDValue MULOp = findMUL_LOHI(AddeOp0);
8485   if (MULOp == SDValue())
8486    MULOp = findMUL_LOHI(AddeOp1);
8487   else
8488     IsLeftOperandMUL = true;
8489   if (MULOp == SDValue())
8490     return SDValue();
8491
8492   // Figure out the right opcode.
8493   unsigned Opc = MULOp->getOpcode();
8494   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8495
8496   // Figure out the high and low input values to the MLAL node.
8497   SDValue* HiAdd = nullptr;
8498   SDValue* LoMul = nullptr;
8499   SDValue* LowAdd = nullptr;
8500
8501   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8502   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8503     return SDValue();
8504
8505   if (IsLeftOperandMUL)
8506     HiAdd = &AddeOp1;
8507   else
8508     HiAdd = &AddeOp0;
8509
8510
8511   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8512   // whose low result is fed to the ADDC we are checking.
8513
8514   if (AddcOp0 == MULOp.getValue(0)) {
8515     LoMul = &AddcOp0;
8516     LowAdd = &AddcOp1;
8517   }
8518   if (AddcOp1 == MULOp.getValue(0)) {
8519     LoMul = &AddcOp1;
8520     LowAdd = &AddcOp0;
8521   }
8522
8523   if (!LoMul)
8524     return SDValue();
8525
8526   // Create the merged node.
8527   SelectionDAG &DAG = DCI.DAG;
8528
8529   // Build operand list.
8530   SmallVector<SDValue, 8> Ops;
8531   Ops.push_back(LoMul->getOperand(0));
8532   Ops.push_back(LoMul->getOperand(1));
8533   Ops.push_back(*LowAdd);
8534   Ops.push_back(*HiAdd);
8535
8536   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8537                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8538
8539   // Replace the ADDs' nodes uses by the MLA node's values.
8540   SDValue HiMLALResult(MLALNode.getNode(), 1);
8541   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8542
8543   SDValue LoMLALResult(MLALNode.getNode(), 0);
8544   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8545
8546   // Return original node to notify the driver to stop replacing.
8547   SDValue resNode(AddcNode, 0);
8548   return resNode;
8549 }
8550
8551 /// PerformADDCCombine - Target-specific dag combine transform from
8552 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8553 static SDValue PerformADDCCombine(SDNode *N,
8554                                  TargetLowering::DAGCombinerInfo &DCI,
8555                                  const ARMSubtarget *Subtarget) {
8556
8557   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8558
8559 }
8560
8561 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8562 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8563 /// called with the default operands, and if that fails, with commuted
8564 /// operands.
8565 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8566                                           TargetLowering::DAGCombinerInfo &DCI,
8567                                           const ARMSubtarget *Subtarget){
8568
8569   // Attempt to create vpaddl for this add.
8570   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8571   if (Result.getNode())
8572     return Result;
8573
8574   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8575   if (N0.getNode()->hasOneUse()) {
8576     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8577     if (Result.getNode()) return Result;
8578   }
8579   return SDValue();
8580 }
8581
8582 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8583 ///
8584 static SDValue PerformADDCombine(SDNode *N,
8585                                  TargetLowering::DAGCombinerInfo &DCI,
8586                                  const ARMSubtarget *Subtarget) {
8587   SDValue N0 = N->getOperand(0);
8588   SDValue N1 = N->getOperand(1);
8589
8590   // First try with the default operand order.
8591   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8592   if (Result.getNode())
8593     return Result;
8594
8595   // If that didn't work, try again with the operands commuted.
8596   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8597 }
8598
8599 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8600 ///
8601 static SDValue PerformSUBCombine(SDNode *N,
8602                                  TargetLowering::DAGCombinerInfo &DCI) {
8603   SDValue N0 = N->getOperand(0);
8604   SDValue N1 = N->getOperand(1);
8605
8606   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8607   if (N1.getNode()->hasOneUse()) {
8608     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8609     if (Result.getNode()) return Result;
8610   }
8611
8612   return SDValue();
8613 }
8614
8615 /// PerformVMULCombine
8616 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8617 /// special multiplier accumulator forwarding.
8618 ///   vmul d3, d0, d2
8619 ///   vmla d3, d1, d2
8620 /// is faster than
8621 ///   vadd d3, d0, d1
8622 ///   vmul d3, d3, d2
8623 //  However, for (A + B) * (A + B),
8624 //    vadd d2, d0, d1
8625 //    vmul d3, d0, d2
8626 //    vmla d3, d1, d2
8627 //  is slower than
8628 //    vadd d2, d0, d1
8629 //    vmul d3, d2, d2
8630 static SDValue PerformVMULCombine(SDNode *N,
8631                                   TargetLowering::DAGCombinerInfo &DCI,
8632                                   const ARMSubtarget *Subtarget) {
8633   if (!Subtarget->hasVMLxForwarding())
8634     return SDValue();
8635
8636   SelectionDAG &DAG = DCI.DAG;
8637   SDValue N0 = N->getOperand(0);
8638   SDValue N1 = N->getOperand(1);
8639   unsigned Opcode = N0.getOpcode();
8640   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8641       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8642     Opcode = N1.getOpcode();
8643     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8644         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8645       return SDValue();
8646     std::swap(N0, N1);
8647   }
8648
8649   if (N0 == N1)
8650     return SDValue();
8651
8652   EVT VT = N->getValueType(0);
8653   SDLoc DL(N);
8654   SDValue N00 = N0->getOperand(0);
8655   SDValue N01 = N0->getOperand(1);
8656   return DAG.getNode(Opcode, DL, VT,
8657                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8658                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8659 }
8660
8661 static SDValue PerformMULCombine(SDNode *N,
8662                                  TargetLowering::DAGCombinerInfo &DCI,
8663                                  const ARMSubtarget *Subtarget) {
8664   SelectionDAG &DAG = DCI.DAG;
8665
8666   if (Subtarget->isThumb1Only())
8667     return SDValue();
8668
8669   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8670     return SDValue();
8671
8672   EVT VT = N->getValueType(0);
8673   if (VT.is64BitVector() || VT.is128BitVector())
8674     return PerformVMULCombine(N, DCI, Subtarget);
8675   if (VT != MVT::i32)
8676     return SDValue();
8677
8678   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8679   if (!C)
8680     return SDValue();
8681
8682   int64_t MulAmt = C->getSExtValue();
8683   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8684
8685   ShiftAmt = ShiftAmt & (32 - 1);
8686   SDValue V = N->getOperand(0);
8687   SDLoc DL(N);
8688
8689   SDValue Res;
8690   MulAmt >>= ShiftAmt;
8691
8692   if (MulAmt >= 0) {
8693     if (isPowerOf2_32(MulAmt - 1)) {
8694       // (mul x, 2^N + 1) => (add (shl x, N), x)
8695       Res = DAG.getNode(ISD::ADD, DL, VT,
8696                         V,
8697                         DAG.getNode(ISD::SHL, DL, VT,
8698                                     V,
8699                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8700                                                     MVT::i32)));
8701     } else if (isPowerOf2_32(MulAmt + 1)) {
8702       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8703       Res = DAG.getNode(ISD::SUB, DL, VT,
8704                         DAG.getNode(ISD::SHL, DL, VT,
8705                                     V,
8706                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8707                                                     MVT::i32)),
8708                         V);
8709     } else
8710       return SDValue();
8711   } else {
8712     uint64_t MulAmtAbs = -MulAmt;
8713     if (isPowerOf2_32(MulAmtAbs + 1)) {
8714       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8715       Res = DAG.getNode(ISD::SUB, DL, VT,
8716                         V,
8717                         DAG.getNode(ISD::SHL, DL, VT,
8718                                     V,
8719                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8720                                                     MVT::i32)));
8721     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8722       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8723       Res = DAG.getNode(ISD::ADD, DL, VT,
8724                         V,
8725                         DAG.getNode(ISD::SHL, DL, VT,
8726                                     V,
8727                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8728                                                     MVT::i32)));
8729       Res = DAG.getNode(ISD::SUB, DL, VT,
8730                         DAG.getConstant(0, DL, MVT::i32), Res);
8731
8732     } else
8733       return SDValue();
8734   }
8735
8736   if (ShiftAmt != 0)
8737     Res = DAG.getNode(ISD::SHL, DL, VT,
8738                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8739
8740   // Do not add new nodes to DAG combiner worklist.
8741   DCI.CombineTo(N, Res, false);
8742   return SDValue();
8743 }
8744
8745 static SDValue PerformANDCombine(SDNode *N,
8746                                  TargetLowering::DAGCombinerInfo &DCI,
8747                                  const ARMSubtarget *Subtarget) {
8748
8749   // Attempt to use immediate-form VBIC
8750   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8751   SDLoc dl(N);
8752   EVT VT = N->getValueType(0);
8753   SelectionDAG &DAG = DCI.DAG;
8754
8755   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8756     return SDValue();
8757
8758   APInt SplatBits, SplatUndef;
8759   unsigned SplatBitSize;
8760   bool HasAnyUndefs;
8761   if (BVN &&
8762       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8763     if (SplatBitSize <= 64) {
8764       EVT VbicVT;
8765       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8766                                       SplatUndef.getZExtValue(), SplatBitSize,
8767                                       DAG, dl, VbicVT, VT.is128BitVector(),
8768                                       OtherModImm);
8769       if (Val.getNode()) {
8770         SDValue Input =
8771           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8772         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8773         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8774       }
8775     }
8776   }
8777
8778   if (!Subtarget->isThumb1Only()) {
8779     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8780     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8781     if (Result.getNode())
8782       return Result;
8783   }
8784
8785   return SDValue();
8786 }
8787
8788 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8789 static SDValue PerformORCombine(SDNode *N,
8790                                 TargetLowering::DAGCombinerInfo &DCI,
8791                                 const ARMSubtarget *Subtarget) {
8792   // Attempt to use immediate-form VORR
8793   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8794   SDLoc dl(N);
8795   EVT VT = N->getValueType(0);
8796   SelectionDAG &DAG = DCI.DAG;
8797
8798   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8799     return SDValue();
8800
8801   APInt SplatBits, SplatUndef;
8802   unsigned SplatBitSize;
8803   bool HasAnyUndefs;
8804   if (BVN && Subtarget->hasNEON() &&
8805       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8806     if (SplatBitSize <= 64) {
8807       EVT VorrVT;
8808       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8809                                       SplatUndef.getZExtValue(), SplatBitSize,
8810                                       DAG, dl, VorrVT, VT.is128BitVector(),
8811                                       OtherModImm);
8812       if (Val.getNode()) {
8813         SDValue Input =
8814           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8815         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8816         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8817       }
8818     }
8819   }
8820
8821   if (!Subtarget->isThumb1Only()) {
8822     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8823     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8824     if (Result.getNode())
8825       return Result;
8826   }
8827
8828   // The code below optimizes (or (and X, Y), Z).
8829   // The AND operand needs to have a single user to make these optimizations
8830   // profitable.
8831   SDValue N0 = N->getOperand(0);
8832   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8833     return SDValue();
8834   SDValue N1 = N->getOperand(1);
8835
8836   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8837   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8838       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8839     APInt SplatUndef;
8840     unsigned SplatBitSize;
8841     bool HasAnyUndefs;
8842
8843     APInt SplatBits0, SplatBits1;
8844     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8845     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8846     // Ensure that the second operand of both ands are constants
8847     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8848                                       HasAnyUndefs) && !HasAnyUndefs) {
8849         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8850                                           HasAnyUndefs) && !HasAnyUndefs) {
8851             // Ensure that the bit width of the constants are the same and that
8852             // the splat arguments are logical inverses as per the pattern we
8853             // are trying to simplify.
8854             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8855                 SplatBits0 == ~SplatBits1) {
8856                 // Canonicalize the vector type to make instruction selection
8857                 // simpler.
8858                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8859                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8860                                              N0->getOperand(1),
8861                                              N0->getOperand(0),
8862                                              N1->getOperand(0));
8863                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8864             }
8865         }
8866     }
8867   }
8868
8869   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8870   // reasonable.
8871
8872   // BFI is only available on V6T2+
8873   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8874     return SDValue();
8875
8876   SDLoc DL(N);
8877   // 1) or (and A, mask), val => ARMbfi A, val, mask
8878   //      iff (val & mask) == val
8879   //
8880   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8881   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8882   //          && mask == ~mask2
8883   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8884   //          && ~mask == mask2
8885   //  (i.e., copy a bitfield value into another bitfield of the same width)
8886
8887   if (VT != MVT::i32)
8888     return SDValue();
8889
8890   SDValue N00 = N0.getOperand(0);
8891
8892   // The value and the mask need to be constants so we can verify this is
8893   // actually a bitfield set. If the mask is 0xffff, we can do better
8894   // via a movt instruction, so don't use BFI in that case.
8895   SDValue MaskOp = N0.getOperand(1);
8896   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8897   if (!MaskC)
8898     return SDValue();
8899   unsigned Mask = MaskC->getZExtValue();
8900   if (Mask == 0xffff)
8901     return SDValue();
8902   SDValue Res;
8903   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8904   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8905   if (N1C) {
8906     unsigned Val = N1C->getZExtValue();
8907     if ((Val & ~Mask) != Val)
8908       return SDValue();
8909
8910     if (ARM::isBitFieldInvertedMask(Mask)) {
8911       Val >>= countTrailingZeros(~Mask);
8912
8913       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8914                         DAG.getConstant(Val, DL, MVT::i32),
8915                         DAG.getConstant(Mask, DL, MVT::i32));
8916
8917       // Do not add new nodes to DAG combiner worklist.
8918       DCI.CombineTo(N, Res, false);
8919       return SDValue();
8920     }
8921   } else if (N1.getOpcode() == ISD::AND) {
8922     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8923     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8924     if (!N11C)
8925       return SDValue();
8926     unsigned Mask2 = N11C->getZExtValue();
8927
8928     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8929     // as is to match.
8930     if (ARM::isBitFieldInvertedMask(Mask) &&
8931         (Mask == ~Mask2)) {
8932       // The pack halfword instruction works better for masks that fit it,
8933       // so use that when it's available.
8934       if (Subtarget->hasT2ExtractPack() &&
8935           (Mask == 0xffff || Mask == 0xffff0000))
8936         return SDValue();
8937       // 2a
8938       unsigned amt = countTrailingZeros(Mask2);
8939       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8940                         DAG.getConstant(amt, DL, MVT::i32));
8941       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8942                         DAG.getConstant(Mask, DL, MVT::i32));
8943       // Do not add new nodes to DAG combiner worklist.
8944       DCI.CombineTo(N, Res, false);
8945       return SDValue();
8946     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8947                (~Mask == Mask2)) {
8948       // The pack halfword instruction works better for masks that fit it,
8949       // so use that when it's available.
8950       if (Subtarget->hasT2ExtractPack() &&
8951           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8952         return SDValue();
8953       // 2b
8954       unsigned lsb = countTrailingZeros(Mask);
8955       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8956                         DAG.getConstant(lsb, DL, MVT::i32));
8957       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8958                         DAG.getConstant(Mask2, DL, MVT::i32));
8959       // Do not add new nodes to DAG combiner worklist.
8960       DCI.CombineTo(N, Res, false);
8961       return SDValue();
8962     }
8963   }
8964
8965   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8966       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8967       ARM::isBitFieldInvertedMask(~Mask)) {
8968     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8969     // where lsb(mask) == #shamt and masked bits of B are known zero.
8970     SDValue ShAmt = N00.getOperand(1);
8971     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8972     unsigned LSB = countTrailingZeros(Mask);
8973     if (ShAmtC != LSB)
8974       return SDValue();
8975
8976     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8977                       DAG.getConstant(~Mask, DL, MVT::i32));
8978
8979     // Do not add new nodes to DAG combiner worklist.
8980     DCI.CombineTo(N, Res, false);
8981   }
8982
8983   return SDValue();
8984 }
8985
8986 static SDValue PerformXORCombine(SDNode *N,
8987                                  TargetLowering::DAGCombinerInfo &DCI,
8988                                  const ARMSubtarget *Subtarget) {
8989   EVT VT = N->getValueType(0);
8990   SelectionDAG &DAG = DCI.DAG;
8991
8992   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8993     return SDValue();
8994
8995   if (!Subtarget->isThumb1Only()) {
8996     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8997     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8998     if (Result.getNode())
8999       return Result;
9000   }
9001
9002   return SDValue();
9003 }
9004
9005 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9006 /// the bits being cleared by the AND are not demanded by the BFI.
9007 static SDValue PerformBFICombine(SDNode *N,
9008                                  TargetLowering::DAGCombinerInfo &DCI) {
9009   SDValue N1 = N->getOperand(1);
9010   if (N1.getOpcode() == ISD::AND) {
9011     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9012     if (!N11C)
9013       return SDValue();
9014     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9015     unsigned LSB = countTrailingZeros(~InvMask);
9016     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9017     assert(Width <
9018                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9019            "undefined behavior");
9020     unsigned Mask = (1u << Width) - 1;
9021     unsigned Mask2 = N11C->getZExtValue();
9022     if ((Mask & (~Mask2)) == 0)
9023       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9024                              N->getOperand(0), N1.getOperand(0),
9025                              N->getOperand(2));
9026   }
9027   return SDValue();
9028 }
9029
9030 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9031 /// ARMISD::VMOVRRD.
9032 static SDValue PerformVMOVRRDCombine(SDNode *N,
9033                                      TargetLowering::DAGCombinerInfo &DCI,
9034                                      const ARMSubtarget *Subtarget) {
9035   // vmovrrd(vmovdrr x, y) -> x,y
9036   SDValue InDouble = N->getOperand(0);
9037   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9038     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9039
9040   // vmovrrd(load f64) -> (load i32), (load i32)
9041   SDNode *InNode = InDouble.getNode();
9042   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9043       InNode->getValueType(0) == MVT::f64 &&
9044       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9045       !cast<LoadSDNode>(InNode)->isVolatile()) {
9046     // TODO: Should this be done for non-FrameIndex operands?
9047     LoadSDNode *LD = cast<LoadSDNode>(InNode);
9048
9049     SelectionDAG &DAG = DCI.DAG;
9050     SDLoc DL(LD);
9051     SDValue BasePtr = LD->getBasePtr();
9052     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9053                                  LD->getPointerInfo(), LD->isVolatile(),
9054                                  LD->isNonTemporal(), LD->isInvariant(),
9055                                  LD->getAlignment());
9056
9057     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9058                                     DAG.getConstant(4, DL, MVT::i32));
9059     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9060                                  LD->getPointerInfo(), LD->isVolatile(),
9061                                  LD->isNonTemporal(), LD->isInvariant(),
9062                                  std::min(4U, LD->getAlignment() / 2));
9063
9064     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9065     if (DCI.DAG.getDataLayout().isBigEndian())
9066       std::swap (NewLD1, NewLD2);
9067     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9068     return Result;
9069   }
9070
9071   return SDValue();
9072 }
9073
9074 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9075 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
9076 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9077   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9078   SDValue Op0 = N->getOperand(0);
9079   SDValue Op1 = N->getOperand(1);
9080   if (Op0.getOpcode() == ISD::BITCAST)
9081     Op0 = Op0.getOperand(0);
9082   if (Op1.getOpcode() == ISD::BITCAST)
9083     Op1 = Op1.getOperand(0);
9084   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9085       Op0.getNode() == Op1.getNode() &&
9086       Op0.getResNo() == 0 && Op1.getResNo() == 1)
9087     return DAG.getNode(ISD::BITCAST, SDLoc(N),
9088                        N->getValueType(0), Op0.getOperand(0));
9089   return SDValue();
9090 }
9091
9092 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9093 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9094 /// i64 vector to have f64 elements, since the value can then be loaded
9095 /// directly into a VFP register.
9096 static bool hasNormalLoadOperand(SDNode *N) {
9097   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9098   for (unsigned i = 0; i < NumElts; ++i) {
9099     SDNode *Elt = N->getOperand(i).getNode();
9100     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9101       return true;
9102   }
9103   return false;
9104 }
9105
9106 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9107 /// ISD::BUILD_VECTOR.
9108 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9109                                           TargetLowering::DAGCombinerInfo &DCI,
9110                                           const ARMSubtarget *Subtarget) {
9111   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9112   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9113   // into a pair of GPRs, which is fine when the value is used as a scalar,
9114   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9115   SelectionDAG &DAG = DCI.DAG;
9116   if (N->getNumOperands() == 2) {
9117     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9118     if (RV.getNode())
9119       return RV;
9120   }
9121
9122   // Load i64 elements as f64 values so that type legalization does not split
9123   // them up into i32 values.
9124   EVT VT = N->getValueType(0);
9125   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9126     return SDValue();
9127   SDLoc dl(N);
9128   SmallVector<SDValue, 8> Ops;
9129   unsigned NumElts = VT.getVectorNumElements();
9130   for (unsigned i = 0; i < NumElts; ++i) {
9131     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9132     Ops.push_back(V);
9133     // Make the DAGCombiner fold the bitcast.
9134     DCI.AddToWorklist(V.getNode());
9135   }
9136   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9137   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9138   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9139 }
9140
9141 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9142 static SDValue
9143 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9144   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9145   // At that time, we may have inserted bitcasts from integer to float.
9146   // If these bitcasts have survived DAGCombine, change the lowering of this
9147   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9148   // force to use floating point types.
9149
9150   // Make sure we can change the type of the vector.
9151   // This is possible iff:
9152   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9153   //    1.1. Vector is used only once.
9154   //    1.2. Use is a bit convert to an integer type.
9155   // 2. The size of its operands are 32-bits (64-bits are not legal).
9156   EVT VT = N->getValueType(0);
9157   EVT EltVT = VT.getVectorElementType();
9158
9159   // Check 1.1. and 2.
9160   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9161     return SDValue();
9162
9163   // By construction, the input type must be float.
9164   assert(EltVT == MVT::f32 && "Unexpected type!");
9165
9166   // Check 1.2.
9167   SDNode *Use = *N->use_begin();
9168   if (Use->getOpcode() != ISD::BITCAST ||
9169       Use->getValueType(0).isFloatingPoint())
9170     return SDValue();
9171
9172   // Check profitability.
9173   // Model is, if more than half of the relevant operands are bitcast from
9174   // i32, turn the build_vector into a sequence of insert_vector_elt.
9175   // Relevant operands are everything that is not statically
9176   // (i.e., at compile time) bitcasted.
9177   unsigned NumOfBitCastedElts = 0;
9178   unsigned NumElts = VT.getVectorNumElements();
9179   unsigned NumOfRelevantElts = NumElts;
9180   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9181     SDValue Elt = N->getOperand(Idx);
9182     if (Elt->getOpcode() == ISD::BITCAST) {
9183       // Assume only bit cast to i32 will go away.
9184       if (Elt->getOperand(0).getValueType() == MVT::i32)
9185         ++NumOfBitCastedElts;
9186     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9187       // Constants are statically casted, thus do not count them as
9188       // relevant operands.
9189       --NumOfRelevantElts;
9190   }
9191
9192   // Check if more than half of the elements require a non-free bitcast.
9193   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9194     return SDValue();
9195
9196   SelectionDAG &DAG = DCI.DAG;
9197   // Create the new vector type.
9198   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9199   // Check if the type is legal.
9200   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9201   if (!TLI.isTypeLegal(VecVT))
9202     return SDValue();
9203
9204   // Combine:
9205   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9206   // => BITCAST INSERT_VECTOR_ELT
9207   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9208   //                      (BITCAST EN), N.
9209   SDValue Vec = DAG.getUNDEF(VecVT);
9210   SDLoc dl(N);
9211   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9212     SDValue V = N->getOperand(Idx);
9213     if (V.getOpcode() == ISD::UNDEF)
9214       continue;
9215     if (V.getOpcode() == ISD::BITCAST &&
9216         V->getOperand(0).getValueType() == MVT::i32)
9217       // Fold obvious case.
9218       V = V.getOperand(0);
9219     else {
9220       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9221       // Make the DAGCombiner fold the bitcasts.
9222       DCI.AddToWorklist(V.getNode());
9223     }
9224     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9225     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9226   }
9227   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9228   // Make the DAGCombiner fold the bitcasts.
9229   DCI.AddToWorklist(Vec.getNode());
9230   return Vec;
9231 }
9232
9233 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9234 /// ISD::INSERT_VECTOR_ELT.
9235 static SDValue PerformInsertEltCombine(SDNode *N,
9236                                        TargetLowering::DAGCombinerInfo &DCI) {
9237   // Bitcast an i64 load inserted into a vector to f64.
9238   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9239   EVT VT = N->getValueType(0);
9240   SDNode *Elt = N->getOperand(1).getNode();
9241   if (VT.getVectorElementType() != MVT::i64 ||
9242       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9243     return SDValue();
9244
9245   SelectionDAG &DAG = DCI.DAG;
9246   SDLoc dl(N);
9247   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9248                                  VT.getVectorNumElements());
9249   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9250   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9251   // Make the DAGCombiner fold the bitcasts.
9252   DCI.AddToWorklist(Vec.getNode());
9253   DCI.AddToWorklist(V.getNode());
9254   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9255                                Vec, V, N->getOperand(2));
9256   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9257 }
9258
9259 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9260 /// ISD::VECTOR_SHUFFLE.
9261 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9262   // The LLVM shufflevector instruction does not require the shuffle mask
9263   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9264   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9265   // operands do not match the mask length, they are extended by concatenating
9266   // them with undef vectors.  That is probably the right thing for other
9267   // targets, but for NEON it is better to concatenate two double-register
9268   // size vector operands into a single quad-register size vector.  Do that
9269   // transformation here:
9270   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9271   //   shuffle(concat(v1, v2), undef)
9272   SDValue Op0 = N->getOperand(0);
9273   SDValue Op1 = N->getOperand(1);
9274   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9275       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9276       Op0.getNumOperands() != 2 ||
9277       Op1.getNumOperands() != 2)
9278     return SDValue();
9279   SDValue Concat0Op1 = Op0.getOperand(1);
9280   SDValue Concat1Op1 = Op1.getOperand(1);
9281   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9282       Concat1Op1.getOpcode() != ISD::UNDEF)
9283     return SDValue();
9284   // Skip the transformation if any of the types are illegal.
9285   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9286   EVT VT = N->getValueType(0);
9287   if (!TLI.isTypeLegal(VT) ||
9288       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9289       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9290     return SDValue();
9291
9292   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9293                                   Op0.getOperand(0), Op1.getOperand(0));
9294   // Translate the shuffle mask.
9295   SmallVector<int, 16> NewMask;
9296   unsigned NumElts = VT.getVectorNumElements();
9297   unsigned HalfElts = NumElts/2;
9298   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9299   for (unsigned n = 0; n < NumElts; ++n) {
9300     int MaskElt = SVN->getMaskElt(n);
9301     int NewElt = -1;
9302     if (MaskElt < (int)HalfElts)
9303       NewElt = MaskElt;
9304     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9305       NewElt = HalfElts + MaskElt - NumElts;
9306     NewMask.push_back(NewElt);
9307   }
9308   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9309                               DAG.getUNDEF(VT), NewMask.data());
9310 }
9311
9312 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9313 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9314 /// base address updates.
9315 /// For generic load/stores, the memory type is assumed to be a vector.
9316 /// The caller is assumed to have checked legality.
9317 static SDValue CombineBaseUpdate(SDNode *N,
9318                                  TargetLowering::DAGCombinerInfo &DCI) {
9319   SelectionDAG &DAG = DCI.DAG;
9320   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9321                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9322   const bool isStore = N->getOpcode() == ISD::STORE;
9323   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9324   SDValue Addr = N->getOperand(AddrOpIdx);
9325   MemSDNode *MemN = cast<MemSDNode>(N);
9326   SDLoc dl(N);
9327
9328   // Search for a use of the address operand that is an increment.
9329   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9330          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9331     SDNode *User = *UI;
9332     if (User->getOpcode() != ISD::ADD ||
9333         UI.getUse().getResNo() != Addr.getResNo())
9334       continue;
9335
9336     // Check that the add is independent of the load/store.  Otherwise, folding
9337     // it would create a cycle.
9338     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9339       continue;
9340
9341     // Find the new opcode for the updating load/store.
9342     bool isLoadOp = true;
9343     bool isLaneOp = false;
9344     unsigned NewOpc = 0;
9345     unsigned NumVecs = 0;
9346     if (isIntrinsic) {
9347       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9348       switch (IntNo) {
9349       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9350       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9351         NumVecs = 1; break;
9352       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9353         NumVecs = 2; break;
9354       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9355         NumVecs = 3; break;
9356       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9357         NumVecs = 4; break;
9358       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9359         NumVecs = 2; isLaneOp = true; break;
9360       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9361         NumVecs = 3; isLaneOp = true; break;
9362       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9363         NumVecs = 4; isLaneOp = true; break;
9364       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9365         NumVecs = 1; isLoadOp = false; break;
9366       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9367         NumVecs = 2; isLoadOp = false; break;
9368       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9369         NumVecs = 3; isLoadOp = false; break;
9370       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9371         NumVecs = 4; isLoadOp = false; break;
9372       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9373         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9374       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9375         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9376       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9377         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9378       }
9379     } else {
9380       isLaneOp = true;
9381       switch (N->getOpcode()) {
9382       default: llvm_unreachable("unexpected opcode for Neon base update");
9383       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9384       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9385       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9386       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9387         NumVecs = 1; isLaneOp = false; break;
9388       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9389         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9390       }
9391     }
9392
9393     // Find the size of memory referenced by the load/store.
9394     EVT VecTy;
9395     if (isLoadOp) {
9396       VecTy = N->getValueType(0);
9397     } else if (isIntrinsic) {
9398       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9399     } else {
9400       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9401       VecTy = N->getOperand(1).getValueType();
9402     }
9403
9404     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9405     if (isLaneOp)
9406       NumBytes /= VecTy.getVectorNumElements();
9407
9408     // If the increment is a constant, it must match the memory ref size.
9409     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9410     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9411       uint64_t IncVal = CInc->getZExtValue();
9412       if (IncVal != NumBytes)
9413         continue;
9414     } else if (NumBytes >= 3 * 16) {
9415       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9416       // separate instructions that make it harder to use a non-constant update.
9417       continue;
9418     }
9419
9420     // OK, we found an ADD we can fold into the base update.
9421     // Now, create a _UPD node, taking care of not breaking alignment.
9422
9423     EVT AlignedVecTy = VecTy;
9424     unsigned Alignment = MemN->getAlignment();
9425
9426     // If this is a less-than-standard-aligned load/store, change the type to
9427     // match the standard alignment.
9428     // The alignment is overlooked when selecting _UPD variants; and it's
9429     // easier to introduce bitcasts here than fix that.
9430     // There are 3 ways to get to this base-update combine:
9431     // - intrinsics: they are assumed to be properly aligned (to the standard
9432     //   alignment of the memory type), so we don't need to do anything.
9433     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9434     //   intrinsics, so, likewise, there's nothing to do.
9435     // - generic load/store instructions: the alignment is specified as an
9436     //   explicit operand, rather than implicitly as the standard alignment
9437     //   of the memory type (like the intrisics).  We need to change the
9438     //   memory type to match the explicit alignment.  That way, we don't
9439     //   generate non-standard-aligned ARMISD::VLDx nodes.
9440     if (isa<LSBaseSDNode>(N)) {
9441       if (Alignment == 0)
9442         Alignment = 1;
9443       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9444         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9445         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9446         assert(!isLaneOp && "Unexpected generic load/store lane.");
9447         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9448         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9449       }
9450       // Don't set an explicit alignment on regular load/stores that we want
9451       // to transform to VLD/VST 1_UPD nodes.
9452       // This matches the behavior of regular load/stores, which only get an
9453       // explicit alignment if the MMO alignment is larger than the standard
9454       // alignment of the memory type.
9455       // Intrinsics, however, always get an explicit alignment, set to the
9456       // alignment of the MMO.
9457       Alignment = 1;
9458     }
9459
9460     // Create the new updating load/store node.
9461     // First, create an SDVTList for the new updating node's results.
9462     EVT Tys[6];
9463     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9464     unsigned n;
9465     for (n = 0; n < NumResultVecs; ++n)
9466       Tys[n] = AlignedVecTy;
9467     Tys[n++] = MVT::i32;
9468     Tys[n] = MVT::Other;
9469     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9470
9471     // Then, gather the new node's operands.
9472     SmallVector<SDValue, 8> Ops;
9473     Ops.push_back(N->getOperand(0)); // incoming chain
9474     Ops.push_back(N->getOperand(AddrOpIdx));
9475     Ops.push_back(Inc);
9476
9477     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9478       // Try to match the intrinsic's signature
9479       Ops.push_back(StN->getValue());
9480     } else {
9481       // Loads (and of course intrinsics) match the intrinsics' signature,
9482       // so just add all but the alignment operand.
9483       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9484         Ops.push_back(N->getOperand(i));
9485     }
9486
9487     // For all node types, the alignment operand is always the last one.
9488     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9489
9490     // If this is a non-standard-aligned STORE, the penultimate operand is the
9491     // stored value.  Bitcast it to the aligned type.
9492     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9493       SDValue &StVal = Ops[Ops.size()-2];
9494       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9495     }
9496
9497     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9498                                            Ops, AlignedVecTy,
9499                                            MemN->getMemOperand());
9500
9501     // Update the uses.
9502     SmallVector<SDValue, 5> NewResults;
9503     for (unsigned i = 0; i < NumResultVecs; ++i)
9504       NewResults.push_back(SDValue(UpdN.getNode(), i));
9505
9506     // If this is an non-standard-aligned LOAD, the first result is the loaded
9507     // value.  Bitcast it to the expected result type.
9508     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9509       SDValue &LdVal = NewResults[0];
9510       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9511     }
9512
9513     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9514     DCI.CombineTo(N, NewResults);
9515     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9516
9517     break;
9518   }
9519   return SDValue();
9520 }
9521
9522 static SDValue PerformVLDCombine(SDNode *N,
9523                                  TargetLowering::DAGCombinerInfo &DCI) {
9524   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9525     return SDValue();
9526
9527   return CombineBaseUpdate(N, DCI);
9528 }
9529
9530 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9531 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9532 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9533 /// return true.
9534 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9535   SelectionDAG &DAG = DCI.DAG;
9536   EVT VT = N->getValueType(0);
9537   // vldN-dup instructions only support 64-bit vectors for N > 1.
9538   if (!VT.is64BitVector())
9539     return false;
9540
9541   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9542   SDNode *VLD = N->getOperand(0).getNode();
9543   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9544     return false;
9545   unsigned NumVecs = 0;
9546   unsigned NewOpc = 0;
9547   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9548   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9549     NumVecs = 2;
9550     NewOpc = ARMISD::VLD2DUP;
9551   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9552     NumVecs = 3;
9553     NewOpc = ARMISD::VLD3DUP;
9554   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9555     NumVecs = 4;
9556     NewOpc = ARMISD::VLD4DUP;
9557   } else {
9558     return false;
9559   }
9560
9561   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9562   // numbers match the load.
9563   unsigned VLDLaneNo =
9564     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9565   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9566        UI != UE; ++UI) {
9567     // Ignore uses of the chain result.
9568     if (UI.getUse().getResNo() == NumVecs)
9569       continue;
9570     SDNode *User = *UI;
9571     if (User->getOpcode() != ARMISD::VDUPLANE ||
9572         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9573       return false;
9574   }
9575
9576   // Create the vldN-dup node.
9577   EVT Tys[5];
9578   unsigned n;
9579   for (n = 0; n < NumVecs; ++n)
9580     Tys[n] = VT;
9581   Tys[n] = MVT::Other;
9582   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9583   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9584   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9585   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9586                                            Ops, VLDMemInt->getMemoryVT(),
9587                                            VLDMemInt->getMemOperand());
9588
9589   // Update the uses.
9590   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9591        UI != UE; ++UI) {
9592     unsigned ResNo = UI.getUse().getResNo();
9593     // Ignore uses of the chain result.
9594     if (ResNo == NumVecs)
9595       continue;
9596     SDNode *User = *UI;
9597     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9598   }
9599
9600   // Now the vldN-lane intrinsic is dead except for its chain result.
9601   // Update uses of the chain.
9602   std::vector<SDValue> VLDDupResults;
9603   for (unsigned n = 0; n < NumVecs; ++n)
9604     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9605   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9606   DCI.CombineTo(VLD, VLDDupResults);
9607
9608   return true;
9609 }
9610
9611 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9612 /// ARMISD::VDUPLANE.
9613 static SDValue PerformVDUPLANECombine(SDNode *N,
9614                                       TargetLowering::DAGCombinerInfo &DCI) {
9615   SDValue Op = N->getOperand(0);
9616
9617   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9618   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9619   if (CombineVLDDUP(N, DCI))
9620     return SDValue(N, 0);
9621
9622   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9623   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9624   while (Op.getOpcode() == ISD::BITCAST)
9625     Op = Op.getOperand(0);
9626   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9627     return SDValue();
9628
9629   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9630   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9631   // The canonical VMOV for a zero vector uses a 32-bit element size.
9632   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9633   unsigned EltBits;
9634   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9635     EltSize = 8;
9636   EVT VT = N->getValueType(0);
9637   if (EltSize > VT.getVectorElementType().getSizeInBits())
9638     return SDValue();
9639
9640   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9641 }
9642
9643 static SDValue PerformLOADCombine(SDNode *N,
9644                                   TargetLowering::DAGCombinerInfo &DCI) {
9645   EVT VT = N->getValueType(0);
9646
9647   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9648   if (ISD::isNormalLoad(N) && VT.isVector() &&
9649       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9650     return CombineBaseUpdate(N, DCI);
9651
9652   return SDValue();
9653 }
9654
9655 /// PerformSTORECombine - Target-specific dag combine xforms for
9656 /// ISD::STORE.
9657 static SDValue PerformSTORECombine(SDNode *N,
9658                                    TargetLowering::DAGCombinerInfo &DCI) {
9659   StoreSDNode *St = cast<StoreSDNode>(N);
9660   if (St->isVolatile())
9661     return SDValue();
9662
9663   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9664   // pack all of the elements in one place.  Next, store to memory in fewer
9665   // chunks.
9666   SDValue StVal = St->getValue();
9667   EVT VT = StVal.getValueType();
9668   if (St->isTruncatingStore() && VT.isVector()) {
9669     SelectionDAG &DAG = DCI.DAG;
9670     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9671     EVT StVT = St->getMemoryVT();
9672     unsigned NumElems = VT.getVectorNumElements();
9673     assert(StVT != VT && "Cannot truncate to the same type");
9674     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9675     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9676
9677     // From, To sizes and ElemCount must be pow of two
9678     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9679
9680     // We are going to use the original vector elt for storing.
9681     // Accumulated smaller vector elements must be a multiple of the store size.
9682     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9683
9684     unsigned SizeRatio  = FromEltSz / ToEltSz;
9685     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9686
9687     // Create a type on which we perform the shuffle.
9688     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9689                                      NumElems*SizeRatio);
9690     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9691
9692     SDLoc DL(St);
9693     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9694     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9695     for (unsigned i = 0; i < NumElems; ++i)
9696       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9697                           ? (i + 1) * SizeRatio - 1
9698                           : i * SizeRatio;
9699
9700     // Can't shuffle using an illegal type.
9701     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9702
9703     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9704                                 DAG.getUNDEF(WideVec.getValueType()),
9705                                 ShuffleVec.data());
9706     // At this point all of the data is stored at the bottom of the
9707     // register. We now need to save it to mem.
9708
9709     // Find the largest store unit
9710     MVT StoreType = MVT::i8;
9711     for (MVT Tp : MVT::integer_valuetypes()) {
9712       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9713         StoreType = Tp;
9714     }
9715     // Didn't find a legal store type.
9716     if (!TLI.isTypeLegal(StoreType))
9717       return SDValue();
9718
9719     // Bitcast the original vector into a vector of store-size units
9720     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9721             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9722     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9723     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9724     SmallVector<SDValue, 8> Chains;
9725     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9726                                         TLI.getPointerTy(DAG.getDataLayout()));
9727     SDValue BasePtr = St->getBasePtr();
9728
9729     // Perform one or more big stores into memory.
9730     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9731     for (unsigned I = 0; I < E; I++) {
9732       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9733                                    StoreType, ShuffWide,
9734                                    DAG.getIntPtrConstant(I, DL));
9735       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9736                                 St->getPointerInfo(), St->isVolatile(),
9737                                 St->isNonTemporal(), St->getAlignment());
9738       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9739                             Increment);
9740       Chains.push_back(Ch);
9741     }
9742     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9743   }
9744
9745   if (!ISD::isNormalStore(St))
9746     return SDValue();
9747
9748   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9749   // ARM stores of arguments in the same cache line.
9750   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9751       StVal.getNode()->hasOneUse()) {
9752     SelectionDAG  &DAG = DCI.DAG;
9753     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9754     SDLoc DL(St);
9755     SDValue BasePtr = St->getBasePtr();
9756     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9757                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9758                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9759                                   St->isNonTemporal(), St->getAlignment());
9760
9761     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9762                                     DAG.getConstant(4, DL, MVT::i32));
9763     return DAG.getStore(NewST1.getValue(0), DL,
9764                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9765                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9766                         St->isNonTemporal(),
9767                         std::min(4U, St->getAlignment() / 2));
9768   }
9769
9770   if (StVal.getValueType() == MVT::i64 &&
9771       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9772
9773     // Bitcast an i64 store extracted from a vector to f64.
9774     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9775     SelectionDAG &DAG = DCI.DAG;
9776     SDLoc dl(StVal);
9777     SDValue IntVec = StVal.getOperand(0);
9778     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9779                                    IntVec.getValueType().getVectorNumElements());
9780     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9781     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9782                                  Vec, StVal.getOperand(1));
9783     dl = SDLoc(N);
9784     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9785     // Make the DAGCombiner fold the bitcasts.
9786     DCI.AddToWorklist(Vec.getNode());
9787     DCI.AddToWorklist(ExtElt.getNode());
9788     DCI.AddToWorklist(V.getNode());
9789     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9790                         St->getPointerInfo(), St->isVolatile(),
9791                         St->isNonTemporal(), St->getAlignment(),
9792                         St->getAAInfo());
9793   }
9794
9795   // If this is a legal vector store, try to combine it into a VST1_UPD.
9796   if (ISD::isNormalStore(N) && VT.isVector() &&
9797       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9798     return CombineBaseUpdate(N, DCI);
9799
9800   return SDValue();
9801 }
9802
9803 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9804 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9805 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9806 {
9807   integerPart cN;
9808   integerPart c0 = 0;
9809   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9810        I != E; I++) {
9811     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9812     if (!C)
9813       return false;
9814
9815     bool isExact;
9816     APFloat APF = C->getValueAPF();
9817     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9818         != APFloat::opOK || !isExact)
9819       return false;
9820
9821     c0 = (I == 0) ? cN : c0;
9822     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9823       return false;
9824   }
9825   C = c0;
9826   return true;
9827 }
9828
9829 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9830 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9831 /// when the VMUL has a constant operand that is a power of 2.
9832 ///
9833 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9834 ///  vmul.f32        d16, d17, d16
9835 ///  vcvt.s32.f32    d16, d16
9836 /// becomes:
9837 ///  vcvt.s32.f32    d16, d16, #3
9838 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
9839                                   const ARMSubtarget *Subtarget) {
9840   if (!Subtarget->hasNEON())
9841     return SDValue();
9842
9843   SDValue Op = N->getOperand(0);
9844   if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
9845     return SDValue();
9846
9847   uint64_t C;
9848   SDValue ConstVec = Op->getOperand(1);
9849   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9850
9851   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9852       !isConstVecPow2(ConstVec, isSigned, C))
9853     return SDValue();
9854
9855   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9856   uint32_t FloatBits = FloatTy.getSizeInBits();
9857   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9858   uint32_t IntBits = IntTy.getSizeInBits();
9859   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9860   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
9861     // These instructions only exist converting from f32 to i32. We can handle
9862     // smaller integers by generating an extra truncate, but larger ones would
9863     // be lossy. We also can't handle more then 4 lanes, since these intructions
9864     // only support v2i32/v4i32 types.
9865     return SDValue();
9866   }
9867
9868   SDLoc dl(N);
9869   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9870     Intrinsic::arm_neon_vcvtfp2fxu;
9871   SDValue FixConv = DAG.getNode(
9872       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9873       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
9874       DAG.getConstant(Log2_64(C), dl, MVT::i32));
9875
9876   if (IntBits < FloatBits)
9877     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9878
9879   return FixConv;
9880 }
9881
9882 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9883 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9884 /// when the VDIV has a constant operand that is a power of 2.
9885 ///
9886 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9887 ///  vcvt.f32.s32    d16, d16
9888 ///  vdiv.f32        d16, d17, d16
9889 /// becomes:
9890 ///  vcvt.f32.s32    d16, d16, #3
9891 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
9892                                   const ARMSubtarget *Subtarget) {
9893   if (!Subtarget->hasNEON())
9894     return SDValue();
9895
9896   SDValue Op = N->getOperand(0);
9897   unsigned OpOpcode = Op.getNode()->getOpcode();
9898   if (!N->getValueType(0).isVector() ||
9899       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9900     return SDValue();
9901
9902   uint64_t C;
9903   SDValue ConstVec = N->getOperand(1);
9904   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9905
9906   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9907       !isConstVecPow2(ConstVec, isSigned, C))
9908     return SDValue();
9909
9910   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9911   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9912   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9913     // These instructions only exist converting from i32 to f32. We can handle
9914     // smaller integers by generating an extra extend, but larger ones would
9915     // be lossy.
9916     return SDValue();
9917   }
9918
9919   SDLoc dl(N);
9920   SDValue ConvInput = Op.getOperand(0);
9921   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9922   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9923     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9924                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9925                             ConvInput);
9926
9927   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9928     Intrinsic::arm_neon_vcvtfxu2fp;
9929   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9930                      Op.getValueType(),
9931                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9932                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9933 }
9934
9935 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9936 /// operand of a vector shift operation, where all the elements of the
9937 /// build_vector must have the same constant integer value.
9938 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9939   // Ignore bit_converts.
9940   while (Op.getOpcode() == ISD::BITCAST)
9941     Op = Op.getOperand(0);
9942   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9943   APInt SplatBits, SplatUndef;
9944   unsigned SplatBitSize;
9945   bool HasAnyUndefs;
9946   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9947                                       HasAnyUndefs, ElementBits) ||
9948       SplatBitSize > ElementBits)
9949     return false;
9950   Cnt = SplatBits.getSExtValue();
9951   return true;
9952 }
9953
9954 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9955 /// operand of a vector shift left operation.  That value must be in the range:
9956 ///   0 <= Value < ElementBits for a left shift; or
9957 ///   0 <= Value <= ElementBits for a long left shift.
9958 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9959   assert(VT.isVector() && "vector shift count is not a vector type");
9960   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9961   if (! getVShiftImm(Op, ElementBits, Cnt))
9962     return false;
9963   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9964 }
9965
9966 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9967 /// operand of a vector shift right operation.  For a shift opcode, the value
9968 /// is positive, but for an intrinsic the value count must be negative. The
9969 /// absolute value must be in the range:
9970 ///   1 <= |Value| <= ElementBits for a right shift; or
9971 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9972 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9973                          int64_t &Cnt) {
9974   assert(VT.isVector() && "vector shift count is not a vector type");
9975   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9976   if (! getVShiftImm(Op, ElementBits, Cnt))
9977     return false;
9978   if (!isIntrinsic)
9979     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9980   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9981     Cnt = -Cnt;
9982     return true;
9983   }
9984   return false;
9985 }
9986
9987 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9988 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9989   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9990   switch (IntNo) {
9991   default:
9992     // Don't do anything for most intrinsics.
9993     break;
9994
9995   case Intrinsic::arm_neon_vabds:
9996     if (!N->getValueType(0).isInteger())
9997       return SDValue();
9998     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9999                        N->getOperand(1), N->getOperand(2));
10000   case Intrinsic::arm_neon_vabdu:
10001     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
10002                        N->getOperand(1), N->getOperand(2));
10003
10004   // Vector shifts: check for immediate versions and lower them.
10005   // Note: This is done during DAG combining instead of DAG legalizing because
10006   // the build_vectors for 64-bit vector element shift counts are generally
10007   // not legal, and it is hard to see their values after they get legalized to
10008   // loads from a constant pool.
10009   case Intrinsic::arm_neon_vshifts:
10010   case Intrinsic::arm_neon_vshiftu:
10011   case Intrinsic::arm_neon_vrshifts:
10012   case Intrinsic::arm_neon_vrshiftu:
10013   case Intrinsic::arm_neon_vrshiftn:
10014   case Intrinsic::arm_neon_vqshifts:
10015   case Intrinsic::arm_neon_vqshiftu:
10016   case Intrinsic::arm_neon_vqshiftsu:
10017   case Intrinsic::arm_neon_vqshiftns:
10018   case Intrinsic::arm_neon_vqshiftnu:
10019   case Intrinsic::arm_neon_vqshiftnsu:
10020   case Intrinsic::arm_neon_vqrshiftns:
10021   case Intrinsic::arm_neon_vqrshiftnu:
10022   case Intrinsic::arm_neon_vqrshiftnsu: {
10023     EVT VT = N->getOperand(1).getValueType();
10024     int64_t Cnt;
10025     unsigned VShiftOpc = 0;
10026
10027     switch (IntNo) {
10028     case Intrinsic::arm_neon_vshifts:
10029     case Intrinsic::arm_neon_vshiftu:
10030       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10031         VShiftOpc = ARMISD::VSHL;
10032         break;
10033       }
10034       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10035         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10036                      ARMISD::VSHRs : ARMISD::VSHRu);
10037         break;
10038       }
10039       return SDValue();
10040
10041     case Intrinsic::arm_neon_vrshifts:
10042     case Intrinsic::arm_neon_vrshiftu:
10043       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10044         break;
10045       return SDValue();
10046
10047     case Intrinsic::arm_neon_vqshifts:
10048     case Intrinsic::arm_neon_vqshiftu:
10049       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10050         break;
10051       return SDValue();
10052
10053     case Intrinsic::arm_neon_vqshiftsu:
10054       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10055         break;
10056       llvm_unreachable("invalid shift count for vqshlu intrinsic");
10057
10058     case Intrinsic::arm_neon_vrshiftn:
10059     case Intrinsic::arm_neon_vqshiftns:
10060     case Intrinsic::arm_neon_vqshiftnu:
10061     case Intrinsic::arm_neon_vqshiftnsu:
10062     case Intrinsic::arm_neon_vqrshiftns:
10063     case Intrinsic::arm_neon_vqrshiftnu:
10064     case Intrinsic::arm_neon_vqrshiftnsu:
10065       // Narrowing shifts require an immediate right shift.
10066       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10067         break;
10068       llvm_unreachable("invalid shift count for narrowing vector shift "
10069                        "intrinsic");
10070
10071     default:
10072       llvm_unreachable("unhandled vector shift");
10073     }
10074
10075     switch (IntNo) {
10076     case Intrinsic::arm_neon_vshifts:
10077     case Intrinsic::arm_neon_vshiftu:
10078       // Opcode already set above.
10079       break;
10080     case Intrinsic::arm_neon_vrshifts:
10081       VShiftOpc = ARMISD::VRSHRs; break;
10082     case Intrinsic::arm_neon_vrshiftu:
10083       VShiftOpc = ARMISD::VRSHRu; break;
10084     case Intrinsic::arm_neon_vrshiftn:
10085       VShiftOpc = ARMISD::VRSHRN; break;
10086     case Intrinsic::arm_neon_vqshifts:
10087       VShiftOpc = ARMISD::VQSHLs; break;
10088     case Intrinsic::arm_neon_vqshiftu:
10089       VShiftOpc = ARMISD::VQSHLu; break;
10090     case Intrinsic::arm_neon_vqshiftsu:
10091       VShiftOpc = ARMISD::VQSHLsu; break;
10092     case Intrinsic::arm_neon_vqshiftns:
10093       VShiftOpc = ARMISD::VQSHRNs; break;
10094     case Intrinsic::arm_neon_vqshiftnu:
10095       VShiftOpc = ARMISD::VQSHRNu; break;
10096     case Intrinsic::arm_neon_vqshiftnsu:
10097       VShiftOpc = ARMISD::VQSHRNsu; break;
10098     case Intrinsic::arm_neon_vqrshiftns:
10099       VShiftOpc = ARMISD::VQRSHRNs; break;
10100     case Intrinsic::arm_neon_vqrshiftnu:
10101       VShiftOpc = ARMISD::VQRSHRNu; break;
10102     case Intrinsic::arm_neon_vqrshiftnsu:
10103       VShiftOpc = ARMISD::VQRSHRNsu; break;
10104     }
10105
10106     SDLoc dl(N);
10107     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10108                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10109   }
10110
10111   case Intrinsic::arm_neon_vshiftins: {
10112     EVT VT = N->getOperand(1).getValueType();
10113     int64_t Cnt;
10114     unsigned VShiftOpc = 0;
10115
10116     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10117       VShiftOpc = ARMISD::VSLI;
10118     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10119       VShiftOpc = ARMISD::VSRI;
10120     else {
10121       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10122     }
10123
10124     SDLoc dl(N);
10125     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10126                        N->getOperand(1), N->getOperand(2),
10127                        DAG.getConstant(Cnt, dl, MVT::i32));
10128   }
10129
10130   case Intrinsic::arm_neon_vqrshifts:
10131   case Intrinsic::arm_neon_vqrshiftu:
10132     // No immediate versions of these to check for.
10133     break;
10134   }
10135
10136   return SDValue();
10137 }
10138
10139 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10140 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
10141 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10142 /// vector element shift counts are generally not legal, and it is hard to see
10143 /// their values after they get legalized to loads from a constant pool.
10144 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10145                                    const ARMSubtarget *ST) {
10146   EVT VT = N->getValueType(0);
10147   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10148     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10149     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10150     SDValue N1 = N->getOperand(1);
10151     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10152       SDValue N0 = N->getOperand(0);
10153       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10154           DAG.MaskedValueIsZero(N0.getOperand(0),
10155                                 APInt::getHighBitsSet(32, 16)))
10156         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10157     }
10158   }
10159
10160   // Nothing to be done for scalar shifts.
10161   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10162   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10163     return SDValue();
10164
10165   assert(ST->hasNEON() && "unexpected vector shift");
10166   int64_t Cnt;
10167
10168   switch (N->getOpcode()) {
10169   default: llvm_unreachable("unexpected shift opcode");
10170
10171   case ISD::SHL:
10172     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10173       SDLoc dl(N);
10174       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10175                          DAG.getConstant(Cnt, dl, MVT::i32));
10176     }
10177     break;
10178
10179   case ISD::SRA:
10180   case ISD::SRL:
10181     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10182       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10183                             ARMISD::VSHRs : ARMISD::VSHRu);
10184       SDLoc dl(N);
10185       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10186                          DAG.getConstant(Cnt, dl, MVT::i32));
10187     }
10188   }
10189   return SDValue();
10190 }
10191
10192 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10193 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10194 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10195                                     const ARMSubtarget *ST) {
10196   SDValue N0 = N->getOperand(0);
10197
10198   // Check for sign- and zero-extensions of vector extract operations of 8-
10199   // and 16-bit vector elements.  NEON supports these directly.  They are
10200   // handled during DAG combining because type legalization will promote them
10201   // to 32-bit types and it is messy to recognize the operations after that.
10202   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10203     SDValue Vec = N0.getOperand(0);
10204     SDValue Lane = N0.getOperand(1);
10205     EVT VT = N->getValueType(0);
10206     EVT EltVT = N0.getValueType();
10207     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10208
10209     if (VT == MVT::i32 &&
10210         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10211         TLI.isTypeLegal(Vec.getValueType()) &&
10212         isa<ConstantSDNode>(Lane)) {
10213
10214       unsigned Opc = 0;
10215       switch (N->getOpcode()) {
10216       default: llvm_unreachable("unexpected opcode");
10217       case ISD::SIGN_EXTEND:
10218         Opc = ARMISD::VGETLANEs;
10219         break;
10220       case ISD::ZERO_EXTEND:
10221       case ISD::ANY_EXTEND:
10222         Opc = ARMISD::VGETLANEu;
10223         break;
10224       }
10225       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10226     }
10227   }
10228
10229   return SDValue();
10230 }
10231
10232 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10233 SDValue
10234 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10235   SDValue Cmp = N->getOperand(4);
10236   if (Cmp.getOpcode() != ARMISD::CMPZ)
10237     // Only looking at EQ and NE cases.
10238     return SDValue();
10239
10240   EVT VT = N->getValueType(0);
10241   SDLoc dl(N);
10242   SDValue LHS = Cmp.getOperand(0);
10243   SDValue RHS = Cmp.getOperand(1);
10244   SDValue FalseVal = N->getOperand(0);
10245   SDValue TrueVal = N->getOperand(1);
10246   SDValue ARMcc = N->getOperand(2);
10247   ARMCC::CondCodes CC =
10248     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10249
10250   // Simplify
10251   //   mov     r1, r0
10252   //   cmp     r1, x
10253   //   mov     r0, y
10254   //   moveq   r0, x
10255   // to
10256   //   cmp     r0, x
10257   //   movne   r0, y
10258   //
10259   //   mov     r1, r0
10260   //   cmp     r1, x
10261   //   mov     r0, x
10262   //   movne   r0, y
10263   // to
10264   //   cmp     r0, x
10265   //   movne   r0, y
10266   /// FIXME: Turn this into a target neutral optimization?
10267   SDValue Res;
10268   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10269     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10270                       N->getOperand(3), Cmp);
10271   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10272     SDValue ARMcc;
10273     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10274     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10275                       N->getOperand(3), NewCmp);
10276   }
10277
10278   if (Res.getNode()) {
10279     APInt KnownZero, KnownOne;
10280     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10281     // Capture demanded bits information that would be otherwise lost.
10282     if (KnownZero == 0xfffffffe)
10283       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10284                         DAG.getValueType(MVT::i1));
10285     else if (KnownZero == 0xffffff00)
10286       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10287                         DAG.getValueType(MVT::i8));
10288     else if (KnownZero == 0xffff0000)
10289       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10290                         DAG.getValueType(MVT::i16));
10291   }
10292
10293   return Res;
10294 }
10295
10296 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10297                                              DAGCombinerInfo &DCI) const {
10298   switch (N->getOpcode()) {
10299   default: break;
10300   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10301   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10302   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10303   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10304   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10305   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10306   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10307   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10308   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10309   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10310   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10311   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10312   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10313   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10314   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10315   case ISD::FP_TO_SINT:
10316   case ISD::FP_TO_UINT:
10317     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
10318   case ISD::FDIV:
10319     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
10320   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10321   case ISD::SHL:
10322   case ISD::SRA:
10323   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10324   case ISD::SIGN_EXTEND:
10325   case ISD::ZERO_EXTEND:
10326   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10327   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10328   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10329   case ARMISD::VLD2DUP:
10330   case ARMISD::VLD3DUP:
10331   case ARMISD::VLD4DUP:
10332     return PerformVLDCombine(N, DCI);
10333   case ARMISD::BUILD_VECTOR:
10334     return PerformARMBUILD_VECTORCombine(N, DCI);
10335   case ISD::INTRINSIC_VOID:
10336   case ISD::INTRINSIC_W_CHAIN:
10337     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10338     case Intrinsic::arm_neon_vld1:
10339     case Intrinsic::arm_neon_vld2:
10340     case Intrinsic::arm_neon_vld3:
10341     case Intrinsic::arm_neon_vld4:
10342     case Intrinsic::arm_neon_vld2lane:
10343     case Intrinsic::arm_neon_vld3lane:
10344     case Intrinsic::arm_neon_vld4lane:
10345     case Intrinsic::arm_neon_vst1:
10346     case Intrinsic::arm_neon_vst2:
10347     case Intrinsic::arm_neon_vst3:
10348     case Intrinsic::arm_neon_vst4:
10349     case Intrinsic::arm_neon_vst2lane:
10350     case Intrinsic::arm_neon_vst3lane:
10351     case Intrinsic::arm_neon_vst4lane:
10352       return PerformVLDCombine(N, DCI);
10353     default: break;
10354     }
10355     break;
10356   }
10357   return SDValue();
10358 }
10359
10360 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10361                                                           EVT VT) const {
10362   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10363 }
10364
10365 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10366                                                        unsigned,
10367                                                        unsigned,
10368                                                        bool *Fast) const {
10369   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10370   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10371
10372   switch (VT.getSimpleVT().SimpleTy) {
10373   default:
10374     return false;
10375   case MVT::i8:
10376   case MVT::i16:
10377   case MVT::i32: {
10378     // Unaligned access can use (for example) LRDB, LRDH, LDR
10379     if (AllowsUnaligned) {
10380       if (Fast)
10381         *Fast = Subtarget->hasV7Ops();
10382       return true;
10383     }
10384     return false;
10385   }
10386   case MVT::f64:
10387   case MVT::v2f64: {
10388     // For any little-endian targets with neon, we can support unaligned ld/st
10389     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10390     // A big-endian target may also explicitly support unaligned accesses
10391     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10392       if (Fast)
10393         *Fast = true;
10394       return true;
10395     }
10396     return false;
10397   }
10398   }
10399 }
10400
10401 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10402                        unsigned AlignCheck) {
10403   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10404           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10405 }
10406
10407 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10408                                            unsigned DstAlign, unsigned SrcAlign,
10409                                            bool IsMemset, bool ZeroMemset,
10410                                            bool MemcpyStrSrc,
10411                                            MachineFunction &MF) const {
10412   const Function *F = MF.getFunction();
10413
10414   // See if we can use NEON instructions for this...
10415   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10416       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10417     bool Fast;
10418     if (Size >= 16 &&
10419         (memOpAlign(SrcAlign, DstAlign, 16) ||
10420          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10421       return MVT::v2f64;
10422     } else if (Size >= 8 &&
10423                (memOpAlign(SrcAlign, DstAlign, 8) ||
10424                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10425                  Fast))) {
10426       return MVT::f64;
10427     }
10428   }
10429
10430   // Lowering to i32/i16 if the size permits.
10431   if (Size >= 4)
10432     return MVT::i32;
10433   else if (Size >= 2)
10434     return MVT::i16;
10435
10436   // Let the target-independent logic figure it out.
10437   return MVT::Other;
10438 }
10439
10440 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10441   if (Val.getOpcode() != ISD::LOAD)
10442     return false;
10443
10444   EVT VT1 = Val.getValueType();
10445   if (!VT1.isSimple() || !VT1.isInteger() ||
10446       !VT2.isSimple() || !VT2.isInteger())
10447     return false;
10448
10449   switch (VT1.getSimpleVT().SimpleTy) {
10450   default: break;
10451   case MVT::i1:
10452   case MVT::i8:
10453   case MVT::i16:
10454     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10455     return true;
10456   }
10457
10458   return false;
10459 }
10460
10461 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10462   EVT VT = ExtVal.getValueType();
10463
10464   if (!isTypeLegal(VT))
10465     return false;
10466
10467   // Don't create a loadext if we can fold the extension into a wide/long
10468   // instruction.
10469   // If there's more than one user instruction, the loadext is desirable no
10470   // matter what.  There can be two uses by the same instruction.
10471   if (ExtVal->use_empty() ||
10472       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10473     return true;
10474
10475   SDNode *U = *ExtVal->use_begin();
10476   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10477        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10478     return false;
10479
10480   return true;
10481 }
10482
10483 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10484   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10485     return false;
10486
10487   if (!isTypeLegal(EVT::getEVT(Ty1)))
10488     return false;
10489
10490   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10491
10492   // Assuming the caller doesn't have a zeroext or signext return parameter,
10493   // truncation all the way down to i1 is valid.
10494   return true;
10495 }
10496
10497
10498 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10499   if (V < 0)
10500     return false;
10501
10502   unsigned Scale = 1;
10503   switch (VT.getSimpleVT().SimpleTy) {
10504   default: return false;
10505   case MVT::i1:
10506   case MVT::i8:
10507     // Scale == 1;
10508     break;
10509   case MVT::i16:
10510     // Scale == 2;
10511     Scale = 2;
10512     break;
10513   case MVT::i32:
10514     // Scale == 4;
10515     Scale = 4;
10516     break;
10517   }
10518
10519   if ((V & (Scale - 1)) != 0)
10520     return false;
10521   V /= Scale;
10522   return V == (V & ((1LL << 5) - 1));
10523 }
10524
10525 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10526                                       const ARMSubtarget *Subtarget) {
10527   bool isNeg = false;
10528   if (V < 0) {
10529     isNeg = true;
10530     V = - V;
10531   }
10532
10533   switch (VT.getSimpleVT().SimpleTy) {
10534   default: return false;
10535   case MVT::i1:
10536   case MVT::i8:
10537   case MVT::i16:
10538   case MVT::i32:
10539     // + imm12 or - imm8
10540     if (isNeg)
10541       return V == (V & ((1LL << 8) - 1));
10542     return V == (V & ((1LL << 12) - 1));
10543   case MVT::f32:
10544   case MVT::f64:
10545     // Same as ARM mode. FIXME: NEON?
10546     if (!Subtarget->hasVFP2())
10547       return false;
10548     if ((V & 3) != 0)
10549       return false;
10550     V >>= 2;
10551     return V == (V & ((1LL << 8) - 1));
10552   }
10553 }
10554
10555 /// isLegalAddressImmediate - Return true if the integer value can be used
10556 /// as the offset of the target addressing mode for load / store of the
10557 /// given type.
10558 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10559                                     const ARMSubtarget *Subtarget) {
10560   if (V == 0)
10561     return true;
10562
10563   if (!VT.isSimple())
10564     return false;
10565
10566   if (Subtarget->isThumb1Only())
10567     return isLegalT1AddressImmediate(V, VT);
10568   else if (Subtarget->isThumb2())
10569     return isLegalT2AddressImmediate(V, VT, Subtarget);
10570
10571   // ARM mode.
10572   if (V < 0)
10573     V = - V;
10574   switch (VT.getSimpleVT().SimpleTy) {
10575   default: return false;
10576   case MVT::i1:
10577   case MVT::i8:
10578   case MVT::i32:
10579     // +- imm12
10580     return V == (V & ((1LL << 12) - 1));
10581   case MVT::i16:
10582     // +- imm8
10583     return V == (V & ((1LL << 8) - 1));
10584   case MVT::f32:
10585   case MVT::f64:
10586     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10587       return false;
10588     if ((V & 3) != 0)
10589       return false;
10590     V >>= 2;
10591     return V == (V & ((1LL << 8) - 1));
10592   }
10593 }
10594
10595 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10596                                                       EVT VT) const {
10597   int Scale = AM.Scale;
10598   if (Scale < 0)
10599     return false;
10600
10601   switch (VT.getSimpleVT().SimpleTy) {
10602   default: return false;
10603   case MVT::i1:
10604   case MVT::i8:
10605   case MVT::i16:
10606   case MVT::i32:
10607     if (Scale == 1)
10608       return true;
10609     // r + r << imm
10610     Scale = Scale & ~1;
10611     return Scale == 2 || Scale == 4 || Scale == 8;
10612   case MVT::i64:
10613     // r + r
10614     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10615       return true;
10616     return false;
10617   case MVT::isVoid:
10618     // Note, we allow "void" uses (basically, uses that aren't loads or
10619     // stores), because arm allows folding a scale into many arithmetic
10620     // operations.  This should be made more precise and revisited later.
10621
10622     // Allow r << imm, but the imm has to be a multiple of two.
10623     if (Scale & 1) return false;
10624     return isPowerOf2_32(Scale);
10625   }
10626 }
10627
10628 /// isLegalAddressingMode - Return true if the addressing mode represented
10629 /// by AM is legal for this target, for a load/store of the specified type.
10630 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10631                                               const AddrMode &AM, Type *Ty,
10632                                               unsigned AS) const {
10633   EVT VT = getValueType(DL, Ty, true);
10634   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10635     return false;
10636
10637   // Can never fold addr of global into load/store.
10638   if (AM.BaseGV)
10639     return false;
10640
10641   switch (AM.Scale) {
10642   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10643     break;
10644   case 1:
10645     if (Subtarget->isThumb1Only())
10646       return false;
10647     // FALL THROUGH.
10648   default:
10649     // ARM doesn't support any R+R*scale+imm addr modes.
10650     if (AM.BaseOffs)
10651       return false;
10652
10653     if (!VT.isSimple())
10654       return false;
10655
10656     if (Subtarget->isThumb2())
10657       return isLegalT2ScaledAddressingMode(AM, VT);
10658
10659     int Scale = AM.Scale;
10660     switch (VT.getSimpleVT().SimpleTy) {
10661     default: return false;
10662     case MVT::i1:
10663     case MVT::i8:
10664     case MVT::i32:
10665       if (Scale < 0) Scale = -Scale;
10666       if (Scale == 1)
10667         return true;
10668       // r + r << imm
10669       return isPowerOf2_32(Scale & ~1);
10670     case MVT::i16:
10671     case MVT::i64:
10672       // r + r
10673       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10674         return true;
10675       return false;
10676
10677     case MVT::isVoid:
10678       // Note, we allow "void" uses (basically, uses that aren't loads or
10679       // stores), because arm allows folding a scale into many arithmetic
10680       // operations.  This should be made more precise and revisited later.
10681
10682       // Allow r << imm, but the imm has to be a multiple of two.
10683       if (Scale & 1) return false;
10684       return isPowerOf2_32(Scale);
10685     }
10686   }
10687   return true;
10688 }
10689
10690 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10691 /// icmp immediate, that is the target has icmp instructions which can compare
10692 /// a register against the immediate without having to materialize the
10693 /// immediate into a register.
10694 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10695   // Thumb2 and ARM modes can use cmn for negative immediates.
10696   if (!Subtarget->isThumb())
10697     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10698   if (Subtarget->isThumb2())
10699     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10700   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10701   return Imm >= 0 && Imm <= 255;
10702 }
10703
10704 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10705 /// *or sub* immediate, that is the target has add or sub instructions which can
10706 /// add a register with the immediate without having to materialize the
10707 /// immediate into a register.
10708 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10709   // Same encoding for add/sub, just flip the sign.
10710   int64_t AbsImm = std::abs(Imm);
10711   if (!Subtarget->isThumb())
10712     return ARM_AM::getSOImmVal(AbsImm) != -1;
10713   if (Subtarget->isThumb2())
10714     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10715   // Thumb1 only has 8-bit unsigned immediate.
10716   return AbsImm >= 0 && AbsImm <= 255;
10717 }
10718
10719 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10720                                       bool isSEXTLoad, SDValue &Base,
10721                                       SDValue &Offset, bool &isInc,
10722                                       SelectionDAG &DAG) {
10723   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10724     return false;
10725
10726   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10727     // AddressingMode 3
10728     Base = Ptr->getOperand(0);
10729     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10730       int RHSC = (int)RHS->getZExtValue();
10731       if (RHSC < 0 && RHSC > -256) {
10732         assert(Ptr->getOpcode() == ISD::ADD);
10733         isInc = false;
10734         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10735         return true;
10736       }
10737     }
10738     isInc = (Ptr->getOpcode() == ISD::ADD);
10739     Offset = Ptr->getOperand(1);
10740     return true;
10741   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10742     // AddressingMode 2
10743     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10744       int RHSC = (int)RHS->getZExtValue();
10745       if (RHSC < 0 && RHSC > -0x1000) {
10746         assert(Ptr->getOpcode() == ISD::ADD);
10747         isInc = false;
10748         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10749         Base = Ptr->getOperand(0);
10750         return true;
10751       }
10752     }
10753
10754     if (Ptr->getOpcode() == ISD::ADD) {
10755       isInc = true;
10756       ARM_AM::ShiftOpc ShOpcVal=
10757         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10758       if (ShOpcVal != ARM_AM::no_shift) {
10759         Base = Ptr->getOperand(1);
10760         Offset = Ptr->getOperand(0);
10761       } else {
10762         Base = Ptr->getOperand(0);
10763         Offset = Ptr->getOperand(1);
10764       }
10765       return true;
10766     }
10767
10768     isInc = (Ptr->getOpcode() == ISD::ADD);
10769     Base = Ptr->getOperand(0);
10770     Offset = Ptr->getOperand(1);
10771     return true;
10772   }
10773
10774   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10775   return false;
10776 }
10777
10778 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10779                                      bool isSEXTLoad, SDValue &Base,
10780                                      SDValue &Offset, bool &isInc,
10781                                      SelectionDAG &DAG) {
10782   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10783     return false;
10784
10785   Base = Ptr->getOperand(0);
10786   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10787     int RHSC = (int)RHS->getZExtValue();
10788     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10789       assert(Ptr->getOpcode() == ISD::ADD);
10790       isInc = false;
10791       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10792       return true;
10793     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10794       isInc = Ptr->getOpcode() == ISD::ADD;
10795       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10796       return true;
10797     }
10798   }
10799
10800   return false;
10801 }
10802
10803 /// getPreIndexedAddressParts - returns true by value, base pointer and
10804 /// offset pointer and addressing mode by reference if the node's address
10805 /// can be legally represented as pre-indexed load / store address.
10806 bool
10807 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10808                                              SDValue &Offset,
10809                                              ISD::MemIndexedMode &AM,
10810                                              SelectionDAG &DAG) const {
10811   if (Subtarget->isThumb1Only())
10812     return false;
10813
10814   EVT VT;
10815   SDValue Ptr;
10816   bool isSEXTLoad = false;
10817   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10818     Ptr = LD->getBasePtr();
10819     VT  = LD->getMemoryVT();
10820     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10821   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10822     Ptr = ST->getBasePtr();
10823     VT  = ST->getMemoryVT();
10824   } else
10825     return false;
10826
10827   bool isInc;
10828   bool isLegal = false;
10829   if (Subtarget->isThumb2())
10830     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10831                                        Offset, isInc, DAG);
10832   else
10833     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10834                                         Offset, isInc, DAG);
10835   if (!isLegal)
10836     return false;
10837
10838   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10839   return true;
10840 }
10841
10842 /// getPostIndexedAddressParts - returns true by value, base pointer and
10843 /// offset pointer and addressing mode by reference if this node can be
10844 /// combined with a load / store to form a post-indexed load / store.
10845 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10846                                                    SDValue &Base,
10847                                                    SDValue &Offset,
10848                                                    ISD::MemIndexedMode &AM,
10849                                                    SelectionDAG &DAG) const {
10850   if (Subtarget->isThumb1Only())
10851     return false;
10852
10853   EVT VT;
10854   SDValue Ptr;
10855   bool isSEXTLoad = false;
10856   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10857     VT  = LD->getMemoryVT();
10858     Ptr = LD->getBasePtr();
10859     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10860   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10861     VT  = ST->getMemoryVT();
10862     Ptr = ST->getBasePtr();
10863   } else
10864     return false;
10865
10866   bool isInc;
10867   bool isLegal = false;
10868   if (Subtarget->isThumb2())
10869     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10870                                        isInc, DAG);
10871   else
10872     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10873                                         isInc, DAG);
10874   if (!isLegal)
10875     return false;
10876
10877   if (Ptr != Base) {
10878     // Swap base ptr and offset to catch more post-index load / store when
10879     // it's legal. In Thumb2 mode, offset must be an immediate.
10880     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10881         !Subtarget->isThumb2())
10882       std::swap(Base, Offset);
10883
10884     // Post-indexed load / store update the base pointer.
10885     if (Ptr != Base)
10886       return false;
10887   }
10888
10889   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10890   return true;
10891 }
10892
10893 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10894                                                       APInt &KnownZero,
10895                                                       APInt &KnownOne,
10896                                                       const SelectionDAG &DAG,
10897                                                       unsigned Depth) const {
10898   unsigned BitWidth = KnownOne.getBitWidth();
10899   KnownZero = KnownOne = APInt(BitWidth, 0);
10900   switch (Op.getOpcode()) {
10901   default: break;
10902   case ARMISD::ADDC:
10903   case ARMISD::ADDE:
10904   case ARMISD::SUBC:
10905   case ARMISD::SUBE:
10906     // These nodes' second result is a boolean
10907     if (Op.getResNo() == 0)
10908       break;
10909     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10910     break;
10911   case ARMISD::CMOV: {
10912     // Bits are known zero/one if known on the LHS and RHS.
10913     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10914     if (KnownZero == 0 && KnownOne == 0) return;
10915
10916     APInt KnownZeroRHS, KnownOneRHS;
10917     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10918     KnownZero &= KnownZeroRHS;
10919     KnownOne  &= KnownOneRHS;
10920     return;
10921   }
10922   case ISD::INTRINSIC_W_CHAIN: {
10923     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10924     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10925     switch (IntID) {
10926     default: return;
10927     case Intrinsic::arm_ldaex:
10928     case Intrinsic::arm_ldrex: {
10929       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10930       unsigned MemBits = VT.getScalarType().getSizeInBits();
10931       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10932       return;
10933     }
10934     }
10935   }
10936   }
10937 }
10938
10939 //===----------------------------------------------------------------------===//
10940 //                           ARM Inline Assembly Support
10941 //===----------------------------------------------------------------------===//
10942
10943 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10944   // Looking for "rev" which is V6+.
10945   if (!Subtarget->hasV6Ops())
10946     return false;
10947
10948   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10949   std::string AsmStr = IA->getAsmString();
10950   SmallVector<StringRef, 4> AsmPieces;
10951   SplitString(AsmStr, AsmPieces, ";\n");
10952
10953   switch (AsmPieces.size()) {
10954   default: return false;
10955   case 1:
10956     AsmStr = AsmPieces[0];
10957     AsmPieces.clear();
10958     SplitString(AsmStr, AsmPieces, " \t,");
10959
10960     // rev $0, $1
10961     if (AsmPieces.size() == 3 &&
10962         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10963         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10964       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10965       if (Ty && Ty->getBitWidth() == 32)
10966         return IntrinsicLowering::LowerToByteSwap(CI);
10967     }
10968     break;
10969   }
10970
10971   return false;
10972 }
10973
10974 /// getConstraintType - Given a constraint letter, return the type of
10975 /// constraint it is for this target.
10976 ARMTargetLowering::ConstraintType
10977 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10978   if (Constraint.size() == 1) {
10979     switch (Constraint[0]) {
10980     default:  break;
10981     case 'l': return C_RegisterClass;
10982     case 'w': return C_RegisterClass;
10983     case 'h': return C_RegisterClass;
10984     case 'x': return C_RegisterClass;
10985     case 't': return C_RegisterClass;
10986     case 'j': return C_Other; // Constant for movw.
10987       // An address with a single base register. Due to the way we
10988       // currently handle addresses it is the same as an 'r' memory constraint.
10989     case 'Q': return C_Memory;
10990     }
10991   } else if (Constraint.size() == 2) {
10992     switch (Constraint[0]) {
10993     default: break;
10994     // All 'U+' constraints are addresses.
10995     case 'U': return C_Memory;
10996     }
10997   }
10998   return TargetLowering::getConstraintType(Constraint);
10999 }
11000
11001 /// Examine constraint type and operand type and determine a weight value.
11002 /// This object must already have been set up with the operand type
11003 /// and the current alternative constraint selected.
11004 TargetLowering::ConstraintWeight
11005 ARMTargetLowering::getSingleConstraintMatchWeight(
11006     AsmOperandInfo &info, const char *constraint) const {
11007   ConstraintWeight weight = CW_Invalid;
11008   Value *CallOperandVal = info.CallOperandVal;
11009     // If we don't have a value, we can't do a match,
11010     // but allow it at the lowest weight.
11011   if (!CallOperandVal)
11012     return CW_Default;
11013   Type *type = CallOperandVal->getType();
11014   // Look at the constraint type.
11015   switch (*constraint) {
11016   default:
11017     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11018     break;
11019   case 'l':
11020     if (type->isIntegerTy()) {
11021       if (Subtarget->isThumb())
11022         weight = CW_SpecificReg;
11023       else
11024         weight = CW_Register;
11025     }
11026     break;
11027   case 'w':
11028     if (type->isFloatingPointTy())
11029       weight = CW_Register;
11030     break;
11031   }
11032   return weight;
11033 }
11034
11035 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11036 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11037     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11038   if (Constraint.size() == 1) {
11039     // GCC ARM Constraint Letters
11040     switch (Constraint[0]) {
11041     case 'l': // Low regs or general regs.
11042       if (Subtarget->isThumb())
11043         return RCPair(0U, &ARM::tGPRRegClass);
11044       return RCPair(0U, &ARM::GPRRegClass);
11045     case 'h': // High regs or no regs.
11046       if (Subtarget->isThumb())
11047         return RCPair(0U, &ARM::hGPRRegClass);
11048       break;
11049     case 'r':
11050       if (Subtarget->isThumb1Only())
11051         return RCPair(0U, &ARM::tGPRRegClass);
11052       return RCPair(0U, &ARM::GPRRegClass);
11053     case 'w':
11054       if (VT == MVT::Other)
11055         break;
11056       if (VT == MVT::f32)
11057         return RCPair(0U, &ARM::SPRRegClass);
11058       if (VT.getSizeInBits() == 64)
11059         return RCPair(0U, &ARM::DPRRegClass);
11060       if (VT.getSizeInBits() == 128)
11061         return RCPair(0U, &ARM::QPRRegClass);
11062       break;
11063     case 'x':
11064       if (VT == MVT::Other)
11065         break;
11066       if (VT == MVT::f32)
11067         return RCPair(0U, &ARM::SPR_8RegClass);
11068       if (VT.getSizeInBits() == 64)
11069         return RCPair(0U, &ARM::DPR_8RegClass);
11070       if (VT.getSizeInBits() == 128)
11071         return RCPair(0U, &ARM::QPR_8RegClass);
11072       break;
11073     case 't':
11074       if (VT == MVT::f32)
11075         return RCPair(0U, &ARM::SPRRegClass);
11076       break;
11077     }
11078   }
11079   if (StringRef("{cc}").equals_lower(Constraint))
11080     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11081
11082   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11083 }
11084
11085 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11086 /// vector.  If it is invalid, don't add anything to Ops.
11087 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11088                                                      std::string &Constraint,
11089                                                      std::vector<SDValue>&Ops,
11090                                                      SelectionDAG &DAG) const {
11091   SDValue Result;
11092
11093   // Currently only support length 1 constraints.
11094   if (Constraint.length() != 1) return;
11095
11096   char ConstraintLetter = Constraint[0];
11097   switch (ConstraintLetter) {
11098   default: break;
11099   case 'j':
11100   case 'I': case 'J': case 'K': case 'L':
11101   case 'M': case 'N': case 'O':
11102     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11103     if (!C)
11104       return;
11105
11106     int64_t CVal64 = C->getSExtValue();
11107     int CVal = (int) CVal64;
11108     // None of these constraints allow values larger than 32 bits.  Check
11109     // that the value fits in an int.
11110     if (CVal != CVal64)
11111       return;
11112
11113     switch (ConstraintLetter) {
11114       case 'j':
11115         // Constant suitable for movw, must be between 0 and
11116         // 65535.
11117         if (Subtarget->hasV6T2Ops())
11118           if (CVal >= 0 && CVal <= 65535)
11119             break;
11120         return;
11121       case 'I':
11122         if (Subtarget->isThumb1Only()) {
11123           // This must be a constant between 0 and 255, for ADD
11124           // immediates.
11125           if (CVal >= 0 && CVal <= 255)
11126             break;
11127         } else if (Subtarget->isThumb2()) {
11128           // A constant that can be used as an immediate value in a
11129           // data-processing instruction.
11130           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11131             break;
11132         } else {
11133           // A constant that can be used as an immediate value in a
11134           // data-processing instruction.
11135           if (ARM_AM::getSOImmVal(CVal) != -1)
11136             break;
11137         }
11138         return;
11139
11140       case 'J':
11141         if (Subtarget->isThumb()) {  // FIXME thumb2
11142           // This must be a constant between -255 and -1, for negated ADD
11143           // immediates. This can be used in GCC with an "n" modifier that
11144           // prints the negated value, for use with SUB instructions. It is
11145           // not useful otherwise but is implemented for compatibility.
11146           if (CVal >= -255 && CVal <= -1)
11147             break;
11148         } else {
11149           // This must be a constant between -4095 and 4095. It is not clear
11150           // what this constraint is intended for. Implemented for
11151           // compatibility with GCC.
11152           if (CVal >= -4095 && CVal <= 4095)
11153             break;
11154         }
11155         return;
11156
11157       case 'K':
11158         if (Subtarget->isThumb1Only()) {
11159           // A 32-bit value where only one byte has a nonzero value. Exclude
11160           // zero to match GCC. This constraint is used by GCC internally for
11161           // constants that can be loaded with a move/shift combination.
11162           // It is not useful otherwise but is implemented for compatibility.
11163           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11164             break;
11165         } else if (Subtarget->isThumb2()) {
11166           // A constant whose bitwise inverse can be used as an immediate
11167           // value in a data-processing instruction. This can be used in GCC
11168           // with a "B" modifier that prints the inverted value, for use with
11169           // BIC and MVN instructions. It is not useful otherwise but is
11170           // implemented for compatibility.
11171           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11172             break;
11173         } else {
11174           // A constant whose bitwise inverse can be used as an immediate
11175           // value in a data-processing instruction. This can be used in GCC
11176           // with a "B" modifier that prints the inverted value, for use with
11177           // BIC and MVN instructions. It is not useful otherwise but is
11178           // implemented for compatibility.
11179           if (ARM_AM::getSOImmVal(~CVal) != -1)
11180             break;
11181         }
11182         return;
11183
11184       case 'L':
11185         if (Subtarget->isThumb1Only()) {
11186           // This must be a constant between -7 and 7,
11187           // for 3-operand ADD/SUB immediate instructions.
11188           if (CVal >= -7 && CVal < 7)
11189             break;
11190         } else if (Subtarget->isThumb2()) {
11191           // A constant whose negation can be used as an immediate value in a
11192           // data-processing instruction. This can be used in GCC with an "n"
11193           // modifier that prints the negated value, for use with SUB
11194           // instructions. It is not useful otherwise but is implemented for
11195           // compatibility.
11196           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11197             break;
11198         } else {
11199           // A constant whose negation can be used as an immediate value in a
11200           // data-processing instruction. This can be used in GCC with an "n"
11201           // modifier that prints the negated value, for use with SUB
11202           // instructions. It is not useful otherwise but is implemented for
11203           // compatibility.
11204           if (ARM_AM::getSOImmVal(-CVal) != -1)
11205             break;
11206         }
11207         return;
11208
11209       case 'M':
11210         if (Subtarget->isThumb()) { // FIXME thumb2
11211           // This must be a multiple of 4 between 0 and 1020, for
11212           // ADD sp + immediate.
11213           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11214             break;
11215         } else {
11216           // A power of two or a constant between 0 and 32.  This is used in
11217           // GCC for the shift amount on shifted register operands, but it is
11218           // useful in general for any shift amounts.
11219           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11220             break;
11221         }
11222         return;
11223
11224       case 'N':
11225         if (Subtarget->isThumb()) {  // FIXME thumb2
11226           // This must be a constant between 0 and 31, for shift amounts.
11227           if (CVal >= 0 && CVal <= 31)
11228             break;
11229         }
11230         return;
11231
11232       case 'O':
11233         if (Subtarget->isThumb()) {  // FIXME thumb2
11234           // This must be a multiple of 4 between -508 and 508, for
11235           // ADD/SUB sp = sp + immediate.
11236           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11237             break;
11238         }
11239         return;
11240     }
11241     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11242     break;
11243   }
11244
11245   if (Result.getNode()) {
11246     Ops.push_back(Result);
11247     return;
11248   }
11249   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11250 }
11251
11252 static RTLIB::Libcall getDivRemLibcall(
11253     const SDNode *N, MVT::SimpleValueType SVT) {
11254   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11255           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11256          "Unhandled Opcode in getDivRemLibcall");
11257   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11258                   N->getOpcode() == ISD::SREM;
11259   RTLIB::Libcall LC;
11260   switch (SVT) {
11261   default: llvm_unreachable("Unexpected request for libcall!");
11262   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11263   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11264   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11265   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11266   }
11267   return LC;
11268 }
11269
11270 static TargetLowering::ArgListTy getDivRemArgList(
11271     const SDNode *N, LLVMContext *Context) {
11272   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11273           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11274          "Unhandled Opcode in getDivRemArgList");
11275   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11276                   N->getOpcode() == ISD::SREM;
11277   TargetLowering::ArgListTy Args;
11278   TargetLowering::ArgListEntry Entry;
11279   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11280     EVT ArgVT = N->getOperand(i).getValueType();
11281     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11282     Entry.Node = N->getOperand(i);
11283     Entry.Ty = ArgTy;
11284     Entry.isSExt = isSigned;
11285     Entry.isZExt = !isSigned;
11286     Args.push_back(Entry);
11287   }
11288   return Args;
11289 }
11290
11291 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11292   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11293          "Register-based DivRem lowering only");
11294   unsigned Opcode = Op->getOpcode();
11295   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11296          "Invalid opcode for Div/Rem lowering");
11297   bool isSigned = (Opcode == ISD::SDIVREM);
11298   EVT VT = Op->getValueType(0);
11299   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11300
11301   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11302                                        VT.getSimpleVT().SimpleTy);
11303   SDValue InChain = DAG.getEntryNode();
11304
11305   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11306                                                     DAG.getContext());
11307
11308   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11309                                          getPointerTy(DAG.getDataLayout()));
11310
11311   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11312
11313   SDLoc dl(Op);
11314   TargetLowering::CallLoweringInfo CLI(DAG);
11315   CLI.setDebugLoc(dl).setChain(InChain)
11316     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11317     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11318
11319   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11320   return CallInfo.first;
11321 }
11322
11323 // Lowers REM using divmod helpers
11324 // see RTABI section 4.2/4.3
11325 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11326   // Build return types (div and rem)
11327   std::vector<Type*> RetTyParams;
11328   Type *RetTyElement;
11329
11330   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11331   default: llvm_unreachable("Unexpected request for libcall!");
11332   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
11333   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11334   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11335   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11336   }
11337
11338   RetTyParams.push_back(RetTyElement);
11339   RetTyParams.push_back(RetTyElement);
11340   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11341   Type *RetTy = StructType::get(*DAG.getContext(), ret);
11342
11343   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11344                                                              SimpleTy);
11345   SDValue InChain = DAG.getEntryNode();
11346   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11347   bool isSigned = N->getOpcode() == ISD::SREM;
11348   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11349                                          getPointerTy(DAG.getDataLayout()));
11350
11351   // Lower call
11352   CallLoweringInfo CLI(DAG);
11353   CLI.setChain(InChain)
11354      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11355      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11356   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11357
11358   // Return second (rem) result operand (first contains div)
11359   SDNode *ResNode = CallResult.first.getNode();
11360   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11361   return ResNode->getOperand(1);
11362 }
11363
11364 SDValue
11365 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11366   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11367   SDLoc DL(Op);
11368
11369   // Get the inputs.
11370   SDValue Chain = Op.getOperand(0);
11371   SDValue Size  = Op.getOperand(1);
11372
11373   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11374                               DAG.getConstant(2, DL, MVT::i32));
11375
11376   SDValue Flag;
11377   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11378   Flag = Chain.getValue(1);
11379
11380   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11381   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11382
11383   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11384   Chain = NewSP.getValue(1);
11385
11386   SDValue Ops[2] = { NewSP, Chain };
11387   return DAG.getMergeValues(Ops, DL);
11388 }
11389
11390 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11391   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11392          "Unexpected type for custom-lowering FP_EXTEND");
11393
11394   RTLIB::Libcall LC;
11395   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11396
11397   SDValue SrcVal = Op.getOperand(0);
11398   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11399                      /*isSigned*/ false, SDLoc(Op)).first;
11400 }
11401
11402 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11403   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11404          Subtarget->isFPOnlySP() &&
11405          "Unexpected type for custom-lowering FP_ROUND");
11406
11407   RTLIB::Libcall LC;
11408   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11409
11410   SDValue SrcVal = Op.getOperand(0);
11411   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11412                      /*isSigned*/ false, SDLoc(Op)).first;
11413 }
11414
11415 bool
11416 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11417   // The ARM target isn't yet aware of offsets.
11418   return false;
11419 }
11420
11421 bool ARM::isBitFieldInvertedMask(unsigned v) {
11422   if (v == 0xffffffff)
11423     return false;
11424
11425   // there can be 1's on either or both "outsides", all the "inside"
11426   // bits must be 0's
11427   return isShiftedMask_32(~v);
11428 }
11429
11430 /// isFPImmLegal - Returns true if the target can instruction select the
11431 /// specified FP immediate natively. If false, the legalizer will
11432 /// materialize the FP immediate as a load from a constant pool.
11433 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11434   if (!Subtarget->hasVFP3())
11435     return false;
11436   if (VT == MVT::f32)
11437     return ARM_AM::getFP32Imm(Imm) != -1;
11438   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11439     return ARM_AM::getFP64Imm(Imm) != -1;
11440   return false;
11441 }
11442
11443 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11444 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11445 /// specified in the intrinsic calls.
11446 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11447                                            const CallInst &I,
11448                                            unsigned Intrinsic) const {
11449   switch (Intrinsic) {
11450   case Intrinsic::arm_neon_vld1:
11451   case Intrinsic::arm_neon_vld2:
11452   case Intrinsic::arm_neon_vld3:
11453   case Intrinsic::arm_neon_vld4:
11454   case Intrinsic::arm_neon_vld2lane:
11455   case Intrinsic::arm_neon_vld3lane:
11456   case Intrinsic::arm_neon_vld4lane: {
11457     Info.opc = ISD::INTRINSIC_W_CHAIN;
11458     // Conservatively set memVT to the entire set of vectors loaded.
11459     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11460     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11461     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11462     Info.ptrVal = I.getArgOperand(0);
11463     Info.offset = 0;
11464     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11465     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11466     Info.vol = false; // volatile loads with NEON intrinsics not supported
11467     Info.readMem = true;
11468     Info.writeMem = false;
11469     return true;
11470   }
11471   case Intrinsic::arm_neon_vst1:
11472   case Intrinsic::arm_neon_vst2:
11473   case Intrinsic::arm_neon_vst3:
11474   case Intrinsic::arm_neon_vst4:
11475   case Intrinsic::arm_neon_vst2lane:
11476   case Intrinsic::arm_neon_vst3lane:
11477   case Intrinsic::arm_neon_vst4lane: {
11478     Info.opc = ISD::INTRINSIC_VOID;
11479     // Conservatively set memVT to the entire set of vectors stored.
11480     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11481     unsigned NumElts = 0;
11482     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11483       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11484       if (!ArgTy->isVectorTy())
11485         break;
11486       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11487     }
11488     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11489     Info.ptrVal = I.getArgOperand(0);
11490     Info.offset = 0;
11491     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11492     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11493     Info.vol = false; // volatile stores with NEON intrinsics not supported
11494     Info.readMem = false;
11495     Info.writeMem = true;
11496     return true;
11497   }
11498   case Intrinsic::arm_ldaex:
11499   case Intrinsic::arm_ldrex: {
11500     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11501     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11502     Info.opc = ISD::INTRINSIC_W_CHAIN;
11503     Info.memVT = MVT::getVT(PtrTy->getElementType());
11504     Info.ptrVal = I.getArgOperand(0);
11505     Info.offset = 0;
11506     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11507     Info.vol = true;
11508     Info.readMem = true;
11509     Info.writeMem = false;
11510     return true;
11511   }
11512   case Intrinsic::arm_stlex:
11513   case Intrinsic::arm_strex: {
11514     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11515     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11516     Info.opc = ISD::INTRINSIC_W_CHAIN;
11517     Info.memVT = MVT::getVT(PtrTy->getElementType());
11518     Info.ptrVal = I.getArgOperand(1);
11519     Info.offset = 0;
11520     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11521     Info.vol = true;
11522     Info.readMem = false;
11523     Info.writeMem = true;
11524     return true;
11525   }
11526   case Intrinsic::arm_stlexd:
11527   case Intrinsic::arm_strexd: {
11528     Info.opc = ISD::INTRINSIC_W_CHAIN;
11529     Info.memVT = MVT::i64;
11530     Info.ptrVal = I.getArgOperand(2);
11531     Info.offset = 0;
11532     Info.align = 8;
11533     Info.vol = true;
11534     Info.readMem = false;
11535     Info.writeMem = true;
11536     return true;
11537   }
11538   case Intrinsic::arm_ldaexd:
11539   case Intrinsic::arm_ldrexd: {
11540     Info.opc = ISD::INTRINSIC_W_CHAIN;
11541     Info.memVT = MVT::i64;
11542     Info.ptrVal = I.getArgOperand(0);
11543     Info.offset = 0;
11544     Info.align = 8;
11545     Info.vol = true;
11546     Info.readMem = true;
11547     Info.writeMem = false;
11548     return true;
11549   }
11550   default:
11551     break;
11552   }
11553
11554   return false;
11555 }
11556
11557 /// \brief Returns true if it is beneficial to convert a load of a constant
11558 /// to just the constant itself.
11559 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11560                                                           Type *Ty) const {
11561   assert(Ty->isIntegerTy());
11562
11563   unsigned Bits = Ty->getPrimitiveSizeInBits();
11564   if (Bits == 0 || Bits > 32)
11565     return false;
11566   return true;
11567 }
11568
11569 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11570                                         ARM_MB::MemBOpt Domain) const {
11571   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11572
11573   // First, if the target has no DMB, see what fallback we can use.
11574   if (!Subtarget->hasDataBarrier()) {
11575     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11576     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11577     // here.
11578     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11579       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11580       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11581                         Builder.getInt32(0), Builder.getInt32(7),
11582                         Builder.getInt32(10), Builder.getInt32(5)};
11583       return Builder.CreateCall(MCR, args);
11584     } else {
11585       // Instead of using barriers, atomic accesses on these subtargets use
11586       // libcalls.
11587       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11588     }
11589   } else {
11590     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11591     // Only a full system barrier exists in the M-class architectures.
11592     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11593     Constant *CDomain = Builder.getInt32(Domain);
11594     return Builder.CreateCall(DMB, CDomain);
11595   }
11596 }
11597
11598 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11599 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11600                                          AtomicOrdering Ord, bool IsStore,
11601                                          bool IsLoad) const {
11602   if (!getInsertFencesForAtomic())
11603     return nullptr;
11604
11605   switch (Ord) {
11606   case NotAtomic:
11607   case Unordered:
11608     llvm_unreachable("Invalid fence: unordered/non-atomic");
11609   case Monotonic:
11610   case Acquire:
11611     return nullptr; // Nothing to do
11612   case SequentiallyConsistent:
11613     if (!IsStore)
11614       return nullptr; // Nothing to do
11615     /*FALLTHROUGH*/
11616   case Release:
11617   case AcquireRelease:
11618     if (Subtarget->isSwift())
11619       return makeDMB(Builder, ARM_MB::ISHST);
11620     // FIXME: add a comment with a link to documentation justifying this.
11621     else
11622       return makeDMB(Builder, ARM_MB::ISH);
11623   }
11624   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11625 }
11626
11627 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11628                                           AtomicOrdering Ord, bool IsStore,
11629                                           bool IsLoad) const {
11630   if (!getInsertFencesForAtomic())
11631     return nullptr;
11632
11633   switch (Ord) {
11634   case NotAtomic:
11635   case Unordered:
11636     llvm_unreachable("Invalid fence: unordered/not-atomic");
11637   case Monotonic:
11638   case Release:
11639     return nullptr; // Nothing to do
11640   case Acquire:
11641   case AcquireRelease:
11642   case SequentiallyConsistent:
11643     return makeDMB(Builder, ARM_MB::ISH);
11644   }
11645   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11646 }
11647
11648 // Loads and stores less than 64-bits are already atomic; ones above that
11649 // are doomed anyway, so defer to the default libcall and blame the OS when
11650 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11651 // anything for those.
11652 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11653   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11654   return (Size == 64) && !Subtarget->isMClass();
11655 }
11656
11657 // Loads and stores less than 64-bits are already atomic; ones above that
11658 // are doomed anyway, so defer to the default libcall and blame the OS when
11659 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11660 // anything for those.
11661 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11662 // guarantee, see DDI0406C ARM architecture reference manual,
11663 // sections A8.8.72-74 LDRD)
11664 TargetLowering::AtomicExpansionKind
11665 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11666   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11667   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLSC
11668                                                   : AtomicExpansionKind::None;
11669 }
11670
11671 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11672 // and up to 64 bits on the non-M profiles
11673 TargetLowering::AtomicExpansionKind
11674 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11675   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11676   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11677              ? AtomicExpansionKind::LLSC
11678              : AtomicExpansionKind::None;
11679 }
11680
11681 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
11682     AtomicCmpXchgInst *AI) const {
11683   return true;
11684 }
11685
11686 // This has so far only been implemented for MachO.
11687 bool ARMTargetLowering::useLoadStackGuardNode() const {
11688   return Subtarget->isTargetMachO();
11689 }
11690
11691 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11692                                                   unsigned &Cost) const {
11693   // If we do not have NEON, vector types are not natively supported.
11694   if (!Subtarget->hasNEON())
11695     return false;
11696
11697   // Floating point values and vector values map to the same register file.
11698   // Therefore, although we could do a store extract of a vector type, this is
11699   // better to leave at float as we have more freedom in the addressing mode for
11700   // those.
11701   if (VectorTy->isFPOrFPVectorTy())
11702     return false;
11703
11704   // If the index is unknown at compile time, this is very expensive to lower
11705   // and it is not possible to combine the store with the extract.
11706   if (!isa<ConstantInt>(Idx))
11707     return false;
11708
11709   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11710   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11711   // We can do a store + vector extract on any vector that fits perfectly in a D
11712   // or Q register.
11713   if (BitWidth == 64 || BitWidth == 128) {
11714     Cost = 0;
11715     return true;
11716   }
11717   return false;
11718 }
11719
11720 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11721                                          AtomicOrdering Ord) const {
11722   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11723   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11724   bool IsAcquire = isAtLeastAcquire(Ord);
11725
11726   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11727   // intrinsic must return {i32, i32} and we have to recombine them into a
11728   // single i64 here.
11729   if (ValTy->getPrimitiveSizeInBits() == 64) {
11730     Intrinsic::ID Int =
11731         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11732     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11733
11734     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11735     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11736
11737     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11738     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11739     if (!Subtarget->isLittle())
11740       std::swap (Lo, Hi);
11741     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11742     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11743     return Builder.CreateOr(
11744         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11745   }
11746
11747   Type *Tys[] = { Addr->getType() };
11748   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11749   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11750
11751   return Builder.CreateTruncOrBitCast(
11752       Builder.CreateCall(Ldrex, Addr),
11753       cast<PointerType>(Addr->getType())->getElementType());
11754 }
11755
11756 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11757     IRBuilder<> &Builder) const {
11758   if (!Subtarget->hasV7Ops())
11759     return;
11760   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11761   Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
11762 }
11763
11764 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11765                                                Value *Addr,
11766                                                AtomicOrdering Ord) const {
11767   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11768   bool IsRelease = isAtLeastRelease(Ord);
11769
11770   // Since the intrinsics must have legal type, the i64 intrinsics take two
11771   // parameters: "i32, i32". We must marshal Val into the appropriate form
11772   // before the call.
11773   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11774     Intrinsic::ID Int =
11775         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11776     Function *Strex = Intrinsic::getDeclaration(M, Int);
11777     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11778
11779     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11780     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11781     if (!Subtarget->isLittle())
11782       std::swap (Lo, Hi);
11783     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11784     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11785   }
11786
11787   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11788   Type *Tys[] = { Addr->getType() };
11789   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11790
11791   return Builder.CreateCall(
11792       Strex, {Builder.CreateZExtOrBitCast(
11793                   Val, Strex->getFunctionType()->getParamType(0)),
11794               Addr});
11795 }
11796
11797 /// \brief Lower an interleaved load into a vldN intrinsic.
11798 ///
11799 /// E.g. Lower an interleaved load (Factor = 2):
11800 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11801 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11802 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11803 ///
11804 ///      Into:
11805 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11806 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11807 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11808 bool ARMTargetLowering::lowerInterleavedLoad(
11809     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11810     ArrayRef<unsigned> Indices, unsigned Factor) const {
11811   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11812          "Invalid interleave factor");
11813   assert(!Shuffles.empty() && "Empty shufflevector input");
11814   assert(Shuffles.size() == Indices.size() &&
11815          "Unmatched number of shufflevectors and indices");
11816
11817   VectorType *VecTy = Shuffles[0]->getType();
11818   Type *EltTy = VecTy->getVectorElementType();
11819
11820   const DataLayout &DL = LI->getModule()->getDataLayout();
11821   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11822   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11823
11824   // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11825   // support i64/f64 element).
11826   if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11827     return false;
11828
11829   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11830   // load integer vectors first and then convert to pointer vectors.
11831   if (EltTy->isPointerTy())
11832     VecTy =
11833         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11834
11835   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11836                                             Intrinsic::arm_neon_vld3,
11837                                             Intrinsic::arm_neon_vld4};
11838
11839   IRBuilder<> Builder(LI);
11840   SmallVector<Value *, 2> Ops;
11841
11842   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11843   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11844   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11845
11846   Type *Tys[] = { VecTy, Int8Ptr };
11847   Function *VldnFunc =
11848       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
11849   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11850
11851   // Replace uses of each shufflevector with the corresponding vector loaded
11852   // by ldN.
11853   for (unsigned i = 0; i < Shuffles.size(); i++) {
11854     ShuffleVectorInst *SV = Shuffles[i];
11855     unsigned Index = Indices[i];
11856
11857     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11858
11859     // Convert the integer vector to pointer vector if the element is pointer.
11860     if (EltTy->isPointerTy())
11861       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11862
11863     SV->replaceAllUsesWith(SubVec);
11864   }
11865
11866   return true;
11867 }
11868
11869 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11870 ///
11871 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11872 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11873                                    unsigned NumElts) {
11874   SmallVector<Constant *, 16> Mask;
11875   for (unsigned i = 0; i < NumElts; i++)
11876     Mask.push_back(Builder.getInt32(Start + i));
11877
11878   return ConstantVector::get(Mask);
11879 }
11880
11881 /// \brief Lower an interleaved store into a vstN intrinsic.
11882 ///
11883 /// E.g. Lower an interleaved store (Factor = 3):
11884 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11885 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11886 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11887 ///
11888 ///      Into:
11889 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11890 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11891 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11892 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11893 ///
11894 /// Note that the new shufflevectors will be removed and we'll only generate one
11895 /// vst3 instruction in CodeGen.
11896 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11897                                               ShuffleVectorInst *SVI,
11898                                               unsigned Factor) const {
11899   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11900          "Invalid interleave factor");
11901
11902   VectorType *VecTy = SVI->getType();
11903   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11904          "Invalid interleaved store");
11905
11906   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11907   Type *EltTy = VecTy->getVectorElementType();
11908   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11909
11910   const DataLayout &DL = SI->getModule()->getDataLayout();
11911   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11912   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11913
11914   // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11915   // doesn't support i64/f64 element).
11916   if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11917     return false;
11918
11919   Value *Op0 = SVI->getOperand(0);
11920   Value *Op1 = SVI->getOperand(1);
11921   IRBuilder<> Builder(SI);
11922
11923   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11924   // vectors to integer vectors.
11925   if (EltTy->isPointerTy()) {
11926     Type *IntTy = DL.getIntPtrType(EltTy);
11927
11928     // Convert to the corresponding integer vector.
11929     Type *IntVecTy =
11930         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11931     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11932     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11933
11934     SubVecTy = VectorType::get(IntTy, NumSubElts);
11935   }
11936
11937   static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11938                                        Intrinsic::arm_neon_vst3,
11939                                        Intrinsic::arm_neon_vst4};
11940   SmallVector<Value *, 6> Ops;
11941
11942   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11943   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11944
11945   Type *Tys[] = { Int8Ptr, SubVecTy };
11946   Function *VstNFunc = Intrinsic::getDeclaration(
11947       SI->getModule(), StoreInts[Factor - 2], Tys);
11948
11949   // Split the shufflevector operands into sub vectors for the new vstN call.
11950   for (unsigned i = 0; i < Factor; i++)
11951     Ops.push_back(Builder.CreateShuffleVector(
11952         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11953
11954   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11955   Builder.CreateCall(VstNFunc, Ops);
11956   return true;
11957 }
11958
11959 enum HABaseType {
11960   HA_UNKNOWN = 0,
11961   HA_FLOAT,
11962   HA_DOUBLE,
11963   HA_VECT64,
11964   HA_VECT128
11965 };
11966
11967 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11968                                    uint64_t &Members) {
11969   if (auto *ST = dyn_cast<StructType>(Ty)) {
11970     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11971       uint64_t SubMembers = 0;
11972       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11973         return false;
11974       Members += SubMembers;
11975     }
11976   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11977     uint64_t SubMembers = 0;
11978     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11979       return false;
11980     Members += SubMembers * AT->getNumElements();
11981   } else if (Ty->isFloatTy()) {
11982     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11983       return false;
11984     Members = 1;
11985     Base = HA_FLOAT;
11986   } else if (Ty->isDoubleTy()) {
11987     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11988       return false;
11989     Members = 1;
11990     Base = HA_DOUBLE;
11991   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11992     Members = 1;
11993     switch (Base) {
11994     case HA_FLOAT:
11995     case HA_DOUBLE:
11996       return false;
11997     case HA_VECT64:
11998       return VT->getBitWidth() == 64;
11999     case HA_VECT128:
12000       return VT->getBitWidth() == 128;
12001     case HA_UNKNOWN:
12002       switch (VT->getBitWidth()) {
12003       case 64:
12004         Base = HA_VECT64;
12005         return true;
12006       case 128:
12007         Base = HA_VECT128;
12008         return true;
12009       default:
12010         return false;
12011       }
12012     }
12013   }
12014
12015   return (Members > 0 && Members <= 4);
12016 }
12017
12018 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
12019 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
12020 /// passing according to AAPCS rules.
12021 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
12022     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12023   if (getEffectiveCallingConv(CallConv, isVarArg) !=
12024       CallingConv::ARM_AAPCS_VFP)
12025     return false;
12026
12027   HABaseType Base = HA_UNKNOWN;
12028   uint64_t Members = 0;
12029   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12030   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12031
12032   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12033   return IsHA || IsIntArray;
12034 }