ebc63e0db245cbaace0cf63c913525ea520b4c78
[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       { RTLIB::SDIV_I32, "__rt_sdiv",   CallingConv::ARM_AAPCS_VFP },
373       { RTLIB::UDIV_I32, "__rt_udiv",   CallingConv::ARM_AAPCS_VFP },
374       { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP },
375       { RTLIB::UDIV_I64, "__rt_udiv64", CallingConv::ARM_AAPCS_VFP },
376     };
377
378     for (const auto &LC : LibraryCalls) {
379       setLibcallName(LC.Op, LC.Name);
380       setLibcallCallingConv(LC.Op, LC.CC);
381     }
382   }
383
384   // Use divmod compiler-rt calls for iOS 5.0 and later.
385   if (Subtarget->getTargetTriple().isiOS() &&
386       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
387     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
388     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
389   }
390
391   // The half <-> float conversion functions are always soft-float, but are
392   // needed for some targets which use a hard-float calling convention by
393   // default.
394   if (Subtarget->isAAPCS_ABI()) {
395     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
396     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
397     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
398   } else {
399     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
400     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
401     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
402   }
403
404   if (Subtarget->isThumb1Only())
405     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
406   else
407     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
408   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
409       !Subtarget->isThumb1Only()) {
410     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
411     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
412   }
413
414   for (MVT VT : MVT::vector_valuetypes()) {
415     for (MVT InnerVT : MVT::vector_valuetypes()) {
416       setTruncStoreAction(VT, InnerVT, Expand);
417       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
418       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
419       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
420     }
421
422     setOperationAction(ISD::MULHS, VT, Expand);
423     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
424     setOperationAction(ISD::MULHU, VT, Expand);
425     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
426
427     setOperationAction(ISD::BSWAP, VT, Expand);
428   }
429
430   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
431   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
432
433   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
434   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
435
436   if (Subtarget->hasNEON()) {
437     addDRTypeForNEON(MVT::v2f32);
438     addDRTypeForNEON(MVT::v8i8);
439     addDRTypeForNEON(MVT::v4i16);
440     addDRTypeForNEON(MVT::v2i32);
441     addDRTypeForNEON(MVT::v1i64);
442
443     addQRTypeForNEON(MVT::v4f32);
444     addQRTypeForNEON(MVT::v2f64);
445     addQRTypeForNEON(MVT::v16i8);
446     addQRTypeForNEON(MVT::v8i16);
447     addQRTypeForNEON(MVT::v4i32);
448     addQRTypeForNEON(MVT::v2i64);
449
450     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
451     // neither Neon nor VFP support any arithmetic operations on it.
452     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
453     // supported for v4f32.
454     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
455     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
456     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
457     // FIXME: Code duplication: FDIV and FREM are expanded always, see
458     // ARMTargetLowering::addTypeForNEON method for details.
459     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
460     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
461     // FIXME: Create unittest.
462     // In another words, find a way when "copysign" appears in DAG with vector
463     // operands.
464     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
465     // FIXME: Code duplication: SETCC has custom operation action, see
466     // ARMTargetLowering::addTypeForNEON method for details.
467     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
468     // FIXME: Create unittest for FNEG and for FABS.
469     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
470     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
471     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
472     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
473     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
474     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
475     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
476     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
477     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
478     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
479     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
480     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
481     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
482     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
483     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
484     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
485     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
486     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
487     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
488
489     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
490     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
491     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
492     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
493     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
494     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
495     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
496     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
497     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
498     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
499     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
500     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
501     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
502     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
503     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
504
505     // Mark v2f32 intrinsics.
506     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
507     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
508     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
509     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
510     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
511     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
512     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
513     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
514     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
515     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
516     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
517     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
518     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
519     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
520     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
521
522     // Neon does not support some operations on v1i64 and v2i64 types.
523     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
524     // Custom handling for some quad-vector types to detect VMULL.
525     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
528     // Custom handling for some vector types to avoid expensive expansions
529     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
530     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
531     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
532     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
533     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
534     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
535     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
536     // a destination type that is wider than the source, and nor does
537     // it have a FP_TO_[SU]INT instruction with a narrower destination than
538     // source.
539     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
540     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
541     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
542     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
543
544     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
545     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
546
547     // NEON does not have single instruction CTPOP for vectors with element
548     // types wider than 8-bits.  However, custom lowering can leverage the
549     // v8i8/v16i8 vcnt instruction.
550     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
551     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
552     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
553     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
554
555     // NEON does not have single instruction CTTZ for vectors.
556     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
557     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
558     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
559     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
560
561     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
562     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
563     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
564     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
565
566     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
567     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
568     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
569     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
570
571     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
572     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
573     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
574     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
575
576     // NEON only has FMA instructions as of VFP4.
577     if (!Subtarget->hasVFP4()) {
578       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
579       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
580     }
581
582     setTargetDAGCombine(ISD::INTRINSIC_VOID);
583     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
584     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
585     setTargetDAGCombine(ISD::SHL);
586     setTargetDAGCombine(ISD::SRL);
587     setTargetDAGCombine(ISD::SRA);
588     setTargetDAGCombine(ISD::SIGN_EXTEND);
589     setTargetDAGCombine(ISD::ZERO_EXTEND);
590     setTargetDAGCombine(ISD::ANY_EXTEND);
591     setTargetDAGCombine(ISD::BUILD_VECTOR);
592     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
593     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
594     setTargetDAGCombine(ISD::STORE);
595     setTargetDAGCombine(ISD::FP_TO_SINT);
596     setTargetDAGCombine(ISD::FP_TO_UINT);
597     setTargetDAGCombine(ISD::FDIV);
598     setTargetDAGCombine(ISD::LOAD);
599
600     // It is legal to extload from v4i8 to v4i16 or v4i32.
601     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
602                    MVT::v2i32}) {
603       for (MVT VT : MVT::integer_vector_valuetypes()) {
604         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
605         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
606         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
607       }
608     }
609   }
610
611   // ARM and Thumb2 support UMLAL/SMLAL.
612   if (!Subtarget->isThumb1Only())
613     setTargetDAGCombine(ISD::ADDC);
614
615   if (Subtarget->isFPOnlySP()) {
616     // When targeting a floating-point unit with only single-precision
617     // operations, f64 is legal for the few double-precision instructions which
618     // are present However, no double-precision operations other than moves,
619     // loads and stores are provided by the hardware.
620     setOperationAction(ISD::FADD,       MVT::f64, Expand);
621     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
622     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
623     setOperationAction(ISD::FMA,        MVT::f64, Expand);
624     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
625     setOperationAction(ISD::FREM,       MVT::f64, Expand);
626     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
627     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
628     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
629     setOperationAction(ISD::FABS,       MVT::f64, Expand);
630     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
631     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
632     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
633     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
634     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
635     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
636     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
637     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
638     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
639     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
640     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
641     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
642     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
643     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
644     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
645     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
646     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
647     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
648     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
649     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
650     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
651     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
652     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
653   }
654
655   computeRegisterProperties(Subtarget->getRegisterInfo());
656
657   // ARM does not have floating-point extending loads.
658   for (MVT VT : MVT::fp_valuetypes()) {
659     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
660     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
661   }
662
663   // ... or truncating stores
664   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
665   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
666   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
667
668   // ARM does not have i1 sign extending load.
669   for (MVT VT : MVT::integer_valuetypes())
670     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
671
672   // ARM supports all 4 flavors of integer indexed load / store.
673   if (!Subtarget->isThumb1Only()) {
674     for (unsigned im = (unsigned)ISD::PRE_INC;
675          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
676       setIndexedLoadAction(im,  MVT::i1,  Legal);
677       setIndexedLoadAction(im,  MVT::i8,  Legal);
678       setIndexedLoadAction(im,  MVT::i16, Legal);
679       setIndexedLoadAction(im,  MVT::i32, Legal);
680       setIndexedStoreAction(im, MVT::i1,  Legal);
681       setIndexedStoreAction(im, MVT::i8,  Legal);
682       setIndexedStoreAction(im, MVT::i16, Legal);
683       setIndexedStoreAction(im, MVT::i32, Legal);
684     }
685   }
686
687   setOperationAction(ISD::SADDO, MVT::i32, Custom);
688   setOperationAction(ISD::UADDO, MVT::i32, Custom);
689   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
690   setOperationAction(ISD::USUBO, MVT::i32, Custom);
691
692   // i64 operation support.
693   setOperationAction(ISD::MUL,     MVT::i64, Expand);
694   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
695   if (Subtarget->isThumb1Only()) {
696     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
697     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
698   }
699   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
700       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
701     setOperationAction(ISD::MULHS, MVT::i32, Expand);
702
703   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
704   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
705   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
706   setOperationAction(ISD::SRL,       MVT::i64, Custom);
707   setOperationAction(ISD::SRA,       MVT::i64, Custom);
708
709   if (!Subtarget->isThumb1Only()) {
710     // FIXME: We should do this for Thumb1 as well.
711     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
712     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
713     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
714     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
715   }
716
717   // ARM does not have ROTL.
718   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
719   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
720   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
721   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
722     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
723
724   // These just redirect to CTTZ and CTLZ on ARM.
725   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
726   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
727
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   // FIXME: Also set divmod for SREM on EABI/androideabi
742   setOperationAction(ISD::SREM,  MVT::i32, Expand);
743   setOperationAction(ISD::UREM,  MVT::i32, Expand);
744   // Register based DivRem for AEABI (RTABI 4.2)
745   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
746     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
747     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
748     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
749     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
750     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
751     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
752     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
753     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
754
755     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
756     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
757     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
758     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
759     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
760     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
761     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
762     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
763
764     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
765     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
766   } else {
767     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
768     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
769   }
770
771   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
772   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
773   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
774   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
775   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
776
777   setOperationAction(ISD::TRAP, MVT::Other, Legal);
778
779   // Use the default implementation.
780   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
781   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
782   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
783   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
784   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
785   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
786
787   if (!Subtarget->isTargetMachO()) {
788     // Non-MachO platforms may return values in these registers via the
789     // personality function.
790     setExceptionPointerRegister(ARM::R0);
791     setExceptionSelectorRegister(ARM::R1);
792   }
793
794   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
795     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
796   else
797     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
798
799   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
800   // the default expansion. If we are targeting a single threaded system,
801   // then set them all for expand so we can lower them later into their
802   // non-atomic form.
803   if (TM.Options.ThreadModel == ThreadModel::Single)
804     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
805   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
806     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
807     // to ldrex/strex loops already.
808     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
809
810     // On v8, we have particularly efficient implementations of atomic fences
811     // if they can be combined with nearby atomic loads and stores.
812     if (!Subtarget->hasV8Ops()) {
813       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
814       setInsertFencesForAtomic(true);
815     }
816   } else {
817     // If there's anything we can use as a barrier, go through custom lowering
818     // for ATOMIC_FENCE.
819     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
820                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
821
822     // Set them all for expansion, which will force libcalls.
823     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
824     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
825     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
826     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
827     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
828     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
829     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
830     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
831     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
832     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
833     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
834     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
835     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
836     // Unordered/Monotonic case.
837     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
838     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
839   }
840
841   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
842
843   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
844   if (!Subtarget->hasV6Ops()) {
845     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
846     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
847   }
848   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
849
850   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
851       !Subtarget->isThumb1Only()) {
852     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
853     // iff target supports vfp2.
854     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
855     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
856   }
857
858   // We want to custom lower some of our intrinsics.
859   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
860   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
861   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
862   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
863   if (Subtarget->isTargetDarwin())
864     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
865
866   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
867   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
868   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
869   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
870   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
871   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
872   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
873   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
874   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
875
876   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
877   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
878   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
879   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
880   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
881
882   // We don't support sin/cos/fmod/copysign/pow
883   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
884   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
885   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
886   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
887   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
888   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
889   setOperationAction(ISD::FREM,      MVT::f64, Expand);
890   setOperationAction(ISD::FREM,      MVT::f32, Expand);
891   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
892       !Subtarget->isThumb1Only()) {
893     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
894     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
895   }
896   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
897   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
898
899   if (!Subtarget->hasVFP4()) {
900     setOperationAction(ISD::FMA, MVT::f64, Expand);
901     setOperationAction(ISD::FMA, MVT::f32, Expand);
902   }
903
904   // Various VFP goodness
905   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
906     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
907     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
908       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
909       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
910     }
911
912     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
913     if (!Subtarget->hasFP16()) {
914       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
915       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
916     }
917   }
918
919   // Combine sin / cos into one node or libcall if possible.
920   if (Subtarget->hasSinCos()) {
921     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
922     setLibcallName(RTLIB::SINCOS_F64, "sincos");
923     if (Subtarget->getTargetTriple().isiOS()) {
924       // For iOS, we don't want to the normal expansion of a libcall to
925       // sincos. We want to issue a libcall to __sincos_stret.
926       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
927       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
928     }
929   }
930
931   // FP-ARMv8 implements a lot of rounding-like FP operations.
932   if (Subtarget->hasFPARMv8()) {
933     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
934     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
935     setOperationAction(ISD::FROUND, MVT::f32, Legal);
936     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
937     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
938     setOperationAction(ISD::FRINT, MVT::f32, Legal);
939     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
940     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
941     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
942     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
943     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
944     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
945
946     if (!Subtarget->isFPOnlySP()) {
947       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
948       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
949       setOperationAction(ISD::FROUND, MVT::f64, Legal);
950       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
951       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
952       setOperationAction(ISD::FRINT, MVT::f64, Legal);
953       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
954       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
955     }
956   }
957
958   if (Subtarget->hasNEON()) {
959     // vmin and vmax aren't available in a scalar form, so we use
960     // a NEON instruction with an undef lane instead.
961     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
962     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
963     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
964     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
965     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
966     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
967   }
968
969   // We have target-specific dag combine patterns for the following nodes:
970   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
971   setTargetDAGCombine(ISD::ADD);
972   setTargetDAGCombine(ISD::SUB);
973   setTargetDAGCombine(ISD::MUL);
974   setTargetDAGCombine(ISD::AND);
975   setTargetDAGCombine(ISD::OR);
976   setTargetDAGCombine(ISD::XOR);
977
978   if (Subtarget->hasV6Ops())
979     setTargetDAGCombine(ISD::SRL);
980
981   setStackPointerRegisterToSaveRestore(ARM::SP);
982
983   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
984       !Subtarget->hasVFP2())
985     setSchedulingPreference(Sched::RegPressure);
986   else
987     setSchedulingPreference(Sched::Hybrid);
988
989   //// temporary - rewrite interface to use type
990   MaxStoresPerMemset = 8;
991   MaxStoresPerMemsetOptSize = 4;
992   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
993   MaxStoresPerMemcpyOptSize = 2;
994   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
995   MaxStoresPerMemmoveOptSize = 2;
996
997   // On ARM arguments smaller than 4 bytes are extended, so all arguments
998   // are at least 4 bytes aligned.
999   setMinStackArgumentAlignment(4);
1000
1001   // Prefer likely predicted branches to selects on out-of-order cores.
1002   PredictableSelectIsExpensive = Subtarget->isLikeA9();
1003
1004   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1005 }
1006
1007 bool ARMTargetLowering::useSoftFloat() const {
1008   return Subtarget->useSoftFloat();
1009 }
1010
1011 // FIXME: It might make sense to define the representative register class as the
1012 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1013 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1014 // SPR's representative would be DPR_VFP2. This should work well if register
1015 // pressure tracking were modified such that a register use would increment the
1016 // pressure of the register class's representative and all of it's super
1017 // classes' representatives transitively. We have not implemented this because
1018 // of the difficulty prior to coalescing of modeling operand register classes
1019 // due to the common occurrence of cross class copies and subregister insertions
1020 // and extractions.
1021 std::pair<const TargetRegisterClass *, uint8_t>
1022 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1023                                            MVT VT) const {
1024   const TargetRegisterClass *RRC = nullptr;
1025   uint8_t Cost = 1;
1026   switch (VT.SimpleTy) {
1027   default:
1028     return TargetLowering::findRepresentativeClass(TRI, VT);
1029   // Use DPR as representative register class for all floating point
1030   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1031   // the cost is 1 for both f32 and f64.
1032   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1033   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1034     RRC = &ARM::DPRRegClass;
1035     // When NEON is used for SP, only half of the register file is available
1036     // because operations that define both SP and DP results will be constrained
1037     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1038     // coalescing by double-counting the SP regs. See the FIXME above.
1039     if (Subtarget->useNEONForSinglePrecisionFP())
1040       Cost = 2;
1041     break;
1042   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1043   case MVT::v4f32: case MVT::v2f64:
1044     RRC = &ARM::DPRRegClass;
1045     Cost = 2;
1046     break;
1047   case MVT::v4i64:
1048     RRC = &ARM::DPRRegClass;
1049     Cost = 4;
1050     break;
1051   case MVT::v8i64:
1052     RRC = &ARM::DPRRegClass;
1053     Cost = 8;
1054     break;
1055   }
1056   return std::make_pair(RRC, Cost);
1057 }
1058
1059 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1060   switch ((ARMISD::NodeType)Opcode) {
1061   case ARMISD::FIRST_NUMBER:  break;
1062   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1063   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1064   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1065   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1066   case ARMISD::CALL:          return "ARMISD::CALL";
1067   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1068   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1069   case ARMISD::tCALL:         return "ARMISD::tCALL";
1070   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1071   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1072   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1073   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1074   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1075   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1076   case ARMISD::CMP:           return "ARMISD::CMP";
1077   case ARMISD::CMN:           return "ARMISD::CMN";
1078   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1079   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1080   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1081   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1082   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1083
1084   case ARMISD::CMOV:          return "ARMISD::CMOV";
1085
1086   case ARMISD::RBIT:          return "ARMISD::RBIT";
1087
1088   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1089   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1090   case ARMISD::RRX:           return "ARMISD::RRX";
1091
1092   case ARMISD::ADDC:          return "ARMISD::ADDC";
1093   case ARMISD::ADDE:          return "ARMISD::ADDE";
1094   case ARMISD::SUBC:          return "ARMISD::SUBC";
1095   case ARMISD::SUBE:          return "ARMISD::SUBE";
1096
1097   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1098   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1099
1100   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1101   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1102   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1103
1104   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1105
1106   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1107
1108   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1109
1110   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1111
1112   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1113
1114   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1115
1116   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1117   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1118   case ARMISD::VCGE:          return "ARMISD::VCGE";
1119   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1120   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1121   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1122   case ARMISD::VCGT:          return "ARMISD::VCGT";
1123   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1124   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1125   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1126   case ARMISD::VTST:          return "ARMISD::VTST";
1127
1128   case ARMISD::VSHL:          return "ARMISD::VSHL";
1129   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1130   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1131   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1132   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1133   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1134   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1135   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1136   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1137   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1138   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1139   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1140   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1141   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1142   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1143   case ARMISD::VSLI:          return "ARMISD::VSLI";
1144   case ARMISD::VSRI:          return "ARMISD::VSRI";
1145   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1146   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1147   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1148   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1149   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1150   case ARMISD::VDUP:          return "ARMISD::VDUP";
1151   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1152   case ARMISD::VEXT:          return "ARMISD::VEXT";
1153   case ARMISD::VREV64:        return "ARMISD::VREV64";
1154   case ARMISD::VREV32:        return "ARMISD::VREV32";
1155   case ARMISD::VREV16:        return "ARMISD::VREV16";
1156   case ARMISD::VZIP:          return "ARMISD::VZIP";
1157   case ARMISD::VUZP:          return "ARMISD::VUZP";
1158   case ARMISD::VTRN:          return "ARMISD::VTRN";
1159   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1160   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1161   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1162   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1163   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1164   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1165   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1166   case ARMISD::BFI:           return "ARMISD::BFI";
1167   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1168   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1169   case ARMISD::VBSL:          return "ARMISD::VBSL";
1170   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1171   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1172   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1173   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1174   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1175   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1176   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1177   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1178   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1179   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1180   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1181   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1182   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1183   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1184   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1185   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1186   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1187   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1188   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1189   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1190   }
1191   return nullptr;
1192 }
1193
1194 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1195                                           EVT VT) const {
1196   if (!VT.isVector())
1197     return getPointerTy(DL);
1198   return VT.changeVectorElementTypeToInteger();
1199 }
1200
1201 /// getRegClassFor - Return the register class that should be used for the
1202 /// specified value type.
1203 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1204   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1205   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1206   // load / store 4 to 8 consecutive D registers.
1207   if (Subtarget->hasNEON()) {
1208     if (VT == MVT::v4i64)
1209       return &ARM::QQPRRegClass;
1210     if (VT == MVT::v8i64)
1211       return &ARM::QQQQPRRegClass;
1212   }
1213   return TargetLowering::getRegClassFor(VT);
1214 }
1215
1216 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1217 // source/dest is aligned and the copy size is large enough. We therefore want
1218 // to align such objects passed to memory intrinsics.
1219 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1220                                                unsigned &PrefAlign) const {
1221   if (!isa<MemIntrinsic>(CI))
1222     return false;
1223   MinSize = 8;
1224   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1225   // cycle faster than 4-byte aligned LDM.
1226   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1227   return true;
1228 }
1229
1230 // Create a fast isel object.
1231 FastISel *
1232 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1233                                   const TargetLibraryInfo *libInfo) const {
1234   return ARM::createFastISel(funcInfo, libInfo);
1235 }
1236
1237 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1238   unsigned NumVals = N->getNumValues();
1239   if (!NumVals)
1240     return Sched::RegPressure;
1241
1242   for (unsigned i = 0; i != NumVals; ++i) {
1243     EVT VT = N->getValueType(i);
1244     if (VT == MVT::Glue || VT == MVT::Other)
1245       continue;
1246     if (VT.isFloatingPoint() || VT.isVector())
1247       return Sched::ILP;
1248   }
1249
1250   if (!N->isMachineOpcode())
1251     return Sched::RegPressure;
1252
1253   // Load are scheduled for latency even if there instruction itinerary
1254   // is not available.
1255   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1256   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1257
1258   if (MCID.getNumDefs() == 0)
1259     return Sched::RegPressure;
1260   if (!Itins->isEmpty() &&
1261       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1262     return Sched::ILP;
1263
1264   return Sched::RegPressure;
1265 }
1266
1267 //===----------------------------------------------------------------------===//
1268 // Lowering Code
1269 //===----------------------------------------------------------------------===//
1270
1271 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1272 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1273   switch (CC) {
1274   default: llvm_unreachable("Unknown condition code!");
1275   case ISD::SETNE:  return ARMCC::NE;
1276   case ISD::SETEQ:  return ARMCC::EQ;
1277   case ISD::SETGT:  return ARMCC::GT;
1278   case ISD::SETGE:  return ARMCC::GE;
1279   case ISD::SETLT:  return ARMCC::LT;
1280   case ISD::SETLE:  return ARMCC::LE;
1281   case ISD::SETUGT: return ARMCC::HI;
1282   case ISD::SETUGE: return ARMCC::HS;
1283   case ISD::SETULT: return ARMCC::LO;
1284   case ISD::SETULE: return ARMCC::LS;
1285   }
1286 }
1287
1288 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1289 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1290                         ARMCC::CondCodes &CondCode2) {
1291   CondCode2 = ARMCC::AL;
1292   switch (CC) {
1293   default: llvm_unreachable("Unknown FP condition!");
1294   case ISD::SETEQ:
1295   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1296   case ISD::SETGT:
1297   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1298   case ISD::SETGE:
1299   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1300   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1301   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1302   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1303   case ISD::SETO:   CondCode = ARMCC::VC; break;
1304   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1305   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1306   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1307   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1308   case ISD::SETLT:
1309   case ISD::SETULT: CondCode = ARMCC::LT; break;
1310   case ISD::SETLE:
1311   case ISD::SETULE: CondCode = ARMCC::LE; break;
1312   case ISD::SETNE:
1313   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1314   }
1315 }
1316
1317 //===----------------------------------------------------------------------===//
1318 //                      Calling Convention Implementation
1319 //===----------------------------------------------------------------------===//
1320
1321 #include "ARMGenCallingConv.inc"
1322
1323 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1324 /// account presence of floating point hardware and calling convention
1325 /// limitations, such as support for variadic functions.
1326 CallingConv::ID
1327 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1328                                            bool isVarArg) const {
1329   switch (CC) {
1330   default:
1331     llvm_unreachable("Unsupported calling convention");
1332   case CallingConv::ARM_AAPCS:
1333   case CallingConv::ARM_APCS:
1334   case CallingConv::GHC:
1335     return CC;
1336   case CallingConv::ARM_AAPCS_VFP:
1337     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1338   case CallingConv::C:
1339     if (!Subtarget->isAAPCS_ABI())
1340       return CallingConv::ARM_APCS;
1341     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1342              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1343              !isVarArg)
1344       return CallingConv::ARM_AAPCS_VFP;
1345     else
1346       return CallingConv::ARM_AAPCS;
1347   case CallingConv::Fast:
1348     if (!Subtarget->isAAPCS_ABI()) {
1349       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1350         return CallingConv::Fast;
1351       return CallingConv::ARM_APCS;
1352     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1353       return CallingConv::ARM_AAPCS_VFP;
1354     else
1355       return CallingConv::ARM_AAPCS;
1356   }
1357 }
1358
1359 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1360 /// CallingConvention.
1361 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1362                                                  bool Return,
1363                                                  bool isVarArg) const {
1364   switch (getEffectiveCallingConv(CC, isVarArg)) {
1365   default:
1366     llvm_unreachable("Unsupported calling convention");
1367   case CallingConv::ARM_APCS:
1368     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1369   case CallingConv::ARM_AAPCS:
1370     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1371   case CallingConv::ARM_AAPCS_VFP:
1372     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1373   case CallingConv::Fast:
1374     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1375   case CallingConv::GHC:
1376     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1377   }
1378 }
1379
1380 /// LowerCallResult - Lower the result values of a call into the
1381 /// appropriate copies out of appropriate physical registers.
1382 SDValue
1383 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1384                                    CallingConv::ID CallConv, bool isVarArg,
1385                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1386                                    SDLoc dl, SelectionDAG &DAG,
1387                                    SmallVectorImpl<SDValue> &InVals,
1388                                    bool isThisReturn, SDValue ThisVal) const {
1389
1390   // Assign locations to each value returned by this call.
1391   SmallVector<CCValAssign, 16> RVLocs;
1392   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1393                     *DAG.getContext(), Call);
1394   CCInfo.AnalyzeCallResult(Ins,
1395                            CCAssignFnForNode(CallConv, /* Return*/ true,
1396                                              isVarArg));
1397
1398   // Copy all of the result registers out of their specified physreg.
1399   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1400     CCValAssign VA = RVLocs[i];
1401
1402     // Pass 'this' value directly from the argument to return value, to avoid
1403     // reg unit interference
1404     if (i == 0 && isThisReturn) {
1405       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1406              "unexpected return calling convention register assignment");
1407       InVals.push_back(ThisVal);
1408       continue;
1409     }
1410
1411     SDValue Val;
1412     if (VA.needsCustom()) {
1413       // Handle f64 or half of a v2f64.
1414       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1415                                       InFlag);
1416       Chain = Lo.getValue(1);
1417       InFlag = Lo.getValue(2);
1418       VA = RVLocs[++i]; // skip ahead to next loc
1419       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1420                                       InFlag);
1421       Chain = Hi.getValue(1);
1422       InFlag = Hi.getValue(2);
1423       if (!Subtarget->isLittle())
1424         std::swap (Lo, Hi);
1425       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1426
1427       if (VA.getLocVT() == MVT::v2f64) {
1428         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1429         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1430                           DAG.getConstant(0, dl, MVT::i32));
1431
1432         VA = RVLocs[++i]; // skip ahead to next loc
1433         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1434         Chain = Lo.getValue(1);
1435         InFlag = Lo.getValue(2);
1436         VA = RVLocs[++i]; // skip ahead to next loc
1437         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1438         Chain = Hi.getValue(1);
1439         InFlag = Hi.getValue(2);
1440         if (!Subtarget->isLittle())
1441           std::swap (Lo, Hi);
1442         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1443         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1444                           DAG.getConstant(1, dl, MVT::i32));
1445       }
1446     } else {
1447       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1448                                InFlag);
1449       Chain = Val.getValue(1);
1450       InFlag = Val.getValue(2);
1451     }
1452
1453     switch (VA.getLocInfo()) {
1454     default: llvm_unreachable("Unknown loc info!");
1455     case CCValAssign::Full: break;
1456     case CCValAssign::BCvt:
1457       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1458       break;
1459     }
1460
1461     InVals.push_back(Val);
1462   }
1463
1464   return Chain;
1465 }
1466
1467 /// LowerMemOpCallTo - Store the argument to the stack.
1468 SDValue
1469 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1470                                     SDValue StackPtr, SDValue Arg,
1471                                     SDLoc dl, SelectionDAG &DAG,
1472                                     const CCValAssign &VA,
1473                                     ISD::ArgFlagsTy Flags) const {
1474   unsigned LocMemOffset = VA.getLocMemOffset();
1475   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1476   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1477                        StackPtr, PtrOff);
1478   return DAG.getStore(
1479       Chain, dl, Arg, PtrOff,
1480       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1481       false, false, 0);
1482 }
1483
1484 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1485                                          SDValue Chain, SDValue &Arg,
1486                                          RegsToPassVector &RegsToPass,
1487                                          CCValAssign &VA, CCValAssign &NextVA,
1488                                          SDValue &StackPtr,
1489                                          SmallVectorImpl<SDValue> &MemOpChains,
1490                                          ISD::ArgFlagsTy Flags) const {
1491
1492   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1493                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1494   unsigned id = Subtarget->isLittle() ? 0 : 1;
1495   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1496
1497   if (NextVA.isRegLoc())
1498     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1499   else {
1500     assert(NextVA.isMemLoc());
1501     if (!StackPtr.getNode())
1502       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1503                                     getPointerTy(DAG.getDataLayout()));
1504
1505     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1506                                            dl, DAG, NextVA,
1507                                            Flags));
1508   }
1509 }
1510
1511 /// LowerCall - Lowering a call into a callseq_start <-
1512 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1513 /// nodes.
1514 SDValue
1515 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1516                              SmallVectorImpl<SDValue> &InVals) const {
1517   SelectionDAG &DAG                     = CLI.DAG;
1518   SDLoc &dl                             = CLI.DL;
1519   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1520   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1521   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1522   SDValue Chain                         = CLI.Chain;
1523   SDValue Callee                        = CLI.Callee;
1524   bool &isTailCall                      = CLI.IsTailCall;
1525   CallingConv::ID CallConv              = CLI.CallConv;
1526   bool doesNotRet                       = CLI.DoesNotReturn;
1527   bool isVarArg                         = CLI.IsVarArg;
1528
1529   MachineFunction &MF = DAG.getMachineFunction();
1530   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1531   bool isThisReturn   = false;
1532   bool isSibCall      = false;
1533   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1534
1535   // Disable tail calls if they're not supported.
1536   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1537     isTailCall = false;
1538
1539   if (isTailCall) {
1540     // Check if it's really possible to do a tail call.
1541     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1542                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1543                                                    Outs, OutVals, Ins, DAG);
1544     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1545       report_fatal_error("failed to perform tail call elimination on a call "
1546                          "site marked musttail");
1547     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1548     // detected sibcalls.
1549     if (isTailCall) {
1550       ++NumTailCalls;
1551       isSibCall = true;
1552     }
1553   }
1554
1555   // Analyze operands of the call, assigning locations to each operand.
1556   SmallVector<CCValAssign, 16> ArgLocs;
1557   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1558                     *DAG.getContext(), Call);
1559   CCInfo.AnalyzeCallOperands(Outs,
1560                              CCAssignFnForNode(CallConv, /* Return*/ false,
1561                                                isVarArg));
1562
1563   // Get a count of how many bytes are to be pushed on the stack.
1564   unsigned NumBytes = CCInfo.getNextStackOffset();
1565
1566   // For tail calls, memory operands are available in our caller's stack.
1567   if (isSibCall)
1568     NumBytes = 0;
1569
1570   // Adjust the stack pointer for the new arguments...
1571   // These operations are automatically eliminated by the prolog/epilog pass
1572   if (!isSibCall)
1573     Chain = DAG.getCALLSEQ_START(Chain,
1574                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1575
1576   SDValue StackPtr =
1577       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1578
1579   RegsToPassVector RegsToPass;
1580   SmallVector<SDValue, 8> MemOpChains;
1581
1582   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1583   // of tail call optimization, arguments are handled later.
1584   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1585        i != e;
1586        ++i, ++realArgIdx) {
1587     CCValAssign &VA = ArgLocs[i];
1588     SDValue Arg = OutVals[realArgIdx];
1589     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1590     bool isByVal = Flags.isByVal();
1591
1592     // Promote the value if needed.
1593     switch (VA.getLocInfo()) {
1594     default: llvm_unreachable("Unknown loc info!");
1595     case CCValAssign::Full: break;
1596     case CCValAssign::SExt:
1597       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1598       break;
1599     case CCValAssign::ZExt:
1600       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1601       break;
1602     case CCValAssign::AExt:
1603       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1604       break;
1605     case CCValAssign::BCvt:
1606       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1607       break;
1608     }
1609
1610     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1611     if (VA.needsCustom()) {
1612       if (VA.getLocVT() == MVT::v2f64) {
1613         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1614                                   DAG.getConstant(0, dl, MVT::i32));
1615         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1616                                   DAG.getConstant(1, dl, MVT::i32));
1617
1618         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1619                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1620
1621         VA = ArgLocs[++i]; // skip ahead to next loc
1622         if (VA.isRegLoc()) {
1623           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1624                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1625         } else {
1626           assert(VA.isMemLoc());
1627
1628           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1629                                                  dl, DAG, VA, Flags));
1630         }
1631       } else {
1632         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1633                          StackPtr, MemOpChains, Flags);
1634       }
1635     } else if (VA.isRegLoc()) {
1636       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1637         assert(VA.getLocVT() == MVT::i32 &&
1638                "unexpected calling convention register assignment");
1639         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1640                "unexpected use of 'returned'");
1641         isThisReturn = true;
1642       }
1643       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1644     } else if (isByVal) {
1645       assert(VA.isMemLoc());
1646       unsigned offset = 0;
1647
1648       // True if this byval aggregate will be split between registers
1649       // and memory.
1650       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1651       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1652
1653       if (CurByValIdx < ByValArgsCount) {
1654
1655         unsigned RegBegin, RegEnd;
1656         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1657
1658         EVT PtrVT =
1659             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1660         unsigned int i, j;
1661         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1662           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1663           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1664           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1665                                      MachinePointerInfo(),
1666                                      false, false, false,
1667                                      DAG.InferPtrAlignment(AddArg));
1668           MemOpChains.push_back(Load.getValue(1));
1669           RegsToPass.push_back(std::make_pair(j, Load));
1670         }
1671
1672         // If parameter size outsides register area, "offset" value
1673         // helps us to calculate stack slot for remained part properly.
1674         offset = RegEnd - RegBegin;
1675
1676         CCInfo.nextInRegsParam();
1677       }
1678
1679       if (Flags.getByValSize() > 4*offset) {
1680         auto PtrVT = getPointerTy(DAG.getDataLayout());
1681         unsigned LocMemOffset = VA.getLocMemOffset();
1682         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1683         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1684         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1685         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1686         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1687                                            MVT::i32);
1688         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1689                                             MVT::i32);
1690
1691         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1692         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1693         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1694                                           Ops));
1695       }
1696     } else if (!isSibCall) {
1697       assert(VA.isMemLoc());
1698
1699       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1700                                              dl, DAG, VA, Flags));
1701     }
1702   }
1703
1704   if (!MemOpChains.empty())
1705     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1706
1707   // Build a sequence of copy-to-reg nodes chained together with token chain
1708   // and flag operands which copy the outgoing args into the appropriate regs.
1709   SDValue InFlag;
1710   // Tail call byval lowering might overwrite argument registers so in case of
1711   // tail call optimization the copies to registers are lowered later.
1712   if (!isTailCall)
1713     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1714       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1715                                RegsToPass[i].second, InFlag);
1716       InFlag = Chain.getValue(1);
1717     }
1718
1719   // For tail calls lower the arguments to the 'real' stack slot.
1720   if (isTailCall) {
1721     // Force all the incoming stack arguments to be loaded from the stack
1722     // before any new outgoing arguments are stored to the stack, because the
1723     // outgoing stack slots may alias the incoming argument stack slots, and
1724     // the alias isn't otherwise explicit. This is slightly more conservative
1725     // than necessary, because it means that each store effectively depends
1726     // on every argument instead of just those arguments it would clobber.
1727
1728     // Do not flag preceding copytoreg stuff together with the following stuff.
1729     InFlag = SDValue();
1730     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1731       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1732                                RegsToPass[i].second, InFlag);
1733       InFlag = Chain.getValue(1);
1734     }
1735     InFlag = SDValue();
1736   }
1737
1738   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1739   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1740   // node so that legalize doesn't hack it.
1741   bool isDirect = false;
1742   bool isARMFunc = false;
1743   bool isLocalARMFunc = false;
1744   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1745   auto PtrVt = getPointerTy(DAG.getDataLayout());
1746
1747   if (Subtarget->genLongCalls()) {
1748     assert((Subtarget->isTargetWindows() ||
1749             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1750            "long-calls with non-static relocation model!");
1751     // Handle a global address or an external symbol. If it's not one of
1752     // those, the target's already in a register, so we don't need to do
1753     // anything extra.
1754     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1755       const GlobalValue *GV = G->getGlobal();
1756       // Create a constant pool entry for the callee address
1757       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1758       ARMConstantPoolValue *CPV =
1759         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1760
1761       // Get the address of the callee into a register
1762       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1763       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1764       Callee = DAG.getLoad(
1765           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1766           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1767           false, false, 0);
1768     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1769       const char *Sym = S->getSymbol();
1770
1771       // Create a constant pool entry for the callee address
1772       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1773       ARMConstantPoolValue *CPV =
1774         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1775                                       ARMPCLabelIndex, 0);
1776       // Get the address of the callee into a register
1777       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1778       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1779       Callee = DAG.getLoad(
1780           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1781           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1782           false, false, 0);
1783     }
1784   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1785     const GlobalValue *GV = G->getGlobal();
1786     isDirect = true;
1787     bool isDef = GV->isStrongDefinitionForLinker();
1788     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1789                    getTargetMachine().getRelocationModel() != Reloc::Static;
1790     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1791     // ARM call to a local ARM function is predicable.
1792     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1793     // tBX takes a register source operand.
1794     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1795       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1796       Callee = DAG.getNode(
1797           ARMISD::WrapperPIC, dl, PtrVt,
1798           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1799       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1800                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1801                            false, false, true, 0);
1802     } else if (Subtarget->isTargetCOFF()) {
1803       assert(Subtarget->isTargetWindows() &&
1804              "Windows is the only supported COFF target");
1805       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1806                                  ? ARMII::MO_DLLIMPORT
1807                                  : ARMII::MO_NO_FLAG;
1808       Callee =
1809           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1810       if (GV->hasDLLImportStorageClass())
1811         Callee =
1812             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1813                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1814                         MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1815                         false, false, false, 0);
1816     } else {
1817       // On ELF targets for PIC code, direct calls should go through the PLT
1818       unsigned OpFlags = 0;
1819       if (Subtarget->isTargetELF() &&
1820           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1821         OpFlags = ARMII::MO_PLT;
1822       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1823     }
1824   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1825     isDirect = true;
1826     bool isStub = Subtarget->isTargetMachO() &&
1827                   getTargetMachine().getRelocationModel() != Reloc::Static;
1828     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1829     // tBX takes a register source operand.
1830     const char *Sym = S->getSymbol();
1831     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1832       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1833       ARMConstantPoolValue *CPV =
1834         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1835                                       ARMPCLabelIndex, 4);
1836       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1837       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1838       Callee = DAG.getLoad(
1839           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1840           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1841           false, false, 0);
1842       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1843       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1844     } else {
1845       unsigned OpFlags = 0;
1846       // On ELF targets for PIC code, direct calls should go through the PLT
1847       if (Subtarget->isTargetELF() &&
1848                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1849         OpFlags = ARMII::MO_PLT;
1850       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1851     }
1852   }
1853
1854   // FIXME: handle tail calls differently.
1855   unsigned CallOpc;
1856   if (Subtarget->isThumb()) {
1857     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1858       CallOpc = ARMISD::CALL_NOLINK;
1859     else
1860       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1861   } else {
1862     if (!isDirect && !Subtarget->hasV5TOps())
1863       CallOpc = ARMISD::CALL_NOLINK;
1864     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1865              // Emit regular call when code size is the priority
1866              !MF.getFunction()->optForMinSize())
1867       // "mov lr, pc; b _foo" to avoid confusing the RSP
1868       CallOpc = ARMISD::CALL_NOLINK;
1869     else
1870       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1871   }
1872
1873   std::vector<SDValue> Ops;
1874   Ops.push_back(Chain);
1875   Ops.push_back(Callee);
1876
1877   // Add argument registers to the end of the list so that they are known live
1878   // into the call.
1879   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1880     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1881                                   RegsToPass[i].second.getValueType()));
1882
1883   // Add a register mask operand representing the call-preserved registers.
1884   if (!isTailCall) {
1885     const uint32_t *Mask;
1886     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1887     if (isThisReturn) {
1888       // For 'this' returns, use the R0-preserving mask if applicable
1889       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1890       if (!Mask) {
1891         // Set isThisReturn to false if the calling convention is not one that
1892         // allows 'returned' to be modeled in this way, so LowerCallResult does
1893         // not try to pass 'this' straight through
1894         isThisReturn = false;
1895         Mask = ARI->getCallPreservedMask(MF, CallConv);
1896       }
1897     } else
1898       Mask = ARI->getCallPreservedMask(MF, CallConv);
1899
1900     assert(Mask && "Missing call preserved mask for calling convention");
1901     Ops.push_back(DAG.getRegisterMask(Mask));
1902   }
1903
1904   if (InFlag.getNode())
1905     Ops.push_back(InFlag);
1906
1907   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1908   if (isTailCall) {
1909     MF.getFrameInfo()->setHasTailCall();
1910     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1911   }
1912
1913   // Returns a chain and a flag for retval copy to use.
1914   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1915   InFlag = Chain.getValue(1);
1916
1917   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1918                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1919   if (!Ins.empty())
1920     InFlag = Chain.getValue(1);
1921
1922   // Handle result values, copying them out of physregs into vregs that we
1923   // return.
1924   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1925                          InVals, isThisReturn,
1926                          isThisReturn ? OutVals[0] : SDValue());
1927 }
1928
1929 /// HandleByVal - Every parameter *after* a byval parameter is passed
1930 /// on the stack.  Remember the next parameter register to allocate,
1931 /// and then confiscate the rest of the parameter registers to insure
1932 /// this.
1933 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1934                                     unsigned Align) const {
1935   assert((State->getCallOrPrologue() == Prologue ||
1936           State->getCallOrPrologue() == Call) &&
1937          "unhandled ParmContext");
1938
1939   // Byval (as with any stack) slots are always at least 4 byte aligned.
1940   Align = std::max(Align, 4U);
1941
1942   unsigned Reg = State->AllocateReg(GPRArgRegs);
1943   if (!Reg)
1944     return;
1945
1946   unsigned AlignInRegs = Align / 4;
1947   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1948   for (unsigned i = 0; i < Waste; ++i)
1949     Reg = State->AllocateReg(GPRArgRegs);
1950
1951   if (!Reg)
1952     return;
1953
1954   unsigned Excess = 4 * (ARM::R4 - Reg);
1955
1956   // Special case when NSAA != SP and parameter size greater than size of
1957   // all remained GPR regs. In that case we can't split parameter, we must
1958   // send it to stack. We also must set NCRN to R4, so waste all
1959   // remained registers.
1960   const unsigned NSAAOffset = State->getNextStackOffset();
1961   if (NSAAOffset != 0 && Size > Excess) {
1962     while (State->AllocateReg(GPRArgRegs))
1963       ;
1964     return;
1965   }
1966
1967   // First register for byval parameter is the first register that wasn't
1968   // allocated before this method call, so it would be "reg".
1969   // If parameter is small enough to be saved in range [reg, r4), then
1970   // the end (first after last) register would be reg + param-size-in-regs,
1971   // else parameter would be splitted between registers and stack,
1972   // end register would be r4 in this case.
1973   unsigned ByValRegBegin = Reg;
1974   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1975   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1976   // Note, first register is allocated in the beginning of function already,
1977   // allocate remained amount of registers we need.
1978   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1979     State->AllocateReg(GPRArgRegs);
1980   // A byval parameter that is split between registers and memory needs its
1981   // size truncated here.
1982   // In the case where the entire structure fits in registers, we set the
1983   // size in memory to zero.
1984   Size = std::max<int>(Size - Excess, 0);
1985 }
1986
1987 /// MatchingStackOffset - Return true if the given stack call argument is
1988 /// already available in the same position (relatively) of the caller's
1989 /// incoming argument stack.
1990 static
1991 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1992                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1993                          const TargetInstrInfo *TII) {
1994   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1995   int FI = INT_MAX;
1996   if (Arg.getOpcode() == ISD::CopyFromReg) {
1997     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1998     if (!TargetRegisterInfo::isVirtualRegister(VR))
1999       return false;
2000     MachineInstr *Def = MRI->getVRegDef(VR);
2001     if (!Def)
2002       return false;
2003     if (!Flags.isByVal()) {
2004       if (!TII->isLoadFromStackSlot(Def, FI))
2005         return false;
2006     } else {
2007       return false;
2008     }
2009   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2010     if (Flags.isByVal())
2011       // ByVal argument is passed in as a pointer but it's now being
2012       // dereferenced. e.g.
2013       // define @foo(%struct.X* %A) {
2014       //   tail call @bar(%struct.X* byval %A)
2015       // }
2016       return false;
2017     SDValue Ptr = Ld->getBasePtr();
2018     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2019     if (!FINode)
2020       return false;
2021     FI = FINode->getIndex();
2022   } else
2023     return false;
2024
2025   assert(FI != INT_MAX);
2026   if (!MFI->isFixedObjectIndex(FI))
2027     return false;
2028   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2029 }
2030
2031 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2032 /// for tail call optimization. Targets which want to do tail call
2033 /// optimization should implement this function.
2034 bool
2035 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2036                                                      CallingConv::ID CalleeCC,
2037                                                      bool isVarArg,
2038                                                      bool isCalleeStructRet,
2039                                                      bool isCallerStructRet,
2040                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2041                                     const SmallVectorImpl<SDValue> &OutVals,
2042                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2043                                                      SelectionDAG& DAG) const {
2044   const Function *CallerF = DAG.getMachineFunction().getFunction();
2045   CallingConv::ID CallerCC = CallerF->getCallingConv();
2046   bool CCMatch = CallerCC == CalleeCC;
2047
2048   // Look for obvious safe cases to perform tail call optimization that do not
2049   // require ABI changes. This is what gcc calls sibcall.
2050
2051   // Do not sibcall optimize vararg calls unless the call site is not passing
2052   // any arguments.
2053   if (isVarArg && !Outs.empty())
2054     return false;
2055
2056   // Exception-handling functions need a special set of instructions to indicate
2057   // a return to the hardware. Tail-calling another function would probably
2058   // break this.
2059   if (CallerF->hasFnAttribute("interrupt"))
2060     return false;
2061
2062   // Also avoid sibcall optimization if either caller or callee uses struct
2063   // return semantics.
2064   if (isCalleeStructRet || isCallerStructRet)
2065     return false;
2066
2067   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2068   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2069   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2070   // support in the assembler and linker to be used. This would need to be
2071   // fixed to fully support tail calls in Thumb1.
2072   //
2073   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2074   // LR.  This means if we need to reload LR, it takes an extra instructions,
2075   // which outweighs the value of the tail call; but here we don't know yet
2076   // whether LR is going to be used.  Probably the right approach is to
2077   // generate the tail call here and turn it back into CALL/RET in
2078   // emitEpilogue if LR is used.
2079
2080   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2081   // but we need to make sure there are enough registers; the only valid
2082   // registers are the 4 used for parameters.  We don't currently do this
2083   // case.
2084   if (Subtarget->isThumb1Only())
2085     return false;
2086
2087   // Externally-defined functions with weak linkage should not be
2088   // tail-called on ARM when the OS does not support dynamic
2089   // pre-emption of symbols, as the AAELF spec requires normal calls
2090   // to undefined weak functions to be replaced with a NOP or jump to the
2091   // next instruction. The behaviour of branch instructions in this
2092   // situation (as used for tail calls) is implementation-defined, so we
2093   // cannot rely on the linker replacing the tail call with a return.
2094   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2095     const GlobalValue *GV = G->getGlobal();
2096     const Triple &TT = getTargetMachine().getTargetTriple();
2097     if (GV->hasExternalWeakLinkage() &&
2098         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2099       return false;
2100   }
2101
2102   // If the calling conventions do not match, then we'd better make sure the
2103   // results are returned in the same way as what the caller expects.
2104   if (!CCMatch) {
2105     SmallVector<CCValAssign, 16> RVLocs1;
2106     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2107                        *DAG.getContext(), Call);
2108     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2109
2110     SmallVector<CCValAssign, 16> RVLocs2;
2111     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2112                        *DAG.getContext(), Call);
2113     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2114
2115     if (RVLocs1.size() != RVLocs2.size())
2116       return false;
2117     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2118       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2119         return false;
2120       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2121         return false;
2122       if (RVLocs1[i].isRegLoc()) {
2123         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2124           return false;
2125       } else {
2126         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2127           return false;
2128       }
2129     }
2130   }
2131
2132   // If Caller's vararg or byval argument has been split between registers and
2133   // stack, do not perform tail call, since part of the argument is in caller's
2134   // local frame.
2135   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2136                                       getInfo<ARMFunctionInfo>();
2137   if (AFI_Caller->getArgRegsSaveSize())
2138     return false;
2139
2140   // If the callee takes no arguments then go on to check the results of the
2141   // call.
2142   if (!Outs.empty()) {
2143     // Check if stack adjustment is needed. For now, do not do this if any
2144     // argument is passed on the stack.
2145     SmallVector<CCValAssign, 16> ArgLocs;
2146     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2147                       *DAG.getContext(), Call);
2148     CCInfo.AnalyzeCallOperands(Outs,
2149                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2150     if (CCInfo.getNextStackOffset()) {
2151       MachineFunction &MF = DAG.getMachineFunction();
2152
2153       // Check if the arguments are already laid out in the right way as
2154       // the caller's fixed stack objects.
2155       MachineFrameInfo *MFI = MF.getFrameInfo();
2156       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2157       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2158       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2159            i != e;
2160            ++i, ++realArgIdx) {
2161         CCValAssign &VA = ArgLocs[i];
2162         EVT RegVT = VA.getLocVT();
2163         SDValue Arg = OutVals[realArgIdx];
2164         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2165         if (VA.getLocInfo() == CCValAssign::Indirect)
2166           return false;
2167         if (VA.needsCustom()) {
2168           // f64 and vector types are split into multiple registers or
2169           // register/stack-slot combinations.  The types will not match
2170           // the registers; give up on memory f64 refs until we figure
2171           // out what to do about this.
2172           if (!VA.isRegLoc())
2173             return false;
2174           if (!ArgLocs[++i].isRegLoc())
2175             return false;
2176           if (RegVT == MVT::v2f64) {
2177             if (!ArgLocs[++i].isRegLoc())
2178               return false;
2179             if (!ArgLocs[++i].isRegLoc())
2180               return false;
2181           }
2182         } else if (!VA.isRegLoc()) {
2183           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2184                                    MFI, MRI, TII))
2185             return false;
2186         }
2187       }
2188     }
2189   }
2190
2191   return true;
2192 }
2193
2194 bool
2195 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2196                                   MachineFunction &MF, bool isVarArg,
2197                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2198                                   LLVMContext &Context) const {
2199   SmallVector<CCValAssign, 16> RVLocs;
2200   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2201   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2202                                                     isVarArg));
2203 }
2204
2205 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2206                                     SDLoc DL, SelectionDAG &DAG) {
2207   const MachineFunction &MF = DAG.getMachineFunction();
2208   const Function *F = MF.getFunction();
2209
2210   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2211
2212   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2213   // version of the "preferred return address". These offsets affect the return
2214   // instruction if this is a return from PL1 without hypervisor extensions.
2215   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2216   //    SWI:     0      "subs pc, lr, #0"
2217   //    ABORT:   +4     "subs pc, lr, #4"
2218   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2219   // UNDEF varies depending on where the exception came from ARM or Thumb
2220   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2221
2222   int64_t LROffset;
2223   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2224       IntKind == "ABORT")
2225     LROffset = 4;
2226   else if (IntKind == "SWI" || IntKind == "UNDEF")
2227     LROffset = 0;
2228   else
2229     report_fatal_error("Unsupported interrupt attribute. If present, value "
2230                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2231
2232   RetOps.insert(RetOps.begin() + 1,
2233                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2234
2235   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2236 }
2237
2238 SDValue
2239 ARMTargetLowering::LowerReturn(SDValue Chain,
2240                                CallingConv::ID CallConv, bool isVarArg,
2241                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2242                                const SmallVectorImpl<SDValue> &OutVals,
2243                                SDLoc dl, SelectionDAG &DAG) const {
2244
2245   // CCValAssign - represent the assignment of the return value to a location.
2246   SmallVector<CCValAssign, 16> RVLocs;
2247
2248   // CCState - Info about the registers and stack slots.
2249   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2250                     *DAG.getContext(), Call);
2251
2252   // Analyze outgoing return values.
2253   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2254                                                isVarArg));
2255
2256   SDValue Flag;
2257   SmallVector<SDValue, 4> RetOps;
2258   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2259   bool isLittleEndian = Subtarget->isLittle();
2260
2261   MachineFunction &MF = DAG.getMachineFunction();
2262   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2263   AFI->setReturnRegsCount(RVLocs.size());
2264
2265   // Copy the result values into the output registers.
2266   for (unsigned i = 0, realRVLocIdx = 0;
2267        i != RVLocs.size();
2268        ++i, ++realRVLocIdx) {
2269     CCValAssign &VA = RVLocs[i];
2270     assert(VA.isRegLoc() && "Can only return in registers!");
2271
2272     SDValue Arg = OutVals[realRVLocIdx];
2273
2274     switch (VA.getLocInfo()) {
2275     default: llvm_unreachable("Unknown loc info!");
2276     case CCValAssign::Full: break;
2277     case CCValAssign::BCvt:
2278       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2279       break;
2280     }
2281
2282     if (VA.needsCustom()) {
2283       if (VA.getLocVT() == MVT::v2f64) {
2284         // Extract the first half and return it in two registers.
2285         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2286                                    DAG.getConstant(0, dl, MVT::i32));
2287         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2288                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2289
2290         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2291                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
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         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2297                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2298                                  Flag);
2299         Flag = Chain.getValue(1);
2300         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2301         VA = RVLocs[++i]; // skip ahead to next loc
2302
2303         // Extract the 2nd half and fall through to handle it as an f64 value.
2304         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2305                           DAG.getConstant(1, dl, MVT::i32));
2306       }
2307       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2308       // available.
2309       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2310                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2311       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2312                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2313                                Flag);
2314       Flag = Chain.getValue(1);
2315       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2316       VA = RVLocs[++i]; // skip ahead to next loc
2317       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2318                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2319                                Flag);
2320     } else
2321       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2322
2323     // Guarantee that all emitted copies are
2324     // stuck together, avoiding something bad.
2325     Flag = Chain.getValue(1);
2326     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2327   }
2328
2329   // Update chain and glue.
2330   RetOps[0] = Chain;
2331   if (Flag.getNode())
2332     RetOps.push_back(Flag);
2333
2334   // CPUs which aren't M-class use a special sequence to return from
2335   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2336   // though we use "subs pc, lr, #N").
2337   //
2338   // M-class CPUs actually use a normal return sequence with a special
2339   // (hardware-provided) value in LR, so the normal code path works.
2340   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2341       !Subtarget->isMClass()) {
2342     if (Subtarget->isThumb1Only())
2343       report_fatal_error("interrupt attribute is not supported in Thumb1");
2344     return LowerInterruptReturn(RetOps, dl, DAG);
2345   }
2346
2347   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2348 }
2349
2350 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2351   if (N->getNumValues() != 1)
2352     return false;
2353   if (!N->hasNUsesOfValue(1, 0))
2354     return false;
2355
2356   SDValue TCChain = Chain;
2357   SDNode *Copy = *N->use_begin();
2358   if (Copy->getOpcode() == ISD::CopyToReg) {
2359     // If the copy has a glue operand, we conservatively assume it isn't safe to
2360     // perform a tail call.
2361     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2362       return false;
2363     TCChain = Copy->getOperand(0);
2364   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2365     SDNode *VMov = Copy;
2366     // f64 returned in a pair of GPRs.
2367     SmallPtrSet<SDNode*, 2> Copies;
2368     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2369          UI != UE; ++UI) {
2370       if (UI->getOpcode() != ISD::CopyToReg)
2371         return false;
2372       Copies.insert(*UI);
2373     }
2374     if (Copies.size() > 2)
2375       return false;
2376
2377     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2378          UI != UE; ++UI) {
2379       SDValue UseChain = UI->getOperand(0);
2380       if (Copies.count(UseChain.getNode()))
2381         // Second CopyToReg
2382         Copy = *UI;
2383       else {
2384         // We are at the top of this chain.
2385         // If the copy has a glue operand, we conservatively assume it
2386         // isn't safe to perform a tail call.
2387         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2388           return false;
2389         // First CopyToReg
2390         TCChain = UseChain;
2391       }
2392     }
2393   } else if (Copy->getOpcode() == ISD::BITCAST) {
2394     // f32 returned in a single GPR.
2395     if (!Copy->hasOneUse())
2396       return false;
2397     Copy = *Copy->use_begin();
2398     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2399       return false;
2400     // If the copy has a glue operand, we conservatively assume it isn't safe to
2401     // perform a tail call.
2402     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2403       return false;
2404     TCChain = Copy->getOperand(0);
2405   } else {
2406     return false;
2407   }
2408
2409   bool HasRet = false;
2410   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2411        UI != UE; ++UI) {
2412     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2413         UI->getOpcode() != ARMISD::INTRET_FLAG)
2414       return false;
2415     HasRet = true;
2416   }
2417
2418   if (!HasRet)
2419     return false;
2420
2421   Chain = TCChain;
2422   return true;
2423 }
2424
2425 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2426   if (!Subtarget->supportsTailCall())
2427     return false;
2428
2429   auto Attr =
2430       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2431   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2432     return false;
2433
2434   return !Subtarget->isThumb1Only();
2435 }
2436
2437 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2438 // and pass the lower and high parts through.
2439 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2440   SDLoc DL(Op);
2441   SDValue WriteValue = Op->getOperand(2);
2442
2443   // This function is only supposed to be called for i64 type argument.
2444   assert(WriteValue.getValueType() == MVT::i64
2445           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2446
2447   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2448                            DAG.getConstant(0, DL, MVT::i32));
2449   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2450                            DAG.getConstant(1, DL, MVT::i32));
2451   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2452   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2453 }
2454
2455 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2456 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2457 // one of the above mentioned nodes. It has to be wrapped because otherwise
2458 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2459 // be used to form addressing mode. These wrapped nodes will be selected
2460 // into MOVi.
2461 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2462   EVT PtrVT = Op.getValueType();
2463   // FIXME there is no actual debug info here
2464   SDLoc dl(Op);
2465   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2466   SDValue Res;
2467   if (CP->isMachineConstantPoolEntry())
2468     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2469                                     CP->getAlignment());
2470   else
2471     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2472                                     CP->getAlignment());
2473   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2474 }
2475
2476 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2477   return MachineJumpTableInfo::EK_Inline;
2478 }
2479
2480 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2481                                              SelectionDAG &DAG) const {
2482   MachineFunction &MF = DAG.getMachineFunction();
2483   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2484   unsigned ARMPCLabelIndex = 0;
2485   SDLoc DL(Op);
2486   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2487   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2488   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2489   SDValue CPAddr;
2490   if (RelocM == Reloc::Static) {
2491     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2492   } else {
2493     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2494     ARMPCLabelIndex = AFI->createPICLabelUId();
2495     ARMConstantPoolValue *CPV =
2496       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2497                                       ARMCP::CPBlockAddress, PCAdj);
2498     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2499   }
2500   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2501   SDValue Result =
2502       DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2503                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2504                   false, false, false, 0);
2505   if (RelocM == Reloc::Static)
2506     return Result;
2507   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2508   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2509 }
2510
2511 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2512 SDValue
2513 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2514                                                  SelectionDAG &DAG) const {
2515   SDLoc dl(GA);
2516   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2517   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2518   MachineFunction &MF = DAG.getMachineFunction();
2519   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2520   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2521   ARMConstantPoolValue *CPV =
2522     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2523                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2524   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2525   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2526   Argument =
2527       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2528                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2529                   false, false, false, 0);
2530   SDValue Chain = Argument.getValue(1);
2531
2532   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2533   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2534
2535   // call __tls_get_addr.
2536   ArgListTy Args;
2537   ArgListEntry Entry;
2538   Entry.Node = Argument;
2539   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2540   Args.push_back(Entry);
2541
2542   // FIXME: is there useful debug info available here?
2543   TargetLowering::CallLoweringInfo CLI(DAG);
2544   CLI.setDebugLoc(dl).setChain(Chain)
2545     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2546                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2547                0);
2548
2549   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2550   return CallResult.first;
2551 }
2552
2553 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2554 // "local exec" model.
2555 SDValue
2556 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2557                                         SelectionDAG &DAG,
2558                                         TLSModel::Model model) const {
2559   const GlobalValue *GV = GA->getGlobal();
2560   SDLoc dl(GA);
2561   SDValue Offset;
2562   SDValue Chain = DAG.getEntryNode();
2563   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2564   // Get the Thread Pointer
2565   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2566
2567   if (model == TLSModel::InitialExec) {
2568     MachineFunction &MF = DAG.getMachineFunction();
2569     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2570     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2571     // Initial exec model.
2572     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2573     ARMConstantPoolValue *CPV =
2574       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2575                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2576                                       true);
2577     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2578     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2579     Offset = DAG.getLoad(
2580         PtrVT, dl, Chain, Offset,
2581         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2582         false, false, 0);
2583     Chain = Offset.getValue(1);
2584
2585     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2586     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2587
2588     Offset = DAG.getLoad(
2589         PtrVT, dl, Chain, Offset,
2590         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2591         false, false, 0);
2592   } else {
2593     // local exec model
2594     assert(model == TLSModel::LocalExec);
2595     ARMConstantPoolValue *CPV =
2596       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2597     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2598     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2599     Offset = DAG.getLoad(
2600         PtrVT, dl, Chain, Offset,
2601         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2602         false, false, 0);
2603   }
2604
2605   // The address of the thread local variable is the add of the thread
2606   // pointer with the offset of the variable.
2607   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2608 }
2609
2610 SDValue
2611 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2612   // TODO: implement the "local dynamic" model
2613   assert(Subtarget->isTargetELF() &&
2614          "TLS not implemented for non-ELF targets");
2615   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2616   if (DAG.getTarget().Options.EmulatedTLS)
2617     return LowerToTLSEmulatedModel(GA, DAG);
2618
2619   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2620
2621   switch (model) {
2622     case TLSModel::GeneralDynamic:
2623     case TLSModel::LocalDynamic:
2624       return LowerToTLSGeneralDynamicModel(GA, DAG);
2625     case TLSModel::InitialExec:
2626     case TLSModel::LocalExec:
2627       return LowerToTLSExecModels(GA, DAG, model);
2628   }
2629   llvm_unreachable("bogus TLS model");
2630 }
2631
2632 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2633                                                  SelectionDAG &DAG) const {
2634   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2635   SDLoc dl(Op);
2636   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2637   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2638     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2639     ARMConstantPoolValue *CPV =
2640       ARMConstantPoolConstant::Create(GV,
2641                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2642     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2643     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2644     SDValue Result = DAG.getLoad(
2645         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2646         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2647         false, false, 0);
2648     SDValue Chain = Result.getValue(1);
2649     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2650     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2651     if (!UseGOTOFF)
2652       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2653                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2654                            false, false, false, 0);
2655     return Result;
2656   }
2657
2658   // If we have T2 ops, we can materialize the address directly via movt/movw
2659   // pair. This is always cheaper.
2660   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2661     ++NumMovwMovt;
2662     // FIXME: Once remat is capable of dealing with instructions with register
2663     // operands, expand this into two nodes.
2664     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2665                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2666   } else {
2667     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2668     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2669     return DAG.getLoad(
2670         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2671         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2672         false, false, 0);
2673   }
2674 }
2675
2676 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2677                                                     SelectionDAG &DAG) const {
2678   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2679   SDLoc dl(Op);
2680   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2681   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2682
2683   if (Subtarget->useMovt(DAG.getMachineFunction()))
2684     ++NumMovwMovt;
2685
2686   // FIXME: Once remat is capable of dealing with instructions with register
2687   // operands, expand this into multiple nodes
2688   unsigned Wrapper =
2689       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2690
2691   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2692   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2693
2694   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2695     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2696                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2697                          false, false, false, 0);
2698   return Result;
2699 }
2700
2701 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2702                                                      SelectionDAG &DAG) const {
2703   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2704   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2705          "Windows on ARM expects to use movw/movt");
2706
2707   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2708   const ARMII::TOF TargetFlags =
2709     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2710   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2711   SDValue Result;
2712   SDLoc DL(Op);
2713
2714   ++NumMovwMovt;
2715
2716   // FIXME: Once remat is capable of dealing with instructions with register
2717   // operands, expand this into two nodes.
2718   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2719                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2720                                                   TargetFlags));
2721   if (GV->hasDLLImportStorageClass())
2722     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2723                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2724                          false, false, false, 0);
2725   return Result;
2726 }
2727
2728 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2729                                                     SelectionDAG &DAG) const {
2730   assert(Subtarget->isTargetELF() &&
2731          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2732   MachineFunction &MF = DAG.getMachineFunction();
2733   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2734   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2735   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2736   SDLoc dl(Op);
2737   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2738   ARMConstantPoolValue *CPV =
2739     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2740                                   ARMPCLabelIndex, PCAdj);
2741   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2742   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2743   SDValue Result =
2744       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2745                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2746                   false, false, false, 0);
2747   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2748   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2749 }
2750
2751 SDValue
2752 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2753   SDLoc dl(Op);
2754   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2755   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2756                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2757                      Op.getOperand(1), Val);
2758 }
2759
2760 SDValue
2761 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2762   SDLoc dl(Op);
2763   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2764                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2765 }
2766
2767 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2768                                                       SelectionDAG &DAG) const {
2769   SDLoc dl(Op);
2770   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2771                      Op.getOperand(0));
2772 }
2773
2774 SDValue
2775 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2776                                           const ARMSubtarget *Subtarget) const {
2777   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2778   SDLoc dl(Op);
2779   switch (IntNo) {
2780   default: return SDValue();    // Don't custom lower most intrinsics.
2781   case Intrinsic::arm_rbit: {
2782     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2783            "RBIT intrinsic must have i32 type!");
2784     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2785   }
2786   case Intrinsic::arm_thread_pointer: {
2787     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2788     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2789   }
2790   case Intrinsic::eh_sjlj_lsda: {
2791     MachineFunction &MF = DAG.getMachineFunction();
2792     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2793     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2794     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2795     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2796     SDValue CPAddr;
2797     unsigned PCAdj = (RelocM != Reloc::PIC_)
2798       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2799     ARMConstantPoolValue *CPV =
2800       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2801                                       ARMCP::CPLSDA, PCAdj);
2802     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2803     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2804     SDValue Result = DAG.getLoad(
2805         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2806         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2807         false, false, 0);
2808
2809     if (RelocM == Reloc::PIC_) {
2810       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2811       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2812     }
2813     return Result;
2814   }
2815   case Intrinsic::arm_neon_vmulls:
2816   case Intrinsic::arm_neon_vmullu: {
2817     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2818       ? ARMISD::VMULLs : ARMISD::VMULLu;
2819     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2820                        Op.getOperand(1), Op.getOperand(2));
2821   }
2822   case Intrinsic::arm_neon_vminnm:
2823   case Intrinsic::arm_neon_vmaxnm: {
2824     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2825       ? ISD::FMINNUM : ISD::FMAXNUM;
2826     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2827                        Op.getOperand(1), Op.getOperand(2));
2828   }
2829   case Intrinsic::arm_neon_vminu:
2830   case Intrinsic::arm_neon_vmaxu: {
2831     if (Op.getValueType().isFloatingPoint())
2832       return SDValue();
2833     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2834       ? ISD::UMIN : ISD::UMAX;
2835     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2836                          Op.getOperand(1), Op.getOperand(2));
2837   }
2838   case Intrinsic::arm_neon_vmins:
2839   case Intrinsic::arm_neon_vmaxs: {
2840     // v{min,max}s is overloaded between signed integers and floats.
2841     if (!Op.getValueType().isFloatingPoint()) {
2842       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2843         ? ISD::SMIN : ISD::SMAX;
2844       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2845                          Op.getOperand(1), Op.getOperand(2));
2846     }
2847     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2848       ? ISD::FMINNAN : ISD::FMAXNAN;
2849     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2850                        Op.getOperand(1), Op.getOperand(2));
2851   }
2852   }
2853 }
2854
2855 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2856                                  const ARMSubtarget *Subtarget) {
2857   // FIXME: handle "fence singlethread" more efficiently.
2858   SDLoc dl(Op);
2859   if (!Subtarget->hasDataBarrier()) {
2860     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2861     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2862     // here.
2863     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2864            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2865     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2866                        DAG.getConstant(0, dl, MVT::i32));
2867   }
2868
2869   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2870   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2871   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2872   if (Subtarget->isMClass()) {
2873     // Only a full system barrier exists in the M-class architectures.
2874     Domain = ARM_MB::SY;
2875   } else if (Subtarget->isSwift() && Ord == Release) {
2876     // Swift happens to implement ISHST barriers in a way that's compatible with
2877     // Release semantics but weaker than ISH so we'd be fools not to use
2878     // it. Beware: other processors probably don't!
2879     Domain = ARM_MB::ISHST;
2880   }
2881
2882   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2883                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2884                      DAG.getConstant(Domain, dl, MVT::i32));
2885 }
2886
2887 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2888                              const ARMSubtarget *Subtarget) {
2889   // ARM pre v5TE and Thumb1 does not have preload instructions.
2890   if (!(Subtarget->isThumb2() ||
2891         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2892     // Just preserve the chain.
2893     return Op.getOperand(0);
2894
2895   SDLoc dl(Op);
2896   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2897   if (!isRead &&
2898       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2899     // ARMv7 with MP extension has PLDW.
2900     return Op.getOperand(0);
2901
2902   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2903   if (Subtarget->isThumb()) {
2904     // Invert the bits.
2905     isRead = ~isRead & 1;
2906     isData = ~isData & 1;
2907   }
2908
2909   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2910                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2911                      DAG.getConstant(isData, dl, MVT::i32));
2912 }
2913
2914 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2915   MachineFunction &MF = DAG.getMachineFunction();
2916   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2917
2918   // vastart just stores the address of the VarArgsFrameIndex slot into the
2919   // memory location argument.
2920   SDLoc dl(Op);
2921   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2922   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2923   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2924   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2925                       MachinePointerInfo(SV), false, false, 0);
2926 }
2927
2928 SDValue
2929 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2930                                         SDValue &Root, SelectionDAG &DAG,
2931                                         SDLoc dl) const {
2932   MachineFunction &MF = DAG.getMachineFunction();
2933   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2934
2935   const TargetRegisterClass *RC;
2936   if (AFI->isThumb1OnlyFunction())
2937     RC = &ARM::tGPRRegClass;
2938   else
2939     RC = &ARM::GPRRegClass;
2940
2941   // Transform the arguments stored in physical registers into virtual ones.
2942   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2943   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2944
2945   SDValue ArgValue2;
2946   if (NextVA.isMemLoc()) {
2947     MachineFrameInfo *MFI = MF.getFrameInfo();
2948     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2949
2950     // Create load node to retrieve arguments from the stack.
2951     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2952     ArgValue2 = DAG.getLoad(
2953         MVT::i32, dl, Root, FIN,
2954         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2955         false, false, 0);
2956   } else {
2957     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2958     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2959   }
2960   if (!Subtarget->isLittle())
2961     std::swap (ArgValue, ArgValue2);
2962   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2963 }
2964
2965 // The remaining GPRs hold either the beginning of variable-argument
2966 // data, or the beginning of an aggregate passed by value (usually
2967 // byval).  Either way, we allocate stack slots adjacent to the data
2968 // provided by our caller, and store the unallocated registers there.
2969 // If this is a variadic function, the va_list pointer will begin with
2970 // these values; otherwise, this reassembles a (byval) structure that
2971 // was split between registers and memory.
2972 // Return: The frame index registers were stored into.
2973 int
2974 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2975                                   SDLoc dl, SDValue &Chain,
2976                                   const Value *OrigArg,
2977                                   unsigned InRegsParamRecordIdx,
2978                                   int ArgOffset,
2979                                   unsigned ArgSize) const {
2980   // Currently, two use-cases possible:
2981   // Case #1. Non-var-args function, and we meet first byval parameter.
2982   //          Setup first unallocated register as first byval register;
2983   //          eat all remained registers
2984   //          (these two actions are performed by HandleByVal method).
2985   //          Then, here, we initialize stack frame with
2986   //          "store-reg" instructions.
2987   // Case #2. Var-args function, that doesn't contain byval parameters.
2988   //          The same: eat all remained unallocated registers,
2989   //          initialize stack frame.
2990
2991   MachineFunction &MF = DAG.getMachineFunction();
2992   MachineFrameInfo *MFI = MF.getFrameInfo();
2993   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2994   unsigned RBegin, REnd;
2995   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2996     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2997   } else {
2998     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2999     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3000     REnd = ARM::R4;
3001   }
3002
3003   if (REnd != RBegin)
3004     ArgOffset = -4 * (ARM::R4 - RBegin);
3005
3006   auto PtrVT = getPointerTy(DAG.getDataLayout());
3007   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3008   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3009
3010   SmallVector<SDValue, 4> MemOps;
3011   const TargetRegisterClass *RC =
3012       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3013
3014   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3015     unsigned VReg = MF.addLiveIn(Reg, RC);
3016     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3017     SDValue Store =
3018         DAG.getStore(Val.getValue(1), dl, Val, FIN,
3019                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3020     MemOps.push_back(Store);
3021     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3022   }
3023
3024   if (!MemOps.empty())
3025     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3026   return FrameIndex;
3027 }
3028
3029 // Setup stack frame, the va_list pointer will start from.
3030 void
3031 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3032                                         SDLoc dl, SDValue &Chain,
3033                                         unsigned ArgOffset,
3034                                         unsigned TotalArgRegsSaveSize,
3035                                         bool ForceMutable) const {
3036   MachineFunction &MF = DAG.getMachineFunction();
3037   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3038
3039   // Try to store any remaining integer argument regs
3040   // to their spots on the stack so that they may be loaded by deferencing
3041   // the result of va_next.
3042   // If there is no regs to be stored, just point address after last
3043   // argument passed via stack.
3044   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3045                                   CCInfo.getInRegsParamsCount(),
3046                                   CCInfo.getNextStackOffset(), 4);
3047   AFI->setVarArgsFrameIndex(FrameIndex);
3048 }
3049
3050 SDValue
3051 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3052                                         CallingConv::ID CallConv, bool isVarArg,
3053                                         const SmallVectorImpl<ISD::InputArg>
3054                                           &Ins,
3055                                         SDLoc dl, SelectionDAG &DAG,
3056                                         SmallVectorImpl<SDValue> &InVals)
3057                                           const {
3058   MachineFunction &MF = DAG.getMachineFunction();
3059   MachineFrameInfo *MFI = MF.getFrameInfo();
3060
3061   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3062
3063   // Assign locations to all of the incoming arguments.
3064   SmallVector<CCValAssign, 16> ArgLocs;
3065   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3066                     *DAG.getContext(), Prologue);
3067   CCInfo.AnalyzeFormalArguments(Ins,
3068                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3069                                                   isVarArg));
3070
3071   SmallVector<SDValue, 16> ArgValues;
3072   SDValue ArgValue;
3073   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3074   unsigned CurArgIdx = 0;
3075
3076   // Initially ArgRegsSaveSize is zero.
3077   // Then we increase this value each time we meet byval parameter.
3078   // We also increase this value in case of varargs function.
3079   AFI->setArgRegsSaveSize(0);
3080
3081   // Calculate the amount of stack space that we need to allocate to store
3082   // byval and variadic arguments that are passed in registers.
3083   // We need to know this before we allocate the first byval or variadic
3084   // argument, as they will be allocated a stack slot below the CFA (Canonical
3085   // Frame Address, the stack pointer at entry to the function).
3086   unsigned ArgRegBegin = ARM::R4;
3087   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3088     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3089       break;
3090
3091     CCValAssign &VA = ArgLocs[i];
3092     unsigned Index = VA.getValNo();
3093     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3094     if (!Flags.isByVal())
3095       continue;
3096
3097     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3098     unsigned RBegin, REnd;
3099     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3100     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3101
3102     CCInfo.nextInRegsParam();
3103   }
3104   CCInfo.rewindByValRegsInfo();
3105
3106   int lastInsIndex = -1;
3107   if (isVarArg && MFI->hasVAStart()) {
3108     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3109     if (RegIdx != array_lengthof(GPRArgRegs))
3110       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3111   }
3112
3113   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3114   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3115   auto PtrVT = getPointerTy(DAG.getDataLayout());
3116
3117   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3118     CCValAssign &VA = ArgLocs[i];
3119     if (Ins[VA.getValNo()].isOrigArg()) {
3120       std::advance(CurOrigArg,
3121                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3122       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3123     }
3124     // Arguments stored in registers.
3125     if (VA.isRegLoc()) {
3126       EVT RegVT = VA.getLocVT();
3127
3128       if (VA.needsCustom()) {
3129         // f64 and vector types are split up into multiple registers or
3130         // combinations of registers and stack slots.
3131         if (VA.getLocVT() == MVT::v2f64) {
3132           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3133                                                    Chain, DAG, dl);
3134           VA = ArgLocs[++i]; // skip ahead to next loc
3135           SDValue ArgValue2;
3136           if (VA.isMemLoc()) {
3137             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3138             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3139             ArgValue2 = DAG.getLoad(
3140                 MVT::f64, dl, Chain, FIN,
3141                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3142                 false, false, false, 0);
3143           } else {
3144             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3145                                              Chain, DAG, dl);
3146           }
3147           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3148           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3149                                  ArgValue, ArgValue1,
3150                                  DAG.getIntPtrConstant(0, dl));
3151           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3152                                  ArgValue, ArgValue2,
3153                                  DAG.getIntPtrConstant(1, dl));
3154         } else
3155           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3156
3157       } else {
3158         const TargetRegisterClass *RC;
3159
3160         if (RegVT == MVT::f32)
3161           RC = &ARM::SPRRegClass;
3162         else if (RegVT == MVT::f64)
3163           RC = &ARM::DPRRegClass;
3164         else if (RegVT == MVT::v2f64)
3165           RC = &ARM::QPRRegClass;
3166         else if (RegVT == MVT::i32)
3167           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3168                                            : &ARM::GPRRegClass;
3169         else
3170           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3171
3172         // Transform the arguments in physical registers into virtual ones.
3173         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3174         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3175       }
3176
3177       // If this is an 8 or 16-bit value, it is really passed promoted
3178       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3179       // truncate to the right size.
3180       switch (VA.getLocInfo()) {
3181       default: llvm_unreachable("Unknown loc info!");
3182       case CCValAssign::Full: break;
3183       case CCValAssign::BCvt:
3184         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3185         break;
3186       case CCValAssign::SExt:
3187         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3188                                DAG.getValueType(VA.getValVT()));
3189         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3190         break;
3191       case CCValAssign::ZExt:
3192         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3193                                DAG.getValueType(VA.getValVT()));
3194         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3195         break;
3196       }
3197
3198       InVals.push_back(ArgValue);
3199
3200     } else { // VA.isRegLoc()
3201
3202       // sanity check
3203       assert(VA.isMemLoc());
3204       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3205
3206       int index = VA.getValNo();
3207
3208       // Some Ins[] entries become multiple ArgLoc[] entries.
3209       // Process them only once.
3210       if (index != lastInsIndex)
3211         {
3212           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3213           // FIXME: For now, all byval parameter objects are marked mutable.
3214           // This can be changed with more analysis.
3215           // In case of tail call optimization mark all arguments mutable.
3216           // Since they could be overwritten by lowering of arguments in case of
3217           // a tail call.
3218           if (Flags.isByVal()) {
3219             assert(Ins[index].isOrigArg() &&
3220                    "Byval arguments cannot be implicit");
3221             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3222
3223             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3224                                             CurByValIndex, VA.getLocMemOffset(),
3225                                             Flags.getByValSize());
3226             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3227             CCInfo.nextInRegsParam();
3228           } else {
3229             unsigned FIOffset = VA.getLocMemOffset();
3230             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3231                                             FIOffset, true);
3232
3233             // Create load nodes to retrieve arguments from the stack.
3234             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3235             InVals.push_back(DAG.getLoad(
3236                 VA.getValVT(), dl, Chain, FIN,
3237                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3238                 false, false, false, 0));
3239           }
3240           lastInsIndex = index;
3241         }
3242     }
3243   }
3244
3245   // varargs
3246   if (isVarArg && MFI->hasVAStart())
3247     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3248                          CCInfo.getNextStackOffset(),
3249                          TotalArgRegsSaveSize);
3250
3251   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3252
3253   return Chain;
3254 }
3255
3256 /// isFloatingPointZero - Return true if this is +0.0.
3257 static bool isFloatingPointZero(SDValue Op) {
3258   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3259     return CFP->getValueAPF().isPosZero();
3260   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3261     // Maybe this has already been legalized into the constant pool?
3262     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3263       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3264       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3265         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3266           return CFP->getValueAPF().isPosZero();
3267     }
3268   } else if (Op->getOpcode() == ISD::BITCAST &&
3269              Op->getValueType(0) == MVT::f64) {
3270     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3271     // created by LowerConstantFP().
3272     SDValue BitcastOp = Op->getOperand(0);
3273     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3274       SDValue MoveOp = BitcastOp->getOperand(0);
3275       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3276           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3277         return true;
3278       }
3279     }
3280   }
3281   return false;
3282 }
3283
3284 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3285 /// the given operands.
3286 SDValue
3287 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3288                              SDValue &ARMcc, SelectionDAG &DAG,
3289                              SDLoc dl) const {
3290   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3291     unsigned C = RHSC->getZExtValue();
3292     if (!isLegalICmpImmediate(C)) {
3293       // Constant does not fit, try adjusting it by one?
3294       switch (CC) {
3295       default: break;
3296       case ISD::SETLT:
3297       case ISD::SETGE:
3298         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3299           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3300           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3301         }
3302         break;
3303       case ISD::SETULT:
3304       case ISD::SETUGE:
3305         if (C != 0 && isLegalICmpImmediate(C-1)) {
3306           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3307           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3308         }
3309         break;
3310       case ISD::SETLE:
3311       case ISD::SETGT:
3312         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3313           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3314           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3315         }
3316         break;
3317       case ISD::SETULE:
3318       case ISD::SETUGT:
3319         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3320           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3321           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3322         }
3323         break;
3324       }
3325     }
3326   }
3327
3328   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3329   ARMISD::NodeType CompareType;
3330   switch (CondCode) {
3331   default:
3332     CompareType = ARMISD::CMP;
3333     break;
3334   case ARMCC::EQ:
3335   case ARMCC::NE:
3336     // Uses only Z Flag
3337     CompareType = ARMISD::CMPZ;
3338     break;
3339   }
3340   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3341   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3342 }
3343
3344 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3345 SDValue
3346 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3347                              SDLoc dl) const {
3348   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3349   SDValue Cmp;
3350   if (!isFloatingPointZero(RHS))
3351     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3352   else
3353     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3354   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3355 }
3356
3357 /// duplicateCmp - Glue values can have only one use, so this function
3358 /// duplicates a comparison node.
3359 SDValue
3360 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3361   unsigned Opc = Cmp.getOpcode();
3362   SDLoc DL(Cmp);
3363   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3364     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3365
3366   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3367   Cmp = Cmp.getOperand(0);
3368   Opc = Cmp.getOpcode();
3369   if (Opc == ARMISD::CMPFP)
3370     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3371   else {
3372     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3373     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3374   }
3375   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3376 }
3377
3378 std::pair<SDValue, SDValue>
3379 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3380                                  SDValue &ARMcc) const {
3381   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3382
3383   SDValue Value, OverflowCmp;
3384   SDValue LHS = Op.getOperand(0);
3385   SDValue RHS = Op.getOperand(1);
3386   SDLoc dl(Op);
3387
3388   // FIXME: We are currently always generating CMPs because we don't support
3389   // generating CMN through the backend. This is not as good as the natural
3390   // CMP case because it causes a register dependency and cannot be folded
3391   // later.
3392
3393   switch (Op.getOpcode()) {
3394   default:
3395     llvm_unreachable("Unknown overflow instruction!");
3396   case ISD::SADDO:
3397     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3398     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3399     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3400     break;
3401   case ISD::UADDO:
3402     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3403     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3404     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3405     break;
3406   case ISD::SSUBO:
3407     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3408     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3409     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3410     break;
3411   case ISD::USUBO:
3412     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3413     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3414     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3415     break;
3416   } // switch (...)
3417
3418   return std::make_pair(Value, OverflowCmp);
3419 }
3420
3421
3422 SDValue
3423 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3424   // Let legalize expand this if it isn't a legal type yet.
3425   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3426     return SDValue();
3427
3428   SDValue Value, OverflowCmp;
3429   SDValue ARMcc;
3430   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3431   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3432   SDLoc dl(Op);
3433   // We use 0 and 1 as false and true values.
3434   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3435   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3436   EVT VT = Op.getValueType();
3437
3438   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3439                                  ARMcc, CCR, OverflowCmp);
3440
3441   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3442   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3443 }
3444
3445
3446 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3447   SDValue Cond = Op.getOperand(0);
3448   SDValue SelectTrue = Op.getOperand(1);
3449   SDValue SelectFalse = Op.getOperand(2);
3450   SDLoc dl(Op);
3451   unsigned Opc = Cond.getOpcode();
3452
3453   if (Cond.getResNo() == 1 &&
3454       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3455        Opc == ISD::USUBO)) {
3456     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3457       return SDValue();
3458
3459     SDValue Value, OverflowCmp;
3460     SDValue ARMcc;
3461     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3462     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3463     EVT VT = Op.getValueType();
3464
3465     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3466                    OverflowCmp, DAG);
3467   }
3468
3469   // Convert:
3470   //
3471   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3472   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3473   //
3474   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3475     const ConstantSDNode *CMOVTrue =
3476       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3477     const ConstantSDNode *CMOVFalse =
3478       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3479
3480     if (CMOVTrue && CMOVFalse) {
3481       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3482       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3483
3484       SDValue True;
3485       SDValue False;
3486       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3487         True = SelectTrue;
3488         False = SelectFalse;
3489       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3490         True = SelectFalse;
3491         False = SelectTrue;
3492       }
3493
3494       if (True.getNode() && False.getNode()) {
3495         EVT VT = Op.getValueType();
3496         SDValue ARMcc = Cond.getOperand(2);
3497         SDValue CCR = Cond.getOperand(3);
3498         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3499         assert(True.getValueType() == VT);
3500         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3501       }
3502     }
3503   }
3504
3505   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3506   // undefined bits before doing a full-word comparison with zero.
3507   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3508                      DAG.getConstant(1, dl, Cond.getValueType()));
3509
3510   return DAG.getSelectCC(dl, Cond,
3511                          DAG.getConstant(0, dl, Cond.getValueType()),
3512                          SelectTrue, SelectFalse, ISD::SETNE);
3513 }
3514
3515 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3516                                  bool &swpCmpOps, bool &swpVselOps) {
3517   // Start by selecting the GE condition code for opcodes that return true for
3518   // 'equality'
3519   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3520       CC == ISD::SETULE)
3521     CondCode = ARMCC::GE;
3522
3523   // and GT for opcodes that return false for 'equality'.
3524   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3525            CC == ISD::SETULT)
3526     CondCode = ARMCC::GT;
3527
3528   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3529   // to swap the compare operands.
3530   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3531       CC == ISD::SETULT)
3532     swpCmpOps = true;
3533
3534   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3535   // If we have an unordered opcode, we need to swap the operands to the VSEL
3536   // instruction (effectively negating the condition).
3537   //
3538   // This also has the effect of swapping which one of 'less' or 'greater'
3539   // returns true, so we also swap the compare operands. It also switches
3540   // whether we return true for 'equality', so we compensate by picking the
3541   // opposite condition code to our original choice.
3542   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3543       CC == ISD::SETUGT) {
3544     swpCmpOps = !swpCmpOps;
3545     swpVselOps = !swpVselOps;
3546     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3547   }
3548
3549   // 'ordered' is 'anything but unordered', so use the VS condition code and
3550   // swap the VSEL operands.
3551   if (CC == ISD::SETO) {
3552     CondCode = ARMCC::VS;
3553     swpVselOps = true;
3554   }
3555
3556   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3557   // code and swap the VSEL operands.
3558   if (CC == ISD::SETUNE) {
3559     CondCode = ARMCC::EQ;
3560     swpVselOps = true;
3561   }
3562 }
3563
3564 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3565                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3566                                    SDValue Cmp, SelectionDAG &DAG) const {
3567   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3568     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3569                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3570     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3571                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3572
3573     SDValue TrueLow = TrueVal.getValue(0);
3574     SDValue TrueHigh = TrueVal.getValue(1);
3575     SDValue FalseLow = FalseVal.getValue(0);
3576     SDValue FalseHigh = FalseVal.getValue(1);
3577
3578     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3579                               ARMcc, CCR, Cmp);
3580     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3581                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3582
3583     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3584   } else {
3585     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3586                        Cmp);
3587   }
3588 }
3589
3590 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3591   EVT VT = Op.getValueType();
3592   SDValue LHS = Op.getOperand(0);
3593   SDValue RHS = Op.getOperand(1);
3594   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3595   SDValue TrueVal = Op.getOperand(2);
3596   SDValue FalseVal = Op.getOperand(3);
3597   SDLoc dl(Op);
3598
3599   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3600     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3601                                                     dl);
3602
3603     // If softenSetCCOperands only returned one value, we should compare it to
3604     // zero.
3605     if (!RHS.getNode()) {
3606       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3607       CC = ISD::SETNE;
3608     }
3609   }
3610
3611   if (LHS.getValueType() == MVT::i32) {
3612     // Try to generate VSEL on ARMv8.
3613     // The VSEL instruction can't use all the usual ARM condition
3614     // codes: it only has two bits to select the condition code, so it's
3615     // constrained to use only GE, GT, VS and EQ.
3616     //
3617     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3618     // swap the operands of the previous compare instruction (effectively
3619     // inverting the compare condition, swapping 'less' and 'greater') and
3620     // sometimes need to swap the operands to the VSEL (which inverts the
3621     // condition in the sense of firing whenever the previous condition didn't)
3622     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3623                                     TrueVal.getValueType() == MVT::f64)) {
3624       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3625       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3626           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3627         CC = ISD::getSetCCInverse(CC, true);
3628         std::swap(TrueVal, FalseVal);
3629       }
3630     }
3631
3632     SDValue ARMcc;
3633     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3634     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3635     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3636   }
3637
3638   ARMCC::CondCodes CondCode, CondCode2;
3639   FPCCToARMCC(CC, CondCode, CondCode2);
3640
3641   // Try to generate VMAXNM/VMINNM on ARMv8.
3642   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3643                                   TrueVal.getValueType() == MVT::f64)) {
3644     bool swpCmpOps = false;
3645     bool swpVselOps = false;
3646     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3647
3648     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3649         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3650       if (swpCmpOps)
3651         std::swap(LHS, RHS);
3652       if (swpVselOps)
3653         std::swap(TrueVal, FalseVal);
3654     }
3655   }
3656
3657   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3658   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3659   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3660   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3661   if (CondCode2 != ARMCC::AL) {
3662     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3663     // FIXME: Needs another CMP because flag can have but one use.
3664     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3665     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3666   }
3667   return Result;
3668 }
3669
3670 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3671 /// to morph to an integer compare sequence.
3672 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3673                            const ARMSubtarget *Subtarget) {
3674   SDNode *N = Op.getNode();
3675   if (!N->hasOneUse())
3676     // Otherwise it requires moving the value from fp to integer registers.
3677     return false;
3678   if (!N->getNumValues())
3679     return false;
3680   EVT VT = Op.getValueType();
3681   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3682     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3683     // vmrs are very slow, e.g. cortex-a8.
3684     return false;
3685
3686   if (isFloatingPointZero(Op)) {
3687     SeenZero = true;
3688     return true;
3689   }
3690   return ISD::isNormalLoad(N);
3691 }
3692
3693 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3694   if (isFloatingPointZero(Op))
3695     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3696
3697   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3698     return DAG.getLoad(MVT::i32, SDLoc(Op),
3699                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3700                        Ld->isVolatile(), Ld->isNonTemporal(),
3701                        Ld->isInvariant(), Ld->getAlignment());
3702
3703   llvm_unreachable("Unknown VFP cmp argument!");
3704 }
3705
3706 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3707                            SDValue &RetVal1, SDValue &RetVal2) {
3708   SDLoc dl(Op);
3709
3710   if (isFloatingPointZero(Op)) {
3711     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3712     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3713     return;
3714   }
3715
3716   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3717     SDValue Ptr = Ld->getBasePtr();
3718     RetVal1 = DAG.getLoad(MVT::i32, dl,
3719                           Ld->getChain(), Ptr,
3720                           Ld->getPointerInfo(),
3721                           Ld->isVolatile(), Ld->isNonTemporal(),
3722                           Ld->isInvariant(), Ld->getAlignment());
3723
3724     EVT PtrType = Ptr.getValueType();
3725     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3726     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3727                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3728     RetVal2 = DAG.getLoad(MVT::i32, dl,
3729                           Ld->getChain(), NewPtr,
3730                           Ld->getPointerInfo().getWithOffset(4),
3731                           Ld->isVolatile(), Ld->isNonTemporal(),
3732                           Ld->isInvariant(), NewAlign);
3733     return;
3734   }
3735
3736   llvm_unreachable("Unknown VFP cmp argument!");
3737 }
3738
3739 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3740 /// f32 and even f64 comparisons to integer ones.
3741 SDValue
3742 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3743   SDValue Chain = Op.getOperand(0);
3744   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3745   SDValue LHS = Op.getOperand(2);
3746   SDValue RHS = Op.getOperand(3);
3747   SDValue Dest = Op.getOperand(4);
3748   SDLoc dl(Op);
3749
3750   bool LHSSeenZero = false;
3751   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3752   bool RHSSeenZero = false;
3753   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3754   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3755     // If unsafe fp math optimization is enabled and there are no other uses of
3756     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3757     // to an integer comparison.
3758     if (CC == ISD::SETOEQ)
3759       CC = ISD::SETEQ;
3760     else if (CC == ISD::SETUNE)
3761       CC = ISD::SETNE;
3762
3763     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3764     SDValue ARMcc;
3765     if (LHS.getValueType() == MVT::f32) {
3766       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3767                         bitcastf32Toi32(LHS, DAG), Mask);
3768       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3769                         bitcastf32Toi32(RHS, DAG), Mask);
3770       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3771       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3772       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3773                          Chain, Dest, ARMcc, CCR, Cmp);
3774     }
3775
3776     SDValue LHS1, LHS2;
3777     SDValue RHS1, RHS2;
3778     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3779     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3780     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3781     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3782     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3783     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3784     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3785     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3786     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3787   }
3788
3789   return SDValue();
3790 }
3791
3792 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3793   SDValue Chain = Op.getOperand(0);
3794   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3795   SDValue LHS = Op.getOperand(2);
3796   SDValue RHS = Op.getOperand(3);
3797   SDValue Dest = Op.getOperand(4);
3798   SDLoc dl(Op);
3799
3800   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3801     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3802                                                     dl);
3803
3804     // If softenSetCCOperands only returned one value, we should compare it to
3805     // zero.
3806     if (!RHS.getNode()) {
3807       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3808       CC = ISD::SETNE;
3809     }
3810   }
3811
3812   if (LHS.getValueType() == MVT::i32) {
3813     SDValue ARMcc;
3814     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3815     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3816     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3817                        Chain, Dest, ARMcc, CCR, Cmp);
3818   }
3819
3820   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3821
3822   if (getTargetMachine().Options.UnsafeFPMath &&
3823       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3824        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3825     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3826     if (Result.getNode())
3827       return Result;
3828   }
3829
3830   ARMCC::CondCodes CondCode, CondCode2;
3831   FPCCToARMCC(CC, CondCode, CondCode2);
3832
3833   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3834   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3835   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3836   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3837   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3838   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3839   if (CondCode2 != ARMCC::AL) {
3840     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3841     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3842     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3843   }
3844   return Res;
3845 }
3846
3847 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3848   SDValue Chain = Op.getOperand(0);
3849   SDValue Table = Op.getOperand(1);
3850   SDValue Index = Op.getOperand(2);
3851   SDLoc dl(Op);
3852
3853   EVT PTy = getPointerTy(DAG.getDataLayout());
3854   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3855   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3856   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3857   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3858   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3859   if (Subtarget->isThumb2()) {
3860     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3861     // which does another jump to the destination. This also makes it easier
3862     // to translate it to TBB / TBH later.
3863     // FIXME: This might not work if the function is extremely large.
3864     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3865                        Addr, Op.getOperand(2), JTI);
3866   }
3867   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3868     Addr =
3869         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3870                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3871                     false, false, false, 0);
3872     Chain = Addr.getValue(1);
3873     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3874     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3875   } else {
3876     Addr =
3877         DAG.getLoad(PTy, dl, Chain, Addr,
3878                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3879                     false, false, false, 0);
3880     Chain = Addr.getValue(1);
3881     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3882   }
3883 }
3884
3885 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3886   EVT VT = Op.getValueType();
3887   SDLoc dl(Op);
3888
3889   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3890     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3891       return Op;
3892     return DAG.UnrollVectorOp(Op.getNode());
3893   }
3894
3895   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3896          "Invalid type for custom lowering!");
3897   if (VT != MVT::v4i16)
3898     return DAG.UnrollVectorOp(Op.getNode());
3899
3900   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3901   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3902 }
3903
3904 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3905   EVT VT = Op.getValueType();
3906   if (VT.isVector())
3907     return LowerVectorFP_TO_INT(Op, DAG);
3908   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3909     RTLIB::Libcall LC;
3910     if (Op.getOpcode() == ISD::FP_TO_SINT)
3911       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3912                               Op.getValueType());
3913     else
3914       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3915                               Op.getValueType());
3916     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3917                        /*isSigned*/ false, SDLoc(Op)).first;
3918   }
3919
3920   return Op;
3921 }
3922
3923 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3924   EVT VT = Op.getValueType();
3925   SDLoc dl(Op);
3926
3927   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3928     if (VT.getVectorElementType() == MVT::f32)
3929       return Op;
3930     return DAG.UnrollVectorOp(Op.getNode());
3931   }
3932
3933   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3934          "Invalid type for custom lowering!");
3935   if (VT != MVT::v4f32)
3936     return DAG.UnrollVectorOp(Op.getNode());
3937
3938   unsigned CastOpc;
3939   unsigned Opc;
3940   switch (Op.getOpcode()) {
3941   default: llvm_unreachable("Invalid opcode!");
3942   case ISD::SINT_TO_FP:
3943     CastOpc = ISD::SIGN_EXTEND;
3944     Opc = ISD::SINT_TO_FP;
3945     break;
3946   case ISD::UINT_TO_FP:
3947     CastOpc = ISD::ZERO_EXTEND;
3948     Opc = ISD::UINT_TO_FP;
3949     break;
3950   }
3951
3952   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3953   return DAG.getNode(Opc, dl, VT, Op);
3954 }
3955
3956 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3957   EVT VT = Op.getValueType();
3958   if (VT.isVector())
3959     return LowerVectorINT_TO_FP(Op, DAG);
3960   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3961     RTLIB::Libcall LC;
3962     if (Op.getOpcode() == ISD::SINT_TO_FP)
3963       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3964                               Op.getValueType());
3965     else
3966       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3967                               Op.getValueType());
3968     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3969                        /*isSigned*/ false, SDLoc(Op)).first;
3970   }
3971
3972   return Op;
3973 }
3974
3975 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3976   // Implement fcopysign with a fabs and a conditional fneg.
3977   SDValue Tmp0 = Op.getOperand(0);
3978   SDValue Tmp1 = Op.getOperand(1);
3979   SDLoc dl(Op);
3980   EVT VT = Op.getValueType();
3981   EVT SrcVT = Tmp1.getValueType();
3982   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3983     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3984   bool UseNEON = !InGPR && Subtarget->hasNEON();
3985
3986   if (UseNEON) {
3987     // Use VBSL to copy the sign bit.
3988     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3989     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3990                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3991     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3992     if (VT == MVT::f64)
3993       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3994                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3995                          DAG.getConstant(32, dl, MVT::i32));
3996     else /*if (VT == MVT::f32)*/
3997       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3998     if (SrcVT == MVT::f32) {
3999       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4000       if (VT == MVT::f64)
4001         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4002                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4003                            DAG.getConstant(32, dl, MVT::i32));
4004     } else if (VT == MVT::f32)
4005       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4006                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4007                          DAG.getConstant(32, dl, MVT::i32));
4008     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4009     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4010
4011     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4012                                             dl, MVT::i32);
4013     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4014     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4015                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4016
4017     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4018                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4019                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4020     if (VT == MVT::f32) {
4021       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4022       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4023                         DAG.getConstant(0, dl, MVT::i32));
4024     } else {
4025       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4026     }
4027
4028     return Res;
4029   }
4030
4031   // Bitcast operand 1 to i32.
4032   if (SrcVT == MVT::f64)
4033     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4034                        Tmp1).getValue(1);
4035   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4036
4037   // Or in the signbit with integer operations.
4038   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4039   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4040   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4041   if (VT == MVT::f32) {
4042     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4043                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4044     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4045                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4046   }
4047
4048   // f64: Or the high part with signbit and then combine two parts.
4049   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4050                      Tmp0);
4051   SDValue Lo = Tmp0.getValue(0);
4052   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4053   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4054   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4055 }
4056
4057 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4058   MachineFunction &MF = DAG.getMachineFunction();
4059   MachineFrameInfo *MFI = MF.getFrameInfo();
4060   MFI->setReturnAddressIsTaken(true);
4061
4062   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4063     return SDValue();
4064
4065   EVT VT = Op.getValueType();
4066   SDLoc dl(Op);
4067   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4068   if (Depth) {
4069     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4070     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4071     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4072                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4073                        MachinePointerInfo(), false, false, false, 0);
4074   }
4075
4076   // Return LR, which contains the return address. Mark it an implicit live-in.
4077   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4078   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4079 }
4080
4081 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4082   const ARMBaseRegisterInfo &ARI =
4083     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4084   MachineFunction &MF = DAG.getMachineFunction();
4085   MachineFrameInfo *MFI = MF.getFrameInfo();
4086   MFI->setFrameAddressIsTaken(true);
4087
4088   EVT VT = Op.getValueType();
4089   SDLoc dl(Op);  // FIXME probably not meaningful
4090   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4091   unsigned FrameReg = ARI.getFrameRegister(MF);
4092   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4093   while (Depth--)
4094     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4095                             MachinePointerInfo(),
4096                             false, false, false, 0);
4097   return FrameAddr;
4098 }
4099
4100 // FIXME? Maybe this could be a TableGen attribute on some registers and
4101 // this table could be generated automatically from RegInfo.
4102 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4103                                               SelectionDAG &DAG) const {
4104   unsigned Reg = StringSwitch<unsigned>(RegName)
4105                        .Case("sp", ARM::SP)
4106                        .Default(0);
4107   if (Reg)
4108     return Reg;
4109   report_fatal_error(Twine("Invalid register name \""
4110                               + StringRef(RegName)  + "\"."));
4111 }
4112
4113 // Result is 64 bit value so split into two 32 bit values and return as a
4114 // pair of values.
4115 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4116                                 SelectionDAG &DAG) {
4117   SDLoc DL(N);
4118
4119   // This function is only supposed to be called for i64 type destination.
4120   assert(N->getValueType(0) == MVT::i64
4121           && "ExpandREAD_REGISTER called for non-i64 type result.");
4122
4123   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4124                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4125                              N->getOperand(0),
4126                              N->getOperand(1));
4127
4128   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4129                     Read.getValue(1)));
4130   Results.push_back(Read.getOperand(0));
4131 }
4132
4133 /// ExpandBITCAST - If the target supports VFP, this function is called to
4134 /// expand a bit convert where either the source or destination type is i64 to
4135 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4136 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4137 /// vectors), since the legalizer won't know what to do with that.
4138 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4139   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4140   SDLoc dl(N);
4141   SDValue Op = N->getOperand(0);
4142
4143   // This function is only supposed to be called for i64 types, either as the
4144   // source or destination of the bit convert.
4145   EVT SrcVT = Op.getValueType();
4146   EVT DstVT = N->getValueType(0);
4147   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4148          "ExpandBITCAST called for non-i64 type");
4149
4150   // Turn i64->f64 into VMOVDRR.
4151   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4152     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4153                              DAG.getConstant(0, dl, MVT::i32));
4154     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4155                              DAG.getConstant(1, dl, MVT::i32));
4156     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4157                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4158   }
4159
4160   // Turn f64->i64 into VMOVRRD.
4161   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4162     SDValue Cvt;
4163     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4164         SrcVT.getVectorNumElements() > 1)
4165       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4166                         DAG.getVTList(MVT::i32, MVT::i32),
4167                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4168     else
4169       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4170                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4171     // Merge the pieces into a single i64 value.
4172     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4173   }
4174
4175   return SDValue();
4176 }
4177
4178 /// getZeroVector - Returns a vector of specified type with all zero elements.
4179 /// Zero vectors are used to represent vector negation and in those cases
4180 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4181 /// not support i64 elements, so sometimes the zero vectors will need to be
4182 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4183 /// zero vector.
4184 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4185   assert(VT.isVector() && "Expected a vector type");
4186   // The canonical modified immediate encoding of a zero vector is....0!
4187   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4188   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4189   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4190   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4191 }
4192
4193 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4194 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4195 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4196                                                 SelectionDAG &DAG) const {
4197   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4198   EVT VT = Op.getValueType();
4199   unsigned VTBits = VT.getSizeInBits();
4200   SDLoc dl(Op);
4201   SDValue ShOpLo = Op.getOperand(0);
4202   SDValue ShOpHi = Op.getOperand(1);
4203   SDValue ShAmt  = Op.getOperand(2);
4204   SDValue ARMcc;
4205   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4206
4207   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4208
4209   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4210                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4211   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4212   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4213                                    DAG.getConstant(VTBits, dl, MVT::i32));
4214   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4215   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4216   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4217
4218   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4219   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4220                           ISD::SETGE, ARMcc, DAG, dl);
4221   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4222   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4223                            CCR, Cmp);
4224
4225   SDValue Ops[2] = { Lo, Hi };
4226   return DAG.getMergeValues(Ops, dl);
4227 }
4228
4229 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4230 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4231 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4232                                                SelectionDAG &DAG) const {
4233   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4234   EVT VT = Op.getValueType();
4235   unsigned VTBits = VT.getSizeInBits();
4236   SDLoc dl(Op);
4237   SDValue ShOpLo = Op.getOperand(0);
4238   SDValue ShOpHi = Op.getOperand(1);
4239   SDValue ShAmt  = Op.getOperand(2);
4240   SDValue ARMcc;
4241
4242   assert(Op.getOpcode() == ISD::SHL_PARTS);
4243   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4244                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4245   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4246   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4247                                    DAG.getConstant(VTBits, dl, MVT::i32));
4248   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4249   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4250
4251   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4252   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4253   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4254                           ISD::SETGE, ARMcc, DAG, dl);
4255   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4256   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4257                            CCR, Cmp);
4258
4259   SDValue Ops[2] = { Lo, Hi };
4260   return DAG.getMergeValues(Ops, dl);
4261 }
4262
4263 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4264                                             SelectionDAG &DAG) const {
4265   // The rounding mode is in bits 23:22 of the FPSCR.
4266   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4267   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4268   // so that the shift + and get folded into a bitfield extract.
4269   SDLoc dl(Op);
4270   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4271                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4272                                               MVT::i32));
4273   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4274                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4275   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4276                               DAG.getConstant(22, dl, MVT::i32));
4277   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4278                      DAG.getConstant(3, dl, MVT::i32));
4279 }
4280
4281 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4282                          const ARMSubtarget *ST) {
4283   SDLoc dl(N);
4284   EVT VT = N->getValueType(0);
4285   if (VT.isVector()) {
4286     assert(ST->hasNEON());
4287
4288     // Compute the least significant set bit: LSB = X & -X
4289     SDValue X = N->getOperand(0);
4290     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4291     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4292
4293     EVT ElemTy = VT.getVectorElementType();
4294
4295     if (ElemTy == MVT::i8) {
4296       // Compute with: cttz(x) = ctpop(lsb - 1)
4297       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4298                                 DAG.getTargetConstant(1, dl, ElemTy));
4299       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4300       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4301     }
4302
4303     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4304         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4305       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4306       unsigned NumBits = ElemTy.getSizeInBits();
4307       SDValue WidthMinus1 =
4308           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4309                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4310       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4311       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4312     }
4313
4314     // Compute with: cttz(x) = ctpop(lsb - 1)
4315
4316     // Since we can only compute the number of bits in a byte with vcnt.8, we
4317     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4318     // and i64.
4319
4320     // Compute LSB - 1.
4321     SDValue Bits;
4322     if (ElemTy == MVT::i64) {
4323       // Load constant 0xffff'ffff'ffff'ffff to register.
4324       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4325                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4326       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4327     } else {
4328       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4329                                 DAG.getTargetConstant(1, dl, ElemTy));
4330       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4331     }
4332
4333     // Count #bits with vcnt.8.
4334     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4335     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4336     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4337
4338     // Gather the #bits with vpaddl (pairwise add.)
4339     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4340     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4341         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4342         Cnt8);
4343     if (ElemTy == MVT::i16)
4344       return Cnt16;
4345
4346     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4347     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4348         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4349         Cnt16);
4350     if (ElemTy == MVT::i32)
4351       return Cnt32;
4352
4353     assert(ElemTy == MVT::i64);
4354     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4355         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4356         Cnt32);
4357     return Cnt64;
4358   }
4359
4360   if (!ST->hasV6T2Ops())
4361     return SDValue();
4362
4363   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4364   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4365 }
4366
4367 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4368 /// for each 16-bit element from operand, repeated.  The basic idea is to
4369 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4370 ///
4371 /// Trace for v4i16:
4372 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4373 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4374 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4375 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4376 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4377 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4378 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4379 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4380 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4381   EVT VT = N->getValueType(0);
4382   SDLoc DL(N);
4383
4384   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4385   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4386   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4387   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4388   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4389   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4390 }
4391
4392 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4393 /// bit-count for each 16-bit element from the operand.  We need slightly
4394 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4395 /// 64/128-bit registers.
4396 ///
4397 /// Trace for v4i16:
4398 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4399 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4400 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4401 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4402 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4403   EVT VT = N->getValueType(0);
4404   SDLoc DL(N);
4405
4406   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4407   if (VT.is64BitVector()) {
4408     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4409     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4410                        DAG.getIntPtrConstant(0, DL));
4411   } else {
4412     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4413                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4414     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4415   }
4416 }
4417
4418 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4419 /// bit-count for each 32-bit element from the operand.  The idea here is
4420 /// to split the vector into 16-bit elements, leverage the 16-bit count
4421 /// routine, and then combine the results.
4422 ///
4423 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4424 /// input    = [v0    v1    ] (vi: 32-bit elements)
4425 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4426 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4427 /// vrev: N0 = [k1 k0 k3 k2 ]
4428 ///            [k0 k1 k2 k3 ]
4429 ///       N1 =+[k1 k0 k3 k2 ]
4430 ///            [k0 k2 k1 k3 ]
4431 ///       N2 =+[k1 k3 k0 k2 ]
4432 ///            [k0    k2    k1    k3    ]
4433 /// Extended =+[k1    k3    k0    k2    ]
4434 ///            [k0    k2    ]
4435 /// Extracted=+[k1    k3    ]
4436 ///
4437 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4438   EVT VT = N->getValueType(0);
4439   SDLoc DL(N);
4440
4441   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4442
4443   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4444   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4445   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4446   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4447   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4448
4449   if (VT.is64BitVector()) {
4450     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4451     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4452                        DAG.getIntPtrConstant(0, DL));
4453   } else {
4454     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4455                                     DAG.getIntPtrConstant(0, DL));
4456     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4457   }
4458 }
4459
4460 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4461                           const ARMSubtarget *ST) {
4462   EVT VT = N->getValueType(0);
4463
4464   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4465   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4466           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4467          "Unexpected type for custom ctpop lowering");
4468
4469   if (VT.getVectorElementType() == MVT::i32)
4470     return lowerCTPOP32BitElements(N, DAG);
4471   else
4472     return lowerCTPOP16BitElements(N, DAG);
4473 }
4474
4475 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4476                           const ARMSubtarget *ST) {
4477   EVT VT = N->getValueType(0);
4478   SDLoc dl(N);
4479
4480   if (!VT.isVector())
4481     return SDValue();
4482
4483   // Lower vector shifts on NEON to use VSHL.
4484   assert(ST->hasNEON() && "unexpected vector shift");
4485
4486   // Left shifts translate directly to the vshiftu intrinsic.
4487   if (N->getOpcode() == ISD::SHL)
4488     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4489                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4490                                        MVT::i32),
4491                        N->getOperand(0), N->getOperand(1));
4492
4493   assert((N->getOpcode() == ISD::SRA ||
4494           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4495
4496   // NEON uses the same intrinsics for both left and right shifts.  For
4497   // right shifts, the shift amounts are negative, so negate the vector of
4498   // shift amounts.
4499   EVT ShiftVT = N->getOperand(1).getValueType();
4500   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4501                                      getZeroVector(ShiftVT, DAG, dl),
4502                                      N->getOperand(1));
4503   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4504                              Intrinsic::arm_neon_vshifts :
4505                              Intrinsic::arm_neon_vshiftu);
4506   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4507                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4508                      N->getOperand(0), NegatedCount);
4509 }
4510
4511 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4512                                 const ARMSubtarget *ST) {
4513   EVT VT = N->getValueType(0);
4514   SDLoc dl(N);
4515
4516   // We can get here for a node like i32 = ISD::SHL i32, i64
4517   if (VT != MVT::i64)
4518     return SDValue();
4519
4520   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4521          "Unknown shift to lower!");
4522
4523   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4524   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4525       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4526     return SDValue();
4527
4528   // If we are in thumb mode, we don't have RRX.
4529   if (ST->isThumb1Only()) return SDValue();
4530
4531   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4532   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4533                            DAG.getConstant(0, dl, MVT::i32));
4534   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4535                            DAG.getConstant(1, dl, MVT::i32));
4536
4537   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4538   // captures the result into a carry flag.
4539   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4540   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4541
4542   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4543   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4544
4545   // Merge the pieces into a single i64 value.
4546  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4547 }
4548
4549 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4550   SDValue TmpOp0, TmpOp1;
4551   bool Invert = false;
4552   bool Swap = false;
4553   unsigned Opc = 0;
4554
4555   SDValue Op0 = Op.getOperand(0);
4556   SDValue Op1 = Op.getOperand(1);
4557   SDValue CC = Op.getOperand(2);
4558   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4559   EVT VT = Op.getValueType();
4560   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4561   SDLoc dl(Op);
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 result then we need to check the upper
5041   // and lower parts of the mask
5042   for (unsigned i = 0; i < M.size(); i += NumElts) {
5043     WhichResult = M[i] == 0 ? 0 : 1;
5044     for (unsigned j = 0; j < NumElts; j += 2) {
5045       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5046           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5047         return false;
5048     }
5049   }
5050
5051   if (M.size() == NumElts*2)
5052     WhichResult = 0;
5053
5054   return true;
5055 }
5056
5057 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5058 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5059 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5060 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5061   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5062   if (EltSz == 64)
5063     return false;
5064
5065   unsigned NumElts = VT.getVectorNumElements();
5066   if (M.size() != NumElts && M.size() != NumElts*2)
5067     return false;
5068
5069   for (unsigned i = 0; i < M.size(); i += NumElts) {
5070     WhichResult = M[i] == 0 ? 0 : 1;
5071     for (unsigned j = 0; j < NumElts; j += 2) {
5072       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5073           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5074         return false;
5075     }
5076   }
5077
5078   if (M.size() == NumElts*2)
5079     WhichResult = 0;
5080
5081   return true;
5082 }
5083
5084 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5085 // that the mask elements are either all even and in steps of size 2 or all odd
5086 // and in steps of size 2.
5087 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5088 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5089 //  v2={e,f,g,h}
5090 // Requires similar checks to that of isVTRNMask with
5091 // respect the how results are returned.
5092 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5093   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5094   if (EltSz == 64)
5095     return false;
5096
5097   unsigned NumElts = VT.getVectorNumElements();
5098   if (M.size() != NumElts && M.size() != NumElts*2)
5099     return false;
5100
5101   for (unsigned i = 0; i < M.size(); i += NumElts) {
5102     WhichResult = M[i] == 0 ? 0 : 1;
5103     for (unsigned j = 0; j < NumElts; ++j) {
5104       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5105         return false;
5106     }
5107   }
5108
5109   if (M.size() == NumElts*2)
5110     WhichResult = 0;
5111
5112   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5113   if (VT.is64BitVector() && EltSz == 32)
5114     return false;
5115
5116   return true;
5117 }
5118
5119 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5120 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5121 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5122 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5123   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5124   if (EltSz == 64)
5125     return false;
5126
5127   unsigned NumElts = VT.getVectorNumElements();
5128   if (M.size() != NumElts && M.size() != NumElts*2)
5129     return false;
5130
5131   unsigned Half = NumElts / 2;
5132   for (unsigned i = 0; i < M.size(); i += NumElts) {
5133     WhichResult = M[i] == 0 ? 0 : 1;
5134     for (unsigned j = 0; j < NumElts; j += Half) {
5135       unsigned Idx = WhichResult;
5136       for (unsigned k = 0; k < Half; ++k) {
5137         int MIdx = M[i + j + k];
5138         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5139           return false;
5140         Idx += 2;
5141       }
5142     }
5143   }
5144
5145   if (M.size() == NumElts*2)
5146     WhichResult = 0;
5147
5148   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5149   if (VT.is64BitVector() && EltSz == 32)
5150     return false;
5151
5152   return true;
5153 }
5154
5155 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5156 // that pairs of elements of the shufflemask represent the same index in each
5157 // vector incrementing sequentially through the vectors.
5158 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5159 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5160 //  v2={e,f,g,h}
5161 // Requires similar checks to that of isVTRNMask with respect the how results
5162 // are returned.
5163 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5164   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5165   if (EltSz == 64)
5166     return false;
5167
5168   unsigned NumElts = VT.getVectorNumElements();
5169   if (M.size() != NumElts && M.size() != NumElts*2)
5170     return false;
5171
5172   for (unsigned i = 0; i < M.size(); i += NumElts) {
5173     WhichResult = M[i] == 0 ? 0 : 1;
5174     unsigned Idx = WhichResult * NumElts / 2;
5175     for (unsigned j = 0; j < NumElts; j += 2) {
5176       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5177           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5178         return false;
5179       Idx += 1;
5180     }
5181   }
5182
5183   if (M.size() == NumElts*2)
5184     WhichResult = 0;
5185
5186   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5187   if (VT.is64BitVector() && EltSz == 32)
5188     return false;
5189
5190   return true;
5191 }
5192
5193 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5194 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5195 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5196 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5197   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5198   if (EltSz == 64)
5199     return false;
5200
5201   unsigned NumElts = VT.getVectorNumElements();
5202   if (M.size() != NumElts && M.size() != NumElts*2)
5203     return false;
5204
5205   for (unsigned i = 0; i < M.size(); i += NumElts) {
5206     WhichResult = M[i] == 0 ? 0 : 1;
5207     unsigned Idx = WhichResult * NumElts / 2;
5208     for (unsigned j = 0; j < NumElts; j += 2) {
5209       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5210           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5211         return false;
5212       Idx += 1;
5213     }
5214   }
5215
5216   if (M.size() == NumElts*2)
5217     WhichResult = 0;
5218
5219   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5220   if (VT.is64BitVector() && EltSz == 32)
5221     return false;
5222
5223   return true;
5224 }
5225
5226 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5227 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5228 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5229                                            unsigned &WhichResult,
5230                                            bool &isV_UNDEF) {
5231   isV_UNDEF = false;
5232   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5233     return ARMISD::VTRN;
5234   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5235     return ARMISD::VUZP;
5236   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5237     return ARMISD::VZIP;
5238
5239   isV_UNDEF = true;
5240   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5241     return ARMISD::VTRN;
5242   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5243     return ARMISD::VUZP;
5244   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5245     return ARMISD::VZIP;
5246
5247   return 0;
5248 }
5249
5250 /// \return true if this is a reverse operation on an vector.
5251 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5252   unsigned NumElts = VT.getVectorNumElements();
5253   // Make sure the mask has the right size.
5254   if (NumElts != M.size())
5255       return false;
5256
5257   // Look for <15, ..., 3, -1, 1, 0>.
5258   for (unsigned i = 0; i != NumElts; ++i)
5259     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5260       return false;
5261
5262   return true;
5263 }
5264
5265 // If N is an integer constant that can be moved into a register in one
5266 // instruction, return an SDValue of such a constant (will become a MOV
5267 // instruction).  Otherwise return null.
5268 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5269                                      const ARMSubtarget *ST, SDLoc dl) {
5270   uint64_t Val;
5271   if (!isa<ConstantSDNode>(N))
5272     return SDValue();
5273   Val = cast<ConstantSDNode>(N)->getZExtValue();
5274
5275   if (ST->isThumb1Only()) {
5276     if (Val <= 255 || ~Val <= 255)
5277       return DAG.getConstant(Val, dl, MVT::i32);
5278   } else {
5279     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5280       return DAG.getConstant(Val, dl, MVT::i32);
5281   }
5282   return SDValue();
5283 }
5284
5285 // If this is a case we can't handle, return null and let the default
5286 // expansion code take care of it.
5287 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5288                                              const ARMSubtarget *ST) const {
5289   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5290   SDLoc dl(Op);
5291   EVT VT = Op.getValueType();
5292
5293   APInt SplatBits, SplatUndef;
5294   unsigned SplatBitSize;
5295   bool HasAnyUndefs;
5296   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5297     if (SplatBitSize <= 64) {
5298       // Check if an immediate VMOV works.
5299       EVT VmovVT;
5300       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5301                                       SplatUndef.getZExtValue(), SplatBitSize,
5302                                       DAG, dl, VmovVT, VT.is128BitVector(),
5303                                       VMOVModImm);
5304       if (Val.getNode()) {
5305         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5306         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5307       }
5308
5309       // Try an immediate VMVN.
5310       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5311       Val = isNEONModifiedImm(NegatedImm,
5312                                       SplatUndef.getZExtValue(), SplatBitSize,
5313                                       DAG, dl, VmovVT, VT.is128BitVector(),
5314                                       VMVNModImm);
5315       if (Val.getNode()) {
5316         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5317         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5318       }
5319
5320       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5321       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5322         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5323         if (ImmVal != -1) {
5324           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5325           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5326         }
5327       }
5328     }
5329   }
5330
5331   // Scan through the operands to see if only one value is used.
5332   //
5333   // As an optimisation, even if more than one value is used it may be more
5334   // profitable to splat with one value then change some lanes.
5335   //
5336   // Heuristically we decide to do this if the vector has a "dominant" value,
5337   // defined as splatted to more than half of the lanes.
5338   unsigned NumElts = VT.getVectorNumElements();
5339   bool isOnlyLowElement = true;
5340   bool usesOnlyOneValue = true;
5341   bool hasDominantValue = false;
5342   bool isConstant = true;
5343
5344   // Map of the number of times a particular SDValue appears in the
5345   // element list.
5346   DenseMap<SDValue, unsigned> ValueCounts;
5347   SDValue Value;
5348   for (unsigned i = 0; i < NumElts; ++i) {
5349     SDValue V = Op.getOperand(i);
5350     if (V.getOpcode() == ISD::UNDEF)
5351       continue;
5352     if (i > 0)
5353       isOnlyLowElement = false;
5354     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5355       isConstant = false;
5356
5357     ValueCounts.insert(std::make_pair(V, 0));
5358     unsigned &Count = ValueCounts[V];
5359
5360     // Is this value dominant? (takes up more than half of the lanes)
5361     if (++Count > (NumElts / 2)) {
5362       hasDominantValue = true;
5363       Value = V;
5364     }
5365   }
5366   if (ValueCounts.size() != 1)
5367     usesOnlyOneValue = false;
5368   if (!Value.getNode() && ValueCounts.size() > 0)
5369     Value = ValueCounts.begin()->first;
5370
5371   if (ValueCounts.size() == 0)
5372     return DAG.getUNDEF(VT);
5373
5374   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5375   // Keep going if we are hitting this case.
5376   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5377     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5378
5379   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5380
5381   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5382   // i32 and try again.
5383   if (hasDominantValue && EltSize <= 32) {
5384     if (!isConstant) {
5385       SDValue N;
5386
5387       // If we are VDUPing a value that comes directly from a vector, that will
5388       // cause an unnecessary move to and from a GPR, where instead we could
5389       // just use VDUPLANE. We can only do this if the lane being extracted
5390       // is at a constant index, as the VDUP from lane instructions only have
5391       // constant-index forms.
5392       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5393           isa<ConstantSDNode>(Value->getOperand(1))) {
5394         // We need to create a new undef vector to use for the VDUPLANE if the
5395         // size of the vector from which we get the value is different than the
5396         // size of the vector that we need to create. We will insert the element
5397         // such that the register coalescer will remove unnecessary copies.
5398         if (VT != Value->getOperand(0).getValueType()) {
5399           ConstantSDNode *constIndex;
5400           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5401           assert(constIndex && "The index is not a constant!");
5402           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5403                              VT.getVectorNumElements();
5404           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5405                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5406                         Value, DAG.getConstant(index, dl, MVT::i32)),
5407                            DAG.getConstant(index, dl, MVT::i32));
5408         } else
5409           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5410                         Value->getOperand(0), Value->getOperand(1));
5411       } else
5412         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5413
5414       if (!usesOnlyOneValue) {
5415         // The dominant value was splatted as 'N', but we now have to insert
5416         // all differing elements.
5417         for (unsigned I = 0; I < NumElts; ++I) {
5418           if (Op.getOperand(I) == Value)
5419             continue;
5420           SmallVector<SDValue, 3> Ops;
5421           Ops.push_back(N);
5422           Ops.push_back(Op.getOperand(I));
5423           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5424           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5425         }
5426       }
5427       return N;
5428     }
5429     if (VT.getVectorElementType().isFloatingPoint()) {
5430       SmallVector<SDValue, 8> Ops;
5431       for (unsigned i = 0; i < NumElts; ++i)
5432         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5433                                   Op.getOperand(i)));
5434       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5435       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5436       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5437       if (Val.getNode())
5438         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5439     }
5440     if (usesOnlyOneValue) {
5441       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5442       if (isConstant && Val.getNode())
5443         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5444     }
5445   }
5446
5447   // If all elements are constants and the case above didn't get hit, fall back
5448   // to the default expansion, which will generate a load from the constant
5449   // pool.
5450   if (isConstant)
5451     return SDValue();
5452
5453   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5454   if (NumElts >= 4) {
5455     SDValue shuffle = ReconstructShuffle(Op, DAG);
5456     if (shuffle != SDValue())
5457       return shuffle;
5458   }
5459
5460   // Vectors with 32- or 64-bit elements can be built by directly assigning
5461   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5462   // will be legalized.
5463   if (EltSize >= 32) {
5464     // Do the expansion with floating-point types, since that is what the VFP
5465     // registers are defined to use, and since i64 is not legal.
5466     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5467     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5468     SmallVector<SDValue, 8> Ops;
5469     for (unsigned i = 0; i < NumElts; ++i)
5470       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5471     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5472     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5473   }
5474
5475   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5476   // know the default expansion would otherwise fall back on something even
5477   // worse. For a vector with one or two non-undef values, that's
5478   // scalar_to_vector for the elements followed by a shuffle (provided the
5479   // shuffle is valid for the target) and materialization element by element
5480   // on the stack followed by a load for everything else.
5481   if (!isConstant && !usesOnlyOneValue) {
5482     SDValue Vec = DAG.getUNDEF(VT);
5483     for (unsigned i = 0 ; i < NumElts; ++i) {
5484       SDValue V = Op.getOperand(i);
5485       if (V.getOpcode() == ISD::UNDEF)
5486         continue;
5487       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5488       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5489     }
5490     return Vec;
5491   }
5492
5493   return SDValue();
5494 }
5495
5496 /// getExtFactor - Determine the adjustment factor for the position when
5497 /// generating an "extract from vector registers" instruction.
5498 static unsigned getExtFactor(SDValue &V) {
5499   EVT EltType = V.getValueType().getVectorElementType();
5500   return EltType.getSizeInBits() / 8;
5501 }
5502
5503 // Gather data to see if the operation can be modelled as a
5504 // shuffle in combination with VEXTs.
5505 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5506                                               SelectionDAG &DAG) const {
5507   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5508   SDLoc dl(Op);
5509   EVT VT = Op.getValueType();
5510   unsigned NumElts = VT.getVectorNumElements();
5511
5512   struct ShuffleSourceInfo {
5513     SDValue Vec;
5514     unsigned MinElt;
5515     unsigned MaxElt;
5516
5517     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5518     // be compatible with the shuffle we intend to construct. As a result
5519     // ShuffleVec will be some sliding window into the original Vec.
5520     SDValue ShuffleVec;
5521
5522     // Code should guarantee that element i in Vec starts at element "WindowBase
5523     // + i * WindowScale in ShuffleVec".
5524     int WindowBase;
5525     int WindowScale;
5526
5527     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5528     ShuffleSourceInfo(SDValue Vec)
5529         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5530           WindowScale(1) {}
5531   };
5532
5533   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5534   // node.
5535   SmallVector<ShuffleSourceInfo, 2> Sources;
5536   for (unsigned i = 0; i < NumElts; ++i) {
5537     SDValue V = Op.getOperand(i);
5538     if (V.getOpcode() == ISD::UNDEF)
5539       continue;
5540     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5541       // A shuffle can only come from building a vector from various
5542       // elements of other vectors.
5543       return SDValue();
5544     }
5545
5546     // Add this element source to the list if it's not already there.
5547     SDValue SourceVec = V.getOperand(0);
5548     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5549     if (Source == Sources.end())
5550       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5551
5552     // Update the minimum and maximum lane number seen.
5553     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5554     Source->MinElt = std::min(Source->MinElt, EltNo);
5555     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5556   }
5557
5558   // Currently only do something sane when at most two source vectors
5559   // are involved.
5560   if (Sources.size() > 2)
5561     return SDValue();
5562
5563   // Find out the smallest element size among result and two sources, and use
5564   // it as element size to build the shuffle_vector.
5565   EVT SmallestEltTy = VT.getVectorElementType();
5566   for (auto &Source : Sources) {
5567     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5568     if (SrcEltTy.bitsLT(SmallestEltTy))
5569       SmallestEltTy = SrcEltTy;
5570   }
5571   unsigned ResMultiplier =
5572       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5573   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5574   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5575
5576   // If the source vector is too wide or too narrow, we may nevertheless be able
5577   // to construct a compatible shuffle either by concatenating it with UNDEF or
5578   // extracting a suitable range of elements.
5579   for (auto &Src : Sources) {
5580     EVT SrcVT = Src.ShuffleVec.getValueType();
5581
5582     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5583       continue;
5584
5585     // This stage of the search produces a source with the same element type as
5586     // the original, but with a total width matching the BUILD_VECTOR output.
5587     EVT EltVT = SrcVT.getVectorElementType();
5588     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5589     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5590
5591     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5592       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5593         return SDValue();
5594       // We can pad out the smaller vector for free, so if it's part of a
5595       // shuffle...
5596       Src.ShuffleVec =
5597           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5598                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5599       continue;
5600     }
5601
5602     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5603       return SDValue();
5604
5605     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5606       // Span too large for a VEXT to cope
5607       return SDValue();
5608     }
5609
5610     if (Src.MinElt >= NumSrcElts) {
5611       // The extraction can just take the second half
5612       Src.ShuffleVec =
5613           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5614                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5615       Src.WindowBase = -NumSrcElts;
5616     } else if (Src.MaxElt < NumSrcElts) {
5617       // The extraction can just take the first half
5618       Src.ShuffleVec =
5619           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5620                       DAG.getConstant(0, dl, MVT::i32));
5621     } else {
5622       // An actual VEXT is needed
5623       SDValue VEXTSrc1 =
5624           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5625                       DAG.getConstant(0, dl, MVT::i32));
5626       SDValue VEXTSrc2 =
5627           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5628                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5629       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5630
5631       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5632                                    VEXTSrc2,
5633                                    DAG.getConstant(Imm, dl, MVT::i32));
5634       Src.WindowBase = -Src.MinElt;
5635     }
5636   }
5637
5638   // Another possible incompatibility occurs from the vector element types. We
5639   // can fix this by bitcasting the source vectors to the same type we intend
5640   // for the shuffle.
5641   for (auto &Src : Sources) {
5642     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5643     if (SrcEltTy == SmallestEltTy)
5644       continue;
5645     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5646     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5647     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5648     Src.WindowBase *= Src.WindowScale;
5649   }
5650
5651   // Final sanity check before we try to actually produce a shuffle.
5652   DEBUG(
5653     for (auto Src : Sources)
5654       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5655   );
5656
5657   // The stars all align, our next step is to produce the mask for the shuffle.
5658   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5659   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5660   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5661     SDValue Entry = Op.getOperand(i);
5662     if (Entry.getOpcode() == ISD::UNDEF)
5663       continue;
5664
5665     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5666     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5667
5668     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5669     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5670     // segment.
5671     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5672     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5673                                VT.getVectorElementType().getSizeInBits());
5674     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5675
5676     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5677     // starting at the appropriate offset.
5678     int *LaneMask = &Mask[i * ResMultiplier];
5679
5680     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5681     ExtractBase += NumElts * (Src - Sources.begin());
5682     for (int j = 0; j < LanesDefined; ++j)
5683       LaneMask[j] = ExtractBase + j;
5684   }
5685
5686   // Final check before we try to produce nonsense...
5687   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5688     return SDValue();
5689
5690   // We can't handle more than two sources. This should have already
5691   // been checked before this point.
5692   assert(Sources.size() <= 2 && "Too many sources!");
5693
5694   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5695   for (unsigned i = 0; i < Sources.size(); ++i)
5696     ShuffleOps[i] = Sources[i].ShuffleVec;
5697
5698   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5699                                          ShuffleOps[1], &Mask[0]);
5700   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5701 }
5702
5703 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5704 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5705 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5706 /// are assumed to be legal.
5707 bool
5708 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5709                                       EVT VT) const {
5710   if (VT.getVectorNumElements() == 4 &&
5711       (VT.is128BitVector() || VT.is64BitVector())) {
5712     unsigned PFIndexes[4];
5713     for (unsigned i = 0; i != 4; ++i) {
5714       if (M[i] < 0)
5715         PFIndexes[i] = 8;
5716       else
5717         PFIndexes[i] = M[i];
5718     }
5719
5720     // Compute the index in the perfect shuffle table.
5721     unsigned PFTableIndex =
5722       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5723     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5724     unsigned Cost = (PFEntry >> 30);
5725
5726     if (Cost <= 4)
5727       return true;
5728   }
5729
5730   bool ReverseVEXT, isV_UNDEF;
5731   unsigned Imm, WhichResult;
5732
5733   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5734   return (EltSize >= 32 ||
5735           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5736           isVREVMask(M, VT, 64) ||
5737           isVREVMask(M, VT, 32) ||
5738           isVREVMask(M, VT, 16) ||
5739           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5740           isVTBLMask(M, VT) ||
5741           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5742           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5743 }
5744
5745 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5746 /// the specified operations to build the shuffle.
5747 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5748                                       SDValue RHS, SelectionDAG &DAG,
5749                                       SDLoc dl) {
5750   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5751   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5752   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5753
5754   enum {
5755     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5756     OP_VREV,
5757     OP_VDUP0,
5758     OP_VDUP1,
5759     OP_VDUP2,
5760     OP_VDUP3,
5761     OP_VEXT1,
5762     OP_VEXT2,
5763     OP_VEXT3,
5764     OP_VUZPL, // VUZP, left result
5765     OP_VUZPR, // VUZP, right result
5766     OP_VZIPL, // VZIP, left result
5767     OP_VZIPR, // VZIP, right result
5768     OP_VTRNL, // VTRN, left result
5769     OP_VTRNR  // VTRN, right result
5770   };
5771
5772   if (OpNum == OP_COPY) {
5773     if (LHSID == (1*9+2)*9+3) return LHS;
5774     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5775     return RHS;
5776   }
5777
5778   SDValue OpLHS, OpRHS;
5779   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5780   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5781   EVT VT = OpLHS.getValueType();
5782
5783   switch (OpNum) {
5784   default: llvm_unreachable("Unknown shuffle opcode!");
5785   case OP_VREV:
5786     // VREV divides the vector in half and swaps within the half.
5787     if (VT.getVectorElementType() == MVT::i32 ||
5788         VT.getVectorElementType() == MVT::f32)
5789       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5790     // vrev <4 x i16> -> VREV32
5791     if (VT.getVectorElementType() == MVT::i16)
5792       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5793     // vrev <4 x i8> -> VREV16
5794     assert(VT.getVectorElementType() == MVT::i8);
5795     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5796   case OP_VDUP0:
5797   case OP_VDUP1:
5798   case OP_VDUP2:
5799   case OP_VDUP3:
5800     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5801                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5802   case OP_VEXT1:
5803   case OP_VEXT2:
5804   case OP_VEXT3:
5805     return DAG.getNode(ARMISD::VEXT, dl, VT,
5806                        OpLHS, OpRHS,
5807                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5808   case OP_VUZPL:
5809   case OP_VUZPR:
5810     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5811                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5812   case OP_VZIPL:
5813   case OP_VZIPR:
5814     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5815                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5816   case OP_VTRNL:
5817   case OP_VTRNR:
5818     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5819                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5820   }
5821 }
5822
5823 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5824                                        ArrayRef<int> ShuffleMask,
5825                                        SelectionDAG &DAG) {
5826   // Check to see if we can use the VTBL instruction.
5827   SDValue V1 = Op.getOperand(0);
5828   SDValue V2 = Op.getOperand(1);
5829   SDLoc DL(Op);
5830
5831   SmallVector<SDValue, 8> VTBLMask;
5832   for (ArrayRef<int>::iterator
5833          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5834     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5835
5836   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5837     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5838                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5839
5840   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5841                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5842 }
5843
5844 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5845                                                       SelectionDAG &DAG) {
5846   SDLoc DL(Op);
5847   SDValue OpLHS = Op.getOperand(0);
5848   EVT VT = OpLHS.getValueType();
5849
5850   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5851          "Expect an v8i16/v16i8 type");
5852   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5853   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5854   // extract the first 8 bytes into the top double word and the last 8 bytes
5855   // into the bottom double word. The v8i16 case is similar.
5856   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5857   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5858                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5859 }
5860
5861 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5862   SDValue V1 = Op.getOperand(0);
5863   SDValue V2 = Op.getOperand(1);
5864   SDLoc dl(Op);
5865   EVT VT = Op.getValueType();
5866   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5867
5868   // Convert shuffles that are directly supported on NEON to target-specific
5869   // DAG nodes, instead of keeping them as shuffles and matching them again
5870   // during code selection.  This is more efficient and avoids the possibility
5871   // of inconsistencies between legalization and selection.
5872   // FIXME: floating-point vectors should be canonicalized to integer vectors
5873   // of the same time so that they get CSEd properly.
5874   ArrayRef<int> ShuffleMask = SVN->getMask();
5875
5876   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5877   if (EltSize <= 32) {
5878     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5879       int Lane = SVN->getSplatIndex();
5880       // If this is undef splat, generate it via "just" vdup, if possible.
5881       if (Lane == -1) Lane = 0;
5882
5883       // Test if V1 is a SCALAR_TO_VECTOR.
5884       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5885         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5886       }
5887       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5888       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5889       // reaches it).
5890       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5891           !isa<ConstantSDNode>(V1.getOperand(0))) {
5892         bool IsScalarToVector = true;
5893         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5894           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5895             IsScalarToVector = false;
5896             break;
5897           }
5898         if (IsScalarToVector)
5899           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5900       }
5901       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5902                          DAG.getConstant(Lane, dl, MVT::i32));
5903     }
5904
5905     bool ReverseVEXT;
5906     unsigned Imm;
5907     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5908       if (ReverseVEXT)
5909         std::swap(V1, V2);
5910       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5911                          DAG.getConstant(Imm, dl, MVT::i32));
5912     }
5913
5914     if (isVREVMask(ShuffleMask, VT, 64))
5915       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5916     if (isVREVMask(ShuffleMask, VT, 32))
5917       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5918     if (isVREVMask(ShuffleMask, VT, 16))
5919       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5920
5921     if (V2->getOpcode() == ISD::UNDEF &&
5922         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5923       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5924                          DAG.getConstant(Imm, dl, MVT::i32));
5925     }
5926
5927     // Check for Neon shuffles that modify both input vectors in place.
5928     // If both results are used, i.e., if there are two shuffles with the same
5929     // source operands and with masks corresponding to both results of one of
5930     // these operations, DAG memoization will ensure that a single node is
5931     // used for both shuffles.
5932     unsigned WhichResult;
5933     bool isV_UNDEF;
5934     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5935             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5936       if (isV_UNDEF)
5937         V2 = V1;
5938       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5939           .getValue(WhichResult);
5940     }
5941
5942     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5943     // shuffles that produce a result larger than their operands with:
5944     //   shuffle(concat(v1, undef), concat(v2, undef))
5945     // ->
5946     //   shuffle(concat(v1, v2), undef)
5947     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5948     //
5949     // This is useful in the general case, but there are special cases where
5950     // native shuffles produce larger results: the two-result ops.
5951     //
5952     // Look through the concat when lowering them:
5953     //   shuffle(concat(v1, v2), undef)
5954     // ->
5955     //   concat(VZIP(v1, v2):0, :1)
5956     //
5957     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5958         V2->getOpcode() == ISD::UNDEF) {
5959       SDValue SubV1 = V1->getOperand(0);
5960       SDValue SubV2 = V1->getOperand(1);
5961       EVT SubVT = SubV1.getValueType();
5962
5963       // We expect these to have been canonicalized to -1.
5964       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5965         return i < (int)VT.getVectorNumElements();
5966       }) && "Unexpected shuffle index into UNDEF operand!");
5967
5968       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5969               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5970         if (isV_UNDEF)
5971           SubV2 = SubV1;
5972         assert((WhichResult == 0) &&
5973                "In-place shuffle of concat can only have one result!");
5974         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5975                                   SubV1, SubV2);
5976         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5977                            Res.getValue(1));
5978       }
5979     }
5980   }
5981
5982   // If the shuffle is not directly supported and it has 4 elements, use
5983   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5984   unsigned NumElts = VT.getVectorNumElements();
5985   if (NumElts == 4) {
5986     unsigned PFIndexes[4];
5987     for (unsigned i = 0; i != 4; ++i) {
5988       if (ShuffleMask[i] < 0)
5989         PFIndexes[i] = 8;
5990       else
5991         PFIndexes[i] = ShuffleMask[i];
5992     }
5993
5994     // Compute the index in the perfect shuffle table.
5995     unsigned PFTableIndex =
5996       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5997     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5998     unsigned Cost = (PFEntry >> 30);
5999
6000     if (Cost <= 4)
6001       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6002   }
6003
6004   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6005   if (EltSize >= 32) {
6006     // Do the expansion with floating-point types, since that is what the VFP
6007     // registers are defined to use, and since i64 is not legal.
6008     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6009     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6010     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6011     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6012     SmallVector<SDValue, 8> Ops;
6013     for (unsigned i = 0; i < NumElts; ++i) {
6014       if (ShuffleMask[i] < 0)
6015         Ops.push_back(DAG.getUNDEF(EltVT));
6016       else
6017         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6018                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6019                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6020                                                   dl, MVT::i32)));
6021     }
6022     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6023     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6024   }
6025
6026   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6027     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6028
6029   if (VT == MVT::v8i8) {
6030     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6031     if (NewOp.getNode())
6032       return NewOp;
6033   }
6034
6035   return SDValue();
6036 }
6037
6038 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6039   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6040   SDValue Lane = Op.getOperand(2);
6041   if (!isa<ConstantSDNode>(Lane))
6042     return SDValue();
6043
6044   return Op;
6045 }
6046
6047 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6048   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6049   SDValue Lane = Op.getOperand(1);
6050   if (!isa<ConstantSDNode>(Lane))
6051     return SDValue();
6052
6053   SDValue Vec = Op.getOperand(0);
6054   if (Op.getValueType() == MVT::i32 &&
6055       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6056     SDLoc dl(Op);
6057     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6058   }
6059
6060   return Op;
6061 }
6062
6063 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6064   // The only time a CONCAT_VECTORS operation can have legal types is when
6065   // two 64-bit vectors are concatenated to a 128-bit vector.
6066   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6067          "unexpected CONCAT_VECTORS");
6068   SDLoc dl(Op);
6069   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6070   SDValue Op0 = Op.getOperand(0);
6071   SDValue Op1 = Op.getOperand(1);
6072   if (Op0.getOpcode() != ISD::UNDEF)
6073     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6074                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6075                       DAG.getIntPtrConstant(0, dl));
6076   if (Op1.getOpcode() != ISD::UNDEF)
6077     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6078                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6079                       DAG.getIntPtrConstant(1, dl));
6080   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6081 }
6082
6083 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6084 /// element has been zero/sign-extended, depending on the isSigned parameter,
6085 /// from an integer type half its size.
6086 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6087                                    bool isSigned) {
6088   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6089   EVT VT = N->getValueType(0);
6090   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6091     SDNode *BVN = N->getOperand(0).getNode();
6092     if (BVN->getValueType(0) != MVT::v4i32 ||
6093         BVN->getOpcode() != ISD::BUILD_VECTOR)
6094       return false;
6095     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6096     unsigned HiElt = 1 - LoElt;
6097     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6098     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6099     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6100     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6101     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6102       return false;
6103     if (isSigned) {
6104       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6105           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6106         return true;
6107     } else {
6108       if (Hi0->isNullValue() && Hi1->isNullValue())
6109         return true;
6110     }
6111     return false;
6112   }
6113
6114   if (N->getOpcode() != ISD::BUILD_VECTOR)
6115     return false;
6116
6117   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6118     SDNode *Elt = N->getOperand(i).getNode();
6119     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6120       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6121       unsigned HalfSize = EltSize / 2;
6122       if (isSigned) {
6123         if (!isIntN(HalfSize, C->getSExtValue()))
6124           return false;
6125       } else {
6126         if (!isUIntN(HalfSize, C->getZExtValue()))
6127           return false;
6128       }
6129       continue;
6130     }
6131     return false;
6132   }
6133
6134   return true;
6135 }
6136
6137 /// isSignExtended - Check if a node is a vector value that is sign-extended
6138 /// or a constant BUILD_VECTOR with sign-extended elements.
6139 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6140   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6141     return true;
6142   if (isExtendedBUILD_VECTOR(N, DAG, true))
6143     return true;
6144   return false;
6145 }
6146
6147 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6148 /// or a constant BUILD_VECTOR with zero-extended elements.
6149 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6150   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6151     return true;
6152   if (isExtendedBUILD_VECTOR(N, DAG, false))
6153     return true;
6154   return false;
6155 }
6156
6157 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6158   if (OrigVT.getSizeInBits() >= 64)
6159     return OrigVT;
6160
6161   assert(OrigVT.isSimple() && "Expecting a simple value type");
6162
6163   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6164   switch (OrigSimpleTy) {
6165   default: llvm_unreachable("Unexpected Vector Type");
6166   case MVT::v2i8:
6167   case MVT::v2i16:
6168      return MVT::v2i32;
6169   case MVT::v4i8:
6170     return  MVT::v4i16;
6171   }
6172 }
6173
6174 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6175 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6176 /// We insert the required extension here to get the vector to fill a D register.
6177 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6178                                             const EVT &OrigTy,
6179                                             const EVT &ExtTy,
6180                                             unsigned ExtOpcode) {
6181   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6182   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6183   // 64-bits we need to insert a new extension so that it will be 64-bits.
6184   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6185   if (OrigTy.getSizeInBits() >= 64)
6186     return N;
6187
6188   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6189   EVT NewVT = getExtensionTo64Bits(OrigTy);
6190
6191   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6192 }
6193
6194 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6195 /// does not do any sign/zero extension. If the original vector is less
6196 /// than 64 bits, an appropriate extension will be added after the load to
6197 /// reach a total size of 64 bits. We have to add the extension separately
6198 /// because ARM does not have a sign/zero extending load for vectors.
6199 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6200   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6201
6202   // The load already has the right type.
6203   if (ExtendedTy == LD->getMemoryVT())
6204     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6205                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6206                 LD->isNonTemporal(), LD->isInvariant(),
6207                 LD->getAlignment());
6208
6209   // We need to create a zextload/sextload. We cannot just create a load
6210   // followed by a zext/zext node because LowerMUL is also run during normal
6211   // operation legalization where we can't create illegal types.
6212   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6213                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6214                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6215                         LD->isNonTemporal(), LD->getAlignment());
6216 }
6217
6218 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6219 /// extending load, or BUILD_VECTOR with extended elements, return the
6220 /// unextended value. The unextended vector should be 64 bits so that it can
6221 /// be used as an operand to a VMULL instruction. If the original vector size
6222 /// before extension is less than 64 bits we add a an extension to resize
6223 /// the vector to 64 bits.
6224 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6225   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6226     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6227                                         N->getOperand(0)->getValueType(0),
6228                                         N->getValueType(0),
6229                                         N->getOpcode());
6230
6231   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6232     return SkipLoadExtensionForVMULL(LD, DAG);
6233
6234   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6235   // have been legalized as a BITCAST from v4i32.
6236   if (N->getOpcode() == ISD::BITCAST) {
6237     SDNode *BVN = N->getOperand(0).getNode();
6238     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6239            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6240     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6241     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6242                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6243   }
6244   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6245   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6246   EVT VT = N->getValueType(0);
6247   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6248   unsigned NumElts = VT.getVectorNumElements();
6249   MVT TruncVT = MVT::getIntegerVT(EltSize);
6250   SmallVector<SDValue, 8> Ops;
6251   SDLoc dl(N);
6252   for (unsigned i = 0; i != NumElts; ++i) {
6253     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6254     const APInt &CInt = C->getAPIntValue();
6255     // Element types smaller than 32 bits are not legal, so use i32 elements.
6256     // The values are implicitly truncated so sext vs. zext doesn't matter.
6257     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6258   }
6259   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6260                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6261 }
6262
6263 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6264   unsigned Opcode = N->getOpcode();
6265   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6266     SDNode *N0 = N->getOperand(0).getNode();
6267     SDNode *N1 = N->getOperand(1).getNode();
6268     return N0->hasOneUse() && N1->hasOneUse() &&
6269       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6270   }
6271   return false;
6272 }
6273
6274 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6275   unsigned Opcode = N->getOpcode();
6276   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6277     SDNode *N0 = N->getOperand(0).getNode();
6278     SDNode *N1 = N->getOperand(1).getNode();
6279     return N0->hasOneUse() && N1->hasOneUse() &&
6280       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6281   }
6282   return false;
6283 }
6284
6285 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6286   // Multiplications are only custom-lowered for 128-bit vectors so that
6287   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6288   EVT VT = Op.getValueType();
6289   assert(VT.is128BitVector() && VT.isInteger() &&
6290          "unexpected type for custom-lowering ISD::MUL");
6291   SDNode *N0 = Op.getOperand(0).getNode();
6292   SDNode *N1 = Op.getOperand(1).getNode();
6293   unsigned NewOpc = 0;
6294   bool isMLA = false;
6295   bool isN0SExt = isSignExtended(N0, DAG);
6296   bool isN1SExt = isSignExtended(N1, DAG);
6297   if (isN0SExt && isN1SExt)
6298     NewOpc = ARMISD::VMULLs;
6299   else {
6300     bool isN0ZExt = isZeroExtended(N0, DAG);
6301     bool isN1ZExt = isZeroExtended(N1, DAG);
6302     if (isN0ZExt && isN1ZExt)
6303       NewOpc = ARMISD::VMULLu;
6304     else if (isN1SExt || isN1ZExt) {
6305       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6306       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6307       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6308         NewOpc = ARMISD::VMULLs;
6309         isMLA = true;
6310       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6311         NewOpc = ARMISD::VMULLu;
6312         isMLA = true;
6313       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6314         std::swap(N0, N1);
6315         NewOpc = ARMISD::VMULLu;
6316         isMLA = true;
6317       }
6318     }
6319
6320     if (!NewOpc) {
6321       if (VT == MVT::v2i64)
6322         // Fall through to expand this.  It is not legal.
6323         return SDValue();
6324       else
6325         // Other vector multiplications are legal.
6326         return Op;
6327     }
6328   }
6329
6330   // Legalize to a VMULL instruction.
6331   SDLoc DL(Op);
6332   SDValue Op0;
6333   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6334   if (!isMLA) {
6335     Op0 = SkipExtensionForVMULL(N0, DAG);
6336     assert(Op0.getValueType().is64BitVector() &&
6337            Op1.getValueType().is64BitVector() &&
6338            "unexpected types for extended operands to VMULL");
6339     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6340   }
6341
6342   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6343   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6344   //   vmull q0, d4, d6
6345   //   vmlal q0, d5, d6
6346   // is faster than
6347   //   vaddl q0, d4, d5
6348   //   vmovl q1, d6
6349   //   vmul  q0, q0, q1
6350   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6351   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6352   EVT Op1VT = Op1.getValueType();
6353   return DAG.getNode(N0->getOpcode(), DL, VT,
6354                      DAG.getNode(NewOpc, DL, VT,
6355                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6356                      DAG.getNode(NewOpc, DL, VT,
6357                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6358 }
6359
6360 static SDValue
6361 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6362   // Convert to float
6363   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6364   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6365   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6366   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6367   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6368   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6369   // Get reciprocal estimate.
6370   // float4 recip = vrecpeq_f32(yf);
6371   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6372                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6373                    Y);
6374   // Because char has a smaller range than uchar, we can actually get away
6375   // without any newton steps.  This requires that we use a weird bias
6376   // of 0xb000, however (again, this has been exhaustively tested).
6377   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6378   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6379   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6380   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6381   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6382   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6383   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6384   // Convert back to short.
6385   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6386   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6387   return X;
6388 }
6389
6390 static SDValue
6391 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6392   SDValue N2;
6393   // Convert to float.
6394   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6395   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6396   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6397   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6398   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6399   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6400
6401   // Use reciprocal estimate and one refinement step.
6402   // float4 recip = vrecpeq_f32(yf);
6403   // recip *= vrecpsq_f32(yf, recip);
6404   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6405                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6406                    N1);
6407   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6408                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6409                    N1, N2);
6410   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6411   // Because short has a smaller range than ushort, we can actually get away
6412   // with only a single newton step.  This requires that we use a weird bias
6413   // of 89, however (again, this has been exhaustively tested).
6414   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6415   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6416   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6417   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6418   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6419   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6420   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6421   // Convert back to integer and return.
6422   // return vmovn_s32(vcvt_s32_f32(result));
6423   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6424   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6425   return N0;
6426 }
6427
6428 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6429   EVT VT = Op.getValueType();
6430   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6431          "unexpected type for custom-lowering ISD::SDIV");
6432
6433   SDLoc dl(Op);
6434   SDValue N0 = Op.getOperand(0);
6435   SDValue N1 = Op.getOperand(1);
6436   SDValue N2, N3;
6437
6438   if (VT == MVT::v8i8) {
6439     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6440     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6441
6442     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6443                      DAG.getIntPtrConstant(4, dl));
6444     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6445                      DAG.getIntPtrConstant(4, dl));
6446     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6447                      DAG.getIntPtrConstant(0, dl));
6448     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6449                      DAG.getIntPtrConstant(0, dl));
6450
6451     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6452     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6453
6454     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6455     N0 = LowerCONCAT_VECTORS(N0, DAG);
6456
6457     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6458     return N0;
6459   }
6460   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6461 }
6462
6463 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6464   EVT VT = Op.getValueType();
6465   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6466          "unexpected type for custom-lowering ISD::UDIV");
6467
6468   SDLoc dl(Op);
6469   SDValue N0 = Op.getOperand(0);
6470   SDValue N1 = Op.getOperand(1);
6471   SDValue N2, N3;
6472
6473   if (VT == MVT::v8i8) {
6474     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6475     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6476
6477     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6478                      DAG.getIntPtrConstant(4, dl));
6479     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6480                      DAG.getIntPtrConstant(4, dl));
6481     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6482                      DAG.getIntPtrConstant(0, dl));
6483     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6484                      DAG.getIntPtrConstant(0, dl));
6485
6486     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6487     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6488
6489     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6490     N0 = LowerCONCAT_VECTORS(N0, DAG);
6491
6492     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6493                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6494                                      MVT::i32),
6495                      N0);
6496     return N0;
6497   }
6498
6499   // v4i16 sdiv ... Convert to float.
6500   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6501   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6502   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6503   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6504   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6505   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6506
6507   // Use reciprocal estimate and two refinement steps.
6508   // float4 recip = vrecpeq_f32(yf);
6509   // recip *= vrecpsq_f32(yf, recip);
6510   // recip *= vrecpsq_f32(yf, recip);
6511   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6512                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6513                    BN1);
6514   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6515                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6516                    BN1, N2);
6517   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6518   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6519                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6520                    BN1, N2);
6521   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6522   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6523   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6524   // and that it will never cause us to return an answer too large).
6525   // float4 result = as_float4(as_int4(xf*recip) + 2);
6526   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6527   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6528   N1 = DAG.getConstant(2, dl, MVT::i32);
6529   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6530   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6531   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6532   // Convert back to integer and return.
6533   // return vmovn_u32(vcvt_s32_f32(result));
6534   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6535   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6536   return N0;
6537 }
6538
6539 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6540   EVT VT = Op.getNode()->getValueType(0);
6541   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6542
6543   unsigned Opc;
6544   bool ExtraOp = false;
6545   switch (Op.getOpcode()) {
6546   default: llvm_unreachable("Invalid code");
6547   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6548   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6549   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6550   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6551   }
6552
6553   if (!ExtraOp)
6554     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6555                        Op.getOperand(1));
6556   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6557                      Op.getOperand(1), Op.getOperand(2));
6558 }
6559
6560 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6561   assert(Subtarget->isTargetDarwin());
6562
6563   // For iOS, we want to call an alternative entry point: __sincos_stret,
6564   // return values are passed via sret.
6565   SDLoc dl(Op);
6566   SDValue Arg = Op.getOperand(0);
6567   EVT ArgVT = Arg.getValueType();
6568   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6569   auto PtrVT = getPointerTy(DAG.getDataLayout());
6570
6571   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6572
6573   // Pair of floats / doubles used to pass the result.
6574   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6575
6576   // Create stack object for sret.
6577   auto &DL = DAG.getDataLayout();
6578   const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6579   const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6580   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6581   SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6582
6583   ArgListTy Args;
6584   ArgListEntry Entry;
6585
6586   Entry.Node = SRet;
6587   Entry.Ty = RetTy->getPointerTo();
6588   Entry.isSExt = false;
6589   Entry.isZExt = false;
6590   Entry.isSRet = true;
6591   Args.push_back(Entry);
6592
6593   Entry.Node = Arg;
6594   Entry.Ty = ArgTy;
6595   Entry.isSExt = false;
6596   Entry.isZExt = false;
6597   Args.push_back(Entry);
6598
6599   const char *LibcallName  = (ArgVT == MVT::f64)
6600   ? "__sincos_stret" : "__sincosf_stret";
6601   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6602
6603   TargetLowering::CallLoweringInfo CLI(DAG);
6604   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6605     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6606                std::move(Args), 0)
6607     .setDiscardResult();
6608
6609   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6610
6611   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6612                                 MachinePointerInfo(), false, false, false, 0);
6613
6614   // Address of cos field.
6615   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6616                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6617   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6618                                 MachinePointerInfo(), false, false, false, 0);
6619
6620   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6621   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6622                      LoadSin.getValue(0), LoadCos.getValue(0));
6623 }
6624
6625 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6626   // Monotonic load/store is legal for all targets
6627   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6628     return Op;
6629
6630   // Acquire/Release load/store is not legal for targets without a
6631   // dmb or equivalent available.
6632   return SDValue();
6633 }
6634
6635 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6636                                     SmallVectorImpl<SDValue> &Results,
6637                                     SelectionDAG &DAG,
6638                                     const ARMSubtarget *Subtarget) {
6639   SDLoc DL(N);
6640   SDValue Cycles32, OutChain;
6641
6642   if (Subtarget->hasPerfMon()) {
6643     // Under Power Management extensions, the cycle-count is:
6644     //    mrc p15, #0, <Rt>, c9, c13, #0
6645     SDValue Ops[] = { N->getOperand(0), // Chain
6646                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6647                       DAG.getConstant(15, DL, MVT::i32),
6648                       DAG.getConstant(0, DL, MVT::i32),
6649                       DAG.getConstant(9, DL, MVT::i32),
6650                       DAG.getConstant(13, DL, MVT::i32),
6651                       DAG.getConstant(0, DL, MVT::i32)
6652     };
6653
6654     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6655                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6656     OutChain = Cycles32.getValue(1);
6657   } else {
6658     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6659     // there are older ARM CPUs that have implementation-specific ways of
6660     // obtaining this information (FIXME!).
6661     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6662     OutChain = DAG.getEntryNode();
6663   }
6664
6665
6666   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6667                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6668   Results.push_back(Cycles64);
6669   Results.push_back(OutChain);
6670 }
6671
6672 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6673   switch (Op.getOpcode()) {
6674   default: llvm_unreachable("Don't know how to custom lower this!");
6675   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6676   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6677   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6678   case ISD::GlobalAddress:
6679     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6680     default: llvm_unreachable("unknown object format");
6681     case Triple::COFF:
6682       return LowerGlobalAddressWindows(Op, DAG);
6683     case Triple::ELF:
6684       return LowerGlobalAddressELF(Op, DAG);
6685     case Triple::MachO:
6686       return LowerGlobalAddressDarwin(Op, DAG);
6687     }
6688   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6689   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6690   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6691   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6692   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6693   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6694   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6695   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6696   case ISD::SINT_TO_FP:
6697   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6698   case ISD::FP_TO_SINT:
6699   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6700   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6701   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6702   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6703   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6704   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6705   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6706   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6707   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6708                                                                Subtarget);
6709   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6710   case ISD::SHL:
6711   case ISD::SRL:
6712   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6713   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6714   case ISD::SRL_PARTS:
6715   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6716   case ISD::CTTZ:
6717   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6718   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6719   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6720   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6721   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6722   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6723   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6724   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6725   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6726   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6727   case ISD::MUL:           return LowerMUL(Op, DAG);
6728   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6729   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6730   case ISD::ADDC:
6731   case ISD::ADDE:
6732   case ISD::SUBC:
6733   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6734   case ISD::SADDO:
6735   case ISD::UADDO:
6736   case ISD::SSUBO:
6737   case ISD::USUBO:
6738     return LowerXALUO(Op, DAG);
6739   case ISD::ATOMIC_LOAD:
6740   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6741   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6742   case ISD::SDIVREM:
6743   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6744   case ISD::DYNAMIC_STACKALLOC:
6745     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6746       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6747     llvm_unreachable("Don't know how to custom lower this!");
6748   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6749   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6750   }
6751 }
6752
6753 /// ReplaceNodeResults - Replace the results of node with an illegal result
6754 /// type with new values built out of custom code.
6755 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6756                                            SmallVectorImpl<SDValue>&Results,
6757                                            SelectionDAG &DAG) const {
6758   SDValue Res;
6759   switch (N->getOpcode()) {
6760   default:
6761     llvm_unreachable("Don't know how to custom expand this!");
6762   case ISD::READ_REGISTER:
6763     ExpandREAD_REGISTER(N, Results, DAG);
6764     break;
6765   case ISD::BITCAST:
6766     Res = ExpandBITCAST(N, DAG);
6767     break;
6768   case ISD::SRL:
6769   case ISD::SRA:
6770     Res = Expand64BitShift(N, DAG, Subtarget);
6771     break;
6772   case ISD::READCYCLECOUNTER:
6773     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6774     return;
6775   }
6776   if (Res.getNode())
6777     Results.push_back(Res);
6778 }
6779
6780 //===----------------------------------------------------------------------===//
6781 //                           ARM Scheduler Hooks
6782 //===----------------------------------------------------------------------===//
6783
6784 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6785 /// registers the function context.
6786 void ARMTargetLowering::
6787 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6788                        MachineBasicBlock *DispatchBB, int FI) const {
6789   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6790   DebugLoc dl = MI->getDebugLoc();
6791   MachineFunction *MF = MBB->getParent();
6792   MachineRegisterInfo *MRI = &MF->getRegInfo();
6793   MachineConstantPool *MCP = MF->getConstantPool();
6794   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6795   const Function *F = MF->getFunction();
6796
6797   bool isThumb = Subtarget->isThumb();
6798   bool isThumb2 = Subtarget->isThumb2();
6799
6800   unsigned PCLabelId = AFI->createPICLabelUId();
6801   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6802   ARMConstantPoolValue *CPV =
6803     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6804   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6805
6806   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6807                                            : &ARM::GPRRegClass;
6808
6809   // Grab constant pool and fixed stack memory operands.
6810   MachineMemOperand *CPMMO =
6811       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6812                                MachineMemOperand::MOLoad, 4, 4);
6813
6814   MachineMemOperand *FIMMOSt =
6815       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6816                                MachineMemOperand::MOStore, 4, 4);
6817
6818   // Load the address of the dispatch MBB into the jump buffer.
6819   if (isThumb2) {
6820     // Incoming value: jbuf
6821     //   ldr.n  r5, LCPI1_1
6822     //   orr    r5, r5, #1
6823     //   add    r5, pc
6824     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6825     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6826     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6827                    .addConstantPoolIndex(CPI)
6828                    .addMemOperand(CPMMO));
6829     // Set the low bit because of thumb mode.
6830     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6831     AddDefaultCC(
6832       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6833                      .addReg(NewVReg1, RegState::Kill)
6834                      .addImm(0x01)));
6835     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6836     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6837       .addReg(NewVReg2, RegState::Kill)
6838       .addImm(PCLabelId);
6839     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6840                    .addReg(NewVReg3, RegState::Kill)
6841                    .addFrameIndex(FI)
6842                    .addImm(36)  // &jbuf[1] :: pc
6843                    .addMemOperand(FIMMOSt));
6844   } else if (isThumb) {
6845     // Incoming value: jbuf
6846     //   ldr.n  r1, LCPI1_4
6847     //   add    r1, pc
6848     //   mov    r2, #1
6849     //   orrs   r1, r2
6850     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6851     //   str    r1, [r2]
6852     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6853     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6854                    .addConstantPoolIndex(CPI)
6855                    .addMemOperand(CPMMO));
6856     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6857     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6858       .addReg(NewVReg1, RegState::Kill)
6859       .addImm(PCLabelId);
6860     // Set the low bit because of thumb mode.
6861     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6862     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6863                    .addReg(ARM::CPSR, RegState::Define)
6864                    .addImm(1));
6865     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6866     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6867                    .addReg(ARM::CPSR, RegState::Define)
6868                    .addReg(NewVReg2, RegState::Kill)
6869                    .addReg(NewVReg3, RegState::Kill));
6870     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6871     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6872             .addFrameIndex(FI)
6873             .addImm(36); // &jbuf[1] :: pc
6874     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6875                    .addReg(NewVReg4, RegState::Kill)
6876                    .addReg(NewVReg5, RegState::Kill)
6877                    .addImm(0)
6878                    .addMemOperand(FIMMOSt));
6879   } else {
6880     // Incoming value: jbuf
6881     //   ldr  r1, LCPI1_1
6882     //   add  r1, pc, r1
6883     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6884     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6885     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6886                    .addConstantPoolIndex(CPI)
6887                    .addImm(0)
6888                    .addMemOperand(CPMMO));
6889     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6890     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6891                    .addReg(NewVReg1, RegState::Kill)
6892                    .addImm(PCLabelId));
6893     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6894                    .addReg(NewVReg2, RegState::Kill)
6895                    .addFrameIndex(FI)
6896                    .addImm(36)  // &jbuf[1] :: pc
6897                    .addMemOperand(FIMMOSt));
6898   }
6899 }
6900
6901 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6902                                               MachineBasicBlock *MBB) const {
6903   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6904   DebugLoc dl = MI->getDebugLoc();
6905   MachineFunction *MF = MBB->getParent();
6906   MachineRegisterInfo *MRI = &MF->getRegInfo();
6907   MachineFrameInfo *MFI = MF->getFrameInfo();
6908   int FI = MFI->getFunctionContextIndex();
6909
6910   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6911                                                         : &ARM::GPRnopcRegClass;
6912
6913   // Get a mapping of the call site numbers to all of the landing pads they're
6914   // associated with.
6915   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6916   unsigned MaxCSNum = 0;
6917   MachineModuleInfo &MMI = MF->getMMI();
6918   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6919        ++BB) {
6920     if (!BB->isLandingPad()) continue;
6921
6922     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6923     // pad.
6924     for (MachineBasicBlock::iterator
6925            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6926       if (!II->isEHLabel()) continue;
6927
6928       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6929       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6930
6931       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6932       for (SmallVectorImpl<unsigned>::iterator
6933              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6934            CSI != CSE; ++CSI) {
6935         CallSiteNumToLPad[*CSI].push_back(BB);
6936         MaxCSNum = std::max(MaxCSNum, *CSI);
6937       }
6938       break;
6939     }
6940   }
6941
6942   // Get an ordered list of the machine basic blocks for the jump table.
6943   std::vector<MachineBasicBlock*> LPadList;
6944   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6945   LPadList.reserve(CallSiteNumToLPad.size());
6946   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6947     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6948     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6949            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6950       LPadList.push_back(*II);
6951       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6952     }
6953   }
6954
6955   assert(!LPadList.empty() &&
6956          "No landing pad destinations for the dispatch jump table!");
6957
6958   // Create the jump table and associated information.
6959   MachineJumpTableInfo *JTI =
6960     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6961   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6962   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6963
6964   // Create the MBBs for the dispatch code.
6965
6966   // Shove the dispatch's address into the return slot in the function context.
6967   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6968   DispatchBB->setIsLandingPad();
6969
6970   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6971   unsigned trap_opcode;
6972   if (Subtarget->isThumb())
6973     trap_opcode = ARM::tTRAP;
6974   else
6975     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6976
6977   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6978   DispatchBB->addSuccessor(TrapBB);
6979
6980   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6981   DispatchBB->addSuccessor(DispContBB);
6982
6983   // Insert and MBBs.
6984   MF->insert(MF->end(), DispatchBB);
6985   MF->insert(MF->end(), DispContBB);
6986   MF->insert(MF->end(), TrapBB);
6987
6988   // Insert code into the entry block that creates and registers the function
6989   // context.
6990   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6991
6992   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
6993       MachinePointerInfo::getFixedStack(*MF, FI),
6994       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
6995
6996   MachineInstrBuilder MIB;
6997   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6998
6999   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7000   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7001
7002   // Add a register mask with no preserved registers.  This results in all
7003   // registers being marked as clobbered.
7004   MIB.addRegMask(RI.getNoPreservedMask());
7005
7006   unsigned NumLPads = LPadList.size();
7007   if (Subtarget->isThumb2()) {
7008     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7009     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7010                    .addFrameIndex(FI)
7011                    .addImm(4)
7012                    .addMemOperand(FIMMOLd));
7013
7014     if (NumLPads < 256) {
7015       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7016                      .addReg(NewVReg1)
7017                      .addImm(LPadList.size()));
7018     } else {
7019       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7020       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7021                      .addImm(NumLPads & 0xFFFF));
7022
7023       unsigned VReg2 = VReg1;
7024       if ((NumLPads & 0xFFFF0000) != 0) {
7025         VReg2 = MRI->createVirtualRegister(TRC);
7026         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7027                        .addReg(VReg1)
7028                        .addImm(NumLPads >> 16));
7029       }
7030
7031       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7032                      .addReg(NewVReg1)
7033                      .addReg(VReg2));
7034     }
7035
7036     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7037       .addMBB(TrapBB)
7038       .addImm(ARMCC::HI)
7039       .addReg(ARM::CPSR);
7040
7041     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7042     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7043                    .addJumpTableIndex(MJTI));
7044
7045     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7046     AddDefaultCC(
7047       AddDefaultPred(
7048         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7049         .addReg(NewVReg3, RegState::Kill)
7050         .addReg(NewVReg1)
7051         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7052
7053     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7054       .addReg(NewVReg4, RegState::Kill)
7055       .addReg(NewVReg1)
7056       .addJumpTableIndex(MJTI);
7057   } else if (Subtarget->isThumb()) {
7058     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7059     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7060                    .addFrameIndex(FI)
7061                    .addImm(1)
7062                    .addMemOperand(FIMMOLd));
7063
7064     if (NumLPads < 256) {
7065       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7066                      .addReg(NewVReg1)
7067                      .addImm(NumLPads));
7068     } else {
7069       MachineConstantPool *ConstantPool = MF->getConstantPool();
7070       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7071       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7072
7073       // MachineConstantPool wants an explicit alignment.
7074       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7075       if (Align == 0)
7076         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7077       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7078
7079       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7080       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7081                      .addReg(VReg1, RegState::Define)
7082                      .addConstantPoolIndex(Idx));
7083       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7084                      .addReg(NewVReg1)
7085                      .addReg(VReg1));
7086     }
7087
7088     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7089       .addMBB(TrapBB)
7090       .addImm(ARMCC::HI)
7091       .addReg(ARM::CPSR);
7092
7093     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7094     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7095                    .addReg(ARM::CPSR, RegState::Define)
7096                    .addReg(NewVReg1)
7097                    .addImm(2));
7098
7099     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7100     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7101                    .addJumpTableIndex(MJTI));
7102
7103     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7104     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7105                    .addReg(ARM::CPSR, RegState::Define)
7106                    .addReg(NewVReg2, RegState::Kill)
7107                    .addReg(NewVReg3));
7108
7109     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7110         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7111
7112     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7113     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7114                    .addReg(NewVReg4, RegState::Kill)
7115                    .addImm(0)
7116                    .addMemOperand(JTMMOLd));
7117
7118     unsigned NewVReg6 = NewVReg5;
7119     if (RelocM == Reloc::PIC_) {
7120       NewVReg6 = MRI->createVirtualRegister(TRC);
7121       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7122                      .addReg(ARM::CPSR, RegState::Define)
7123                      .addReg(NewVReg5, RegState::Kill)
7124                      .addReg(NewVReg3));
7125     }
7126
7127     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7128       .addReg(NewVReg6, RegState::Kill)
7129       .addJumpTableIndex(MJTI);
7130   } else {
7131     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7132     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7133                    .addFrameIndex(FI)
7134                    .addImm(4)
7135                    .addMemOperand(FIMMOLd));
7136
7137     if (NumLPads < 256) {
7138       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7139                      .addReg(NewVReg1)
7140                      .addImm(NumLPads));
7141     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7142       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7143       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7144                      .addImm(NumLPads & 0xFFFF));
7145
7146       unsigned VReg2 = VReg1;
7147       if ((NumLPads & 0xFFFF0000) != 0) {
7148         VReg2 = MRI->createVirtualRegister(TRC);
7149         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7150                        .addReg(VReg1)
7151                        .addImm(NumLPads >> 16));
7152       }
7153
7154       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7155                      .addReg(NewVReg1)
7156                      .addReg(VReg2));
7157     } else {
7158       MachineConstantPool *ConstantPool = MF->getConstantPool();
7159       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7160       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7161
7162       // MachineConstantPool wants an explicit alignment.
7163       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7164       if (Align == 0)
7165         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7166       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7167
7168       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7169       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7170                      .addReg(VReg1, RegState::Define)
7171                      .addConstantPoolIndex(Idx)
7172                      .addImm(0));
7173       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7174                      .addReg(NewVReg1)
7175                      .addReg(VReg1, RegState::Kill));
7176     }
7177
7178     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7179       .addMBB(TrapBB)
7180       .addImm(ARMCC::HI)
7181       .addReg(ARM::CPSR);
7182
7183     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7184     AddDefaultCC(
7185       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7186                      .addReg(NewVReg1)
7187                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7188     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7189     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7190                    .addJumpTableIndex(MJTI));
7191
7192     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7193         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7194     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7195     AddDefaultPred(
7196       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7197       .addReg(NewVReg3, RegState::Kill)
7198       .addReg(NewVReg4)
7199       .addImm(0)
7200       .addMemOperand(JTMMOLd));
7201
7202     if (RelocM == Reloc::PIC_) {
7203       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7204         .addReg(NewVReg5, RegState::Kill)
7205         .addReg(NewVReg4)
7206         .addJumpTableIndex(MJTI);
7207     } else {
7208       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7209         .addReg(NewVReg5, RegState::Kill)
7210         .addJumpTableIndex(MJTI);
7211     }
7212   }
7213
7214   // Add the jump table entries as successors to the MBB.
7215   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7216   for (std::vector<MachineBasicBlock*>::iterator
7217          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7218     MachineBasicBlock *CurMBB = *I;
7219     if (SeenMBBs.insert(CurMBB).second)
7220       DispContBB->addSuccessor(CurMBB);
7221   }
7222
7223   // N.B. the order the invoke BBs are processed in doesn't matter here.
7224   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7225   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7226   for (MachineBasicBlock *BB : InvokeBBs) {
7227
7228     // Remove the landing pad successor from the invoke block and replace it
7229     // with the new dispatch block.
7230     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7231                                                   BB->succ_end());
7232     while (!Successors.empty()) {
7233       MachineBasicBlock *SMBB = Successors.pop_back_val();
7234       if (SMBB->isLandingPad()) {
7235         BB->removeSuccessor(SMBB);
7236         MBBLPads.push_back(SMBB);
7237       }
7238     }
7239
7240     BB->addSuccessor(DispatchBB);
7241
7242     // Find the invoke call and mark all of the callee-saved registers as
7243     // 'implicit defined' so that they're spilled. This prevents code from
7244     // moving instructions to before the EH block, where they will never be
7245     // executed.
7246     for (MachineBasicBlock::reverse_iterator
7247            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7248       if (!II->isCall()) continue;
7249
7250       DenseMap<unsigned, bool> DefRegs;
7251       for (MachineInstr::mop_iterator
7252              OI = II->operands_begin(), OE = II->operands_end();
7253            OI != OE; ++OI) {
7254         if (!OI->isReg()) continue;
7255         DefRegs[OI->getReg()] = true;
7256       }
7257
7258       MachineInstrBuilder MIB(*MF, &*II);
7259
7260       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7261         unsigned Reg = SavedRegs[i];
7262         if (Subtarget->isThumb2() &&
7263             !ARM::tGPRRegClass.contains(Reg) &&
7264             !ARM::hGPRRegClass.contains(Reg))
7265           continue;
7266         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7267           continue;
7268         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7269           continue;
7270         if (!DefRegs[Reg])
7271           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7272       }
7273
7274       break;
7275     }
7276   }
7277
7278   // Mark all former landing pads as non-landing pads. The dispatch is the only
7279   // landing pad now.
7280   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7281          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7282     (*I)->setIsLandingPad(false);
7283
7284   // The instruction is gone now.
7285   MI->eraseFromParent();
7286 }
7287
7288 static
7289 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7290   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7291        E = MBB->succ_end(); I != E; ++I)
7292     if (*I != Succ)
7293       return *I;
7294   llvm_unreachable("Expecting a BB with two successors!");
7295 }
7296
7297 /// Return the load opcode for a given load size. If load size >= 8,
7298 /// neon opcode will be returned.
7299 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7300   if (LdSize >= 8)
7301     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7302                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7303   if (IsThumb1)
7304     return LdSize == 4 ? ARM::tLDRi
7305                        : LdSize == 2 ? ARM::tLDRHi
7306                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7307   if (IsThumb2)
7308     return LdSize == 4 ? ARM::t2LDR_POST
7309                        : LdSize == 2 ? ARM::t2LDRH_POST
7310                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7311   return LdSize == 4 ? ARM::LDR_POST_IMM
7312                      : LdSize == 2 ? ARM::LDRH_POST
7313                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7314 }
7315
7316 /// Return the store opcode for a given store size. If store size >= 8,
7317 /// neon opcode will be returned.
7318 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7319   if (StSize >= 8)
7320     return StSize == 16 ? ARM::VST1q32wb_fixed
7321                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7322   if (IsThumb1)
7323     return StSize == 4 ? ARM::tSTRi
7324                        : StSize == 2 ? ARM::tSTRHi
7325                                      : StSize == 1 ? ARM::tSTRBi : 0;
7326   if (IsThumb2)
7327     return StSize == 4 ? ARM::t2STR_POST
7328                        : StSize == 2 ? ARM::t2STRH_POST
7329                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7330   return StSize == 4 ? ARM::STR_POST_IMM
7331                      : StSize == 2 ? ARM::STRH_POST
7332                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7333 }
7334
7335 /// Emit a post-increment load operation with given size. The instructions
7336 /// will be added to BB at Pos.
7337 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7338                        const TargetInstrInfo *TII, DebugLoc dl,
7339                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7340                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7341   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7342   assert(LdOpc != 0 && "Should have a load opcode");
7343   if (LdSize >= 8) {
7344     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7345                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7346                        .addImm(0));
7347   } else if (IsThumb1) {
7348     // load + update AddrIn
7349     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7350                        .addReg(AddrIn).addImm(0));
7351     MachineInstrBuilder MIB =
7352         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7353     MIB = AddDefaultT1CC(MIB);
7354     MIB.addReg(AddrIn).addImm(LdSize);
7355     AddDefaultPred(MIB);
7356   } else if (IsThumb2) {
7357     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7358                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7359                        .addImm(LdSize));
7360   } else { // arm
7361     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7362                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7363                        .addReg(0).addImm(LdSize));
7364   }
7365 }
7366
7367 /// Emit a post-increment store operation with given size. The instructions
7368 /// will be added to BB at Pos.
7369 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7370                        const TargetInstrInfo *TII, DebugLoc dl,
7371                        unsigned StSize, unsigned Data, unsigned AddrIn,
7372                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7373   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7374   assert(StOpc != 0 && "Should have a store opcode");
7375   if (StSize >= 8) {
7376     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7377                        .addReg(AddrIn).addImm(0).addReg(Data));
7378   } else if (IsThumb1) {
7379     // store + update AddrIn
7380     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7381                        .addReg(AddrIn).addImm(0));
7382     MachineInstrBuilder MIB =
7383         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7384     MIB = AddDefaultT1CC(MIB);
7385     MIB.addReg(AddrIn).addImm(StSize);
7386     AddDefaultPred(MIB);
7387   } else if (IsThumb2) {
7388     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7389                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7390   } else { // arm
7391     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7392                        .addReg(Data).addReg(AddrIn).addReg(0)
7393                        .addImm(StSize));
7394   }
7395 }
7396
7397 MachineBasicBlock *
7398 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7399                                    MachineBasicBlock *BB) const {
7400   // This pseudo instruction has 3 operands: dst, src, size
7401   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7402   // Otherwise, we will generate unrolled scalar copies.
7403   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7404   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7405   MachineFunction::iterator It = BB;
7406   ++It;
7407
7408   unsigned dest = MI->getOperand(0).getReg();
7409   unsigned src = MI->getOperand(1).getReg();
7410   unsigned SizeVal = MI->getOperand(2).getImm();
7411   unsigned Align = MI->getOperand(3).getImm();
7412   DebugLoc dl = MI->getDebugLoc();
7413
7414   MachineFunction *MF = BB->getParent();
7415   MachineRegisterInfo &MRI = MF->getRegInfo();
7416   unsigned UnitSize = 0;
7417   const TargetRegisterClass *TRC = nullptr;
7418   const TargetRegisterClass *VecTRC = nullptr;
7419
7420   bool IsThumb1 = Subtarget->isThumb1Only();
7421   bool IsThumb2 = Subtarget->isThumb2();
7422
7423   if (Align & 1) {
7424     UnitSize = 1;
7425   } else if (Align & 2) {
7426     UnitSize = 2;
7427   } else {
7428     // Check whether we can use NEON instructions.
7429     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7430         Subtarget->hasNEON()) {
7431       if ((Align % 16 == 0) && SizeVal >= 16)
7432         UnitSize = 16;
7433       else if ((Align % 8 == 0) && SizeVal >= 8)
7434         UnitSize = 8;
7435     }
7436     // Can't use NEON instructions.
7437     if (UnitSize == 0)
7438       UnitSize = 4;
7439   }
7440
7441   // Select the correct opcode and register class for unit size load/store
7442   bool IsNeon = UnitSize >= 8;
7443   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7444   if (IsNeon)
7445     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7446                             : UnitSize == 8 ? &ARM::DPRRegClass
7447                                             : nullptr;
7448
7449   unsigned BytesLeft = SizeVal % UnitSize;
7450   unsigned LoopSize = SizeVal - BytesLeft;
7451
7452   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7453     // Use LDR and STR to copy.
7454     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7455     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7456     unsigned srcIn = src;
7457     unsigned destIn = dest;
7458     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7459       unsigned srcOut = MRI.createVirtualRegister(TRC);
7460       unsigned destOut = MRI.createVirtualRegister(TRC);
7461       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7462       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7463                  IsThumb1, IsThumb2);
7464       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7465                  IsThumb1, IsThumb2);
7466       srcIn = srcOut;
7467       destIn = destOut;
7468     }
7469
7470     // Handle the leftover bytes with LDRB and STRB.
7471     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7472     // [destOut] = STRB_POST(scratch, destIn, 1)
7473     for (unsigned i = 0; i < BytesLeft; i++) {
7474       unsigned srcOut = MRI.createVirtualRegister(TRC);
7475       unsigned destOut = MRI.createVirtualRegister(TRC);
7476       unsigned scratch = MRI.createVirtualRegister(TRC);
7477       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7478                  IsThumb1, IsThumb2);
7479       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7480                  IsThumb1, IsThumb2);
7481       srcIn = srcOut;
7482       destIn = destOut;
7483     }
7484     MI->eraseFromParent();   // The instruction is gone now.
7485     return BB;
7486   }
7487
7488   // Expand the pseudo op to a loop.
7489   // thisMBB:
7490   //   ...
7491   //   movw varEnd, # --> with thumb2
7492   //   movt varEnd, #
7493   //   ldrcp varEnd, idx --> without thumb2
7494   //   fallthrough --> loopMBB
7495   // loopMBB:
7496   //   PHI varPhi, varEnd, varLoop
7497   //   PHI srcPhi, src, srcLoop
7498   //   PHI destPhi, dst, destLoop
7499   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7500   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7501   //   subs varLoop, varPhi, #UnitSize
7502   //   bne loopMBB
7503   //   fallthrough --> exitMBB
7504   // exitMBB:
7505   //   epilogue to handle left-over bytes
7506   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7507   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7508   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7509   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7510   MF->insert(It, loopMBB);
7511   MF->insert(It, exitMBB);
7512
7513   // Transfer the remainder of BB and its successor edges to exitMBB.
7514   exitMBB->splice(exitMBB->begin(), BB,
7515                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7516   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7517
7518   // Load an immediate to varEnd.
7519   unsigned varEnd = MRI.createVirtualRegister(TRC);
7520   if (Subtarget->useMovt(*MF)) {
7521     unsigned Vtmp = varEnd;
7522     if ((LoopSize & 0xFFFF0000) != 0)
7523       Vtmp = MRI.createVirtualRegister(TRC);
7524     AddDefaultPred(BuildMI(BB, dl,
7525                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7526                            Vtmp).addImm(LoopSize & 0xFFFF));
7527
7528     if ((LoopSize & 0xFFFF0000) != 0)
7529       AddDefaultPred(BuildMI(BB, dl,
7530                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7531                              varEnd)
7532                          .addReg(Vtmp)
7533                          .addImm(LoopSize >> 16));
7534   } else {
7535     MachineConstantPool *ConstantPool = MF->getConstantPool();
7536     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7537     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7538
7539     // MachineConstantPool wants an explicit alignment.
7540     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7541     if (Align == 0)
7542       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7543     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7544
7545     if (IsThumb1)
7546       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7547           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7548     else
7549       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7550           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7551   }
7552   BB->addSuccessor(loopMBB);
7553
7554   // Generate the loop body:
7555   //   varPhi = PHI(varLoop, varEnd)
7556   //   srcPhi = PHI(srcLoop, src)
7557   //   destPhi = PHI(destLoop, dst)
7558   MachineBasicBlock *entryBB = BB;
7559   BB = loopMBB;
7560   unsigned varLoop = MRI.createVirtualRegister(TRC);
7561   unsigned varPhi = MRI.createVirtualRegister(TRC);
7562   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7563   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7564   unsigned destLoop = MRI.createVirtualRegister(TRC);
7565   unsigned destPhi = MRI.createVirtualRegister(TRC);
7566
7567   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7568     .addReg(varLoop).addMBB(loopMBB)
7569     .addReg(varEnd).addMBB(entryBB);
7570   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7571     .addReg(srcLoop).addMBB(loopMBB)
7572     .addReg(src).addMBB(entryBB);
7573   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7574     .addReg(destLoop).addMBB(loopMBB)
7575     .addReg(dest).addMBB(entryBB);
7576
7577   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7578   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7579   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7580   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7581              IsThumb1, IsThumb2);
7582   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7583              IsThumb1, IsThumb2);
7584
7585   // Decrement loop variable by UnitSize.
7586   if (IsThumb1) {
7587     MachineInstrBuilder MIB =
7588         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7589     MIB = AddDefaultT1CC(MIB);
7590     MIB.addReg(varPhi).addImm(UnitSize);
7591     AddDefaultPred(MIB);
7592   } else {
7593     MachineInstrBuilder MIB =
7594         BuildMI(*BB, BB->end(), dl,
7595                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7596     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7597     MIB->getOperand(5).setReg(ARM::CPSR);
7598     MIB->getOperand(5).setIsDef(true);
7599   }
7600   BuildMI(*BB, BB->end(), dl,
7601           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7602       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7603
7604   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7605   BB->addSuccessor(loopMBB);
7606   BB->addSuccessor(exitMBB);
7607
7608   // Add epilogue to handle BytesLeft.
7609   BB = exitMBB;
7610   MachineInstr *StartOfExit = exitMBB->begin();
7611
7612   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7613   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7614   unsigned srcIn = srcLoop;
7615   unsigned destIn = destLoop;
7616   for (unsigned i = 0; i < BytesLeft; i++) {
7617     unsigned srcOut = MRI.createVirtualRegister(TRC);
7618     unsigned destOut = MRI.createVirtualRegister(TRC);
7619     unsigned scratch = MRI.createVirtualRegister(TRC);
7620     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7621                IsThumb1, IsThumb2);
7622     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7623                IsThumb1, IsThumb2);
7624     srcIn = srcOut;
7625     destIn = destOut;
7626   }
7627
7628   MI->eraseFromParent();   // The instruction is gone now.
7629   return BB;
7630 }
7631
7632 MachineBasicBlock *
7633 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7634                                        MachineBasicBlock *MBB) const {
7635   const TargetMachine &TM = getTargetMachine();
7636   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7637   DebugLoc DL = MI->getDebugLoc();
7638
7639   assert(Subtarget->isTargetWindows() &&
7640          "__chkstk is only supported on Windows");
7641   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7642
7643   // __chkstk takes the number of words to allocate on the stack in R4, and
7644   // returns the stack adjustment in number of bytes in R4.  This will not
7645   // clober any other registers (other than the obvious lr).
7646   //
7647   // Although, technically, IP should be considered a register which may be
7648   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7649   // thumb-2 environment, so there is no interworking required.  As a result, we
7650   // do not expect a veneer to be emitted by the linker, clobbering IP.
7651   //
7652   // Each module receives its own copy of __chkstk, so no import thunk is
7653   // required, again, ensuring that IP is not clobbered.
7654   //
7655   // Finally, although some linkers may theoretically provide a trampoline for
7656   // out of range calls (which is quite common due to a 32M range limitation of
7657   // branches for Thumb), we can generate the long-call version via
7658   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7659   // IP.
7660
7661   switch (TM.getCodeModel()) {
7662   case CodeModel::Small:
7663   case CodeModel::Medium:
7664   case CodeModel::Default:
7665   case CodeModel::Kernel:
7666     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7667       .addImm((unsigned)ARMCC::AL).addReg(0)
7668       .addExternalSymbol("__chkstk")
7669       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7670       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7671       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7672     break;
7673   case CodeModel::Large:
7674   case CodeModel::JITDefault: {
7675     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7676     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7677
7678     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7679       .addExternalSymbol("__chkstk");
7680     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7681       .addImm((unsigned)ARMCC::AL).addReg(0)
7682       .addReg(Reg, RegState::Kill)
7683       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7684       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7685       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7686     break;
7687   }
7688   }
7689
7690   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7691                                       ARM::SP)
7692                               .addReg(ARM::SP).addReg(ARM::R4)));
7693
7694   MI->eraseFromParent();
7695   return MBB;
7696 }
7697
7698 MachineBasicBlock *
7699 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7700                                                MachineBasicBlock *BB) const {
7701   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7702   DebugLoc dl = MI->getDebugLoc();
7703   bool isThumb2 = Subtarget->isThumb2();
7704   switch (MI->getOpcode()) {
7705   default: {
7706     MI->dump();
7707     llvm_unreachable("Unexpected instr type to insert");
7708   }
7709   // The Thumb2 pre-indexed stores have the same MI operands, they just
7710   // define them differently in the .td files from the isel patterns, so
7711   // they need pseudos.
7712   case ARM::t2STR_preidx:
7713     MI->setDesc(TII->get(ARM::t2STR_PRE));
7714     return BB;
7715   case ARM::t2STRB_preidx:
7716     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7717     return BB;
7718   case ARM::t2STRH_preidx:
7719     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7720     return BB;
7721
7722   case ARM::STRi_preidx:
7723   case ARM::STRBi_preidx: {
7724     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7725       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7726     // Decode the offset.
7727     unsigned Offset = MI->getOperand(4).getImm();
7728     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7729     Offset = ARM_AM::getAM2Offset(Offset);
7730     if (isSub)
7731       Offset = -Offset;
7732
7733     MachineMemOperand *MMO = *MI->memoperands_begin();
7734     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7735       .addOperand(MI->getOperand(0))  // Rn_wb
7736       .addOperand(MI->getOperand(1))  // Rt
7737       .addOperand(MI->getOperand(2))  // Rn
7738       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7739       .addOperand(MI->getOperand(5))  // pred
7740       .addOperand(MI->getOperand(6))
7741       .addMemOperand(MMO);
7742     MI->eraseFromParent();
7743     return BB;
7744   }
7745   case ARM::STRr_preidx:
7746   case ARM::STRBr_preidx:
7747   case ARM::STRH_preidx: {
7748     unsigned NewOpc;
7749     switch (MI->getOpcode()) {
7750     default: llvm_unreachable("unexpected opcode!");
7751     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7752     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7753     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7754     }
7755     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7756     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7757       MIB.addOperand(MI->getOperand(i));
7758     MI->eraseFromParent();
7759     return BB;
7760   }
7761
7762   case ARM::tMOVCCr_pseudo: {
7763     // To "insert" a SELECT_CC instruction, we actually have to insert the
7764     // diamond control-flow pattern.  The incoming instruction knows the
7765     // destination vreg to set, the condition code register to branch on, the
7766     // true/false values to select between, and a branch opcode to use.
7767     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7768     MachineFunction::iterator It = BB;
7769     ++It;
7770
7771     //  thisMBB:
7772     //  ...
7773     //   TrueVal = ...
7774     //   cmpTY ccX, r1, r2
7775     //   bCC copy1MBB
7776     //   fallthrough --> copy0MBB
7777     MachineBasicBlock *thisMBB  = BB;
7778     MachineFunction *F = BB->getParent();
7779     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7780     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7781     F->insert(It, copy0MBB);
7782     F->insert(It, sinkMBB);
7783
7784     // Transfer the remainder of BB and its successor edges to sinkMBB.
7785     sinkMBB->splice(sinkMBB->begin(), BB,
7786                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7787     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7788
7789     BB->addSuccessor(copy0MBB);
7790     BB->addSuccessor(sinkMBB);
7791
7792     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7793       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7794
7795     //  copy0MBB:
7796     //   %FalseValue = ...
7797     //   # fallthrough to sinkMBB
7798     BB = copy0MBB;
7799
7800     // Update machine-CFG edges
7801     BB->addSuccessor(sinkMBB);
7802
7803     //  sinkMBB:
7804     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7805     //  ...
7806     BB = sinkMBB;
7807     BuildMI(*BB, BB->begin(), dl,
7808             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7809       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7810       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7811
7812     MI->eraseFromParent();   // The pseudo instruction is gone now.
7813     return BB;
7814   }
7815
7816   case ARM::BCCi64:
7817   case ARM::BCCZi64: {
7818     // If there is an unconditional branch to the other successor, remove it.
7819     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7820
7821     // Compare both parts that make up the double comparison separately for
7822     // equality.
7823     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7824
7825     unsigned LHS1 = MI->getOperand(1).getReg();
7826     unsigned LHS2 = MI->getOperand(2).getReg();
7827     if (RHSisZero) {
7828       AddDefaultPred(BuildMI(BB, dl,
7829                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7830                      .addReg(LHS1).addImm(0));
7831       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7832         .addReg(LHS2).addImm(0)
7833         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7834     } else {
7835       unsigned RHS1 = MI->getOperand(3).getReg();
7836       unsigned RHS2 = MI->getOperand(4).getReg();
7837       AddDefaultPred(BuildMI(BB, dl,
7838                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7839                      .addReg(LHS1).addReg(RHS1));
7840       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7841         .addReg(LHS2).addReg(RHS2)
7842         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7843     }
7844
7845     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7846     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7847     if (MI->getOperand(0).getImm() == ARMCC::NE)
7848       std::swap(destMBB, exitMBB);
7849
7850     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7851       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7852     if (isThumb2)
7853       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7854     else
7855       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7856
7857     MI->eraseFromParent();   // The pseudo instruction is gone now.
7858     return BB;
7859   }
7860
7861   case ARM::Int_eh_sjlj_setjmp:
7862   case ARM::Int_eh_sjlj_setjmp_nofp:
7863   case ARM::tInt_eh_sjlj_setjmp:
7864   case ARM::t2Int_eh_sjlj_setjmp:
7865   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7866     return BB;
7867
7868   case ARM::Int_eh_sjlj_setup_dispatch:
7869     EmitSjLjDispatchBlock(MI, BB);
7870     return BB;
7871
7872   case ARM::ABS:
7873   case ARM::t2ABS: {
7874     // To insert an ABS instruction, we have to insert the
7875     // diamond control-flow pattern.  The incoming instruction knows the
7876     // source vreg to test against 0, the destination vreg to set,
7877     // the condition code register to branch on, the
7878     // true/false values to select between, and a branch opcode to use.
7879     // It transforms
7880     //     V1 = ABS V0
7881     // into
7882     //     V2 = MOVS V0
7883     //     BCC                      (branch to SinkBB if V0 >= 0)
7884     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7885     //     SinkBB: V1 = PHI(V2, V3)
7886     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7887     MachineFunction::iterator BBI = BB;
7888     ++BBI;
7889     MachineFunction *Fn = BB->getParent();
7890     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7891     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7892     Fn->insert(BBI, RSBBB);
7893     Fn->insert(BBI, SinkBB);
7894
7895     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7896     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7897     bool ABSSrcKIll = MI->getOperand(1).isKill();
7898     bool isThumb2 = Subtarget->isThumb2();
7899     MachineRegisterInfo &MRI = Fn->getRegInfo();
7900     // In Thumb mode S must not be specified if source register is the SP or
7901     // PC and if destination register is the SP, so restrict register class
7902     unsigned NewRsbDstReg =
7903       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7904
7905     // Transfer the remainder of BB and its successor edges to sinkMBB.
7906     SinkBB->splice(SinkBB->begin(), BB,
7907                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7908     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7909
7910     BB->addSuccessor(RSBBB);
7911     BB->addSuccessor(SinkBB);
7912
7913     // fall through to SinkMBB
7914     RSBBB->addSuccessor(SinkBB);
7915
7916     // insert a cmp at the end of BB
7917     AddDefaultPred(BuildMI(BB, dl,
7918                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7919                    .addReg(ABSSrcReg).addImm(0));
7920
7921     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7922     BuildMI(BB, dl,
7923       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7924       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7925
7926     // insert rsbri in RSBBB
7927     // Note: BCC and rsbri will be converted into predicated rsbmi
7928     // by if-conversion pass
7929     BuildMI(*RSBBB, RSBBB->begin(), dl,
7930       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7931       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7932       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7933
7934     // insert PHI in SinkBB,
7935     // reuse ABSDstReg to not change uses of ABS instruction
7936     BuildMI(*SinkBB, SinkBB->begin(), dl,
7937       TII->get(ARM::PHI), ABSDstReg)
7938       .addReg(NewRsbDstReg).addMBB(RSBBB)
7939       .addReg(ABSSrcReg).addMBB(BB);
7940
7941     // remove ABS instruction
7942     MI->eraseFromParent();
7943
7944     // return last added BB
7945     return SinkBB;
7946   }
7947   case ARM::COPY_STRUCT_BYVAL_I32:
7948     ++NumLoopByVals;
7949     return EmitStructByval(MI, BB);
7950   case ARM::WIN__CHKSTK:
7951     return EmitLowered__chkstk(MI, BB);
7952   }
7953 }
7954
7955 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7956                                                       SDNode *Node) const {
7957   const MCInstrDesc *MCID = &MI->getDesc();
7958   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7959   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7960   // operand is still set to noreg. If needed, set the optional operand's
7961   // register to CPSR, and remove the redundant implicit def.
7962   //
7963   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7964
7965   // Rename pseudo opcodes.
7966   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7967   if (NewOpc) {
7968     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7969     MCID = &TII->get(NewOpc);
7970
7971     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7972            "converted opcode should be the same except for cc_out");
7973
7974     MI->setDesc(*MCID);
7975
7976     // Add the optional cc_out operand
7977     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7978   }
7979   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7980
7981   // Any ARM instruction that sets the 's' bit should specify an optional
7982   // "cc_out" operand in the last operand position.
7983   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7984     assert(!NewOpc && "Optional cc_out operand required");
7985     return;
7986   }
7987   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7988   // since we already have an optional CPSR def.
7989   bool definesCPSR = false;
7990   bool deadCPSR = false;
7991   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7992        i != e; ++i) {
7993     const MachineOperand &MO = MI->getOperand(i);
7994     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7995       definesCPSR = true;
7996       if (MO.isDead())
7997         deadCPSR = true;
7998       MI->RemoveOperand(i);
7999       break;
8000     }
8001   }
8002   if (!definesCPSR) {
8003     assert(!NewOpc && "Optional cc_out operand required");
8004     return;
8005   }
8006   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8007   if (deadCPSR) {
8008     assert(!MI->getOperand(ccOutIdx).getReg() &&
8009            "expect uninitialized optional cc_out operand");
8010     return;
8011   }
8012
8013   // If this instruction was defined with an optional CPSR def and its dag node
8014   // had a live implicit CPSR def, then activate the optional CPSR def.
8015   MachineOperand &MO = MI->getOperand(ccOutIdx);
8016   MO.setReg(ARM::CPSR);
8017   MO.setIsDef(true);
8018 }
8019
8020 //===----------------------------------------------------------------------===//
8021 //                           ARM Optimization Hooks
8022 //===----------------------------------------------------------------------===//
8023
8024 // Helper function that checks if N is a null or all ones constant.
8025 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8026   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8027   if (!C)
8028     return false;
8029   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8030 }
8031
8032 // Return true if N is conditionally 0 or all ones.
8033 // Detects these expressions where cc is an i1 value:
8034 //
8035 //   (select cc 0, y)   [AllOnes=0]
8036 //   (select cc y, 0)   [AllOnes=0]
8037 //   (zext cc)          [AllOnes=0]
8038 //   (sext cc)          [AllOnes=0/1]
8039 //   (select cc -1, y)  [AllOnes=1]
8040 //   (select cc y, -1)  [AllOnes=1]
8041 //
8042 // Invert is set when N is the null/all ones constant when CC is false.
8043 // OtherOp is set to the alternative value of N.
8044 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8045                                        SDValue &CC, bool &Invert,
8046                                        SDValue &OtherOp,
8047                                        SelectionDAG &DAG) {
8048   switch (N->getOpcode()) {
8049   default: return false;
8050   case ISD::SELECT: {
8051     CC = N->getOperand(0);
8052     SDValue N1 = N->getOperand(1);
8053     SDValue N2 = N->getOperand(2);
8054     if (isZeroOrAllOnes(N1, AllOnes)) {
8055       Invert = false;
8056       OtherOp = N2;
8057       return true;
8058     }
8059     if (isZeroOrAllOnes(N2, AllOnes)) {
8060       Invert = true;
8061       OtherOp = N1;
8062       return true;
8063     }
8064     return false;
8065   }
8066   case ISD::ZERO_EXTEND:
8067     // (zext cc) can never be the all ones value.
8068     if (AllOnes)
8069       return false;
8070     // Fall through.
8071   case ISD::SIGN_EXTEND: {
8072     SDLoc dl(N);
8073     EVT VT = N->getValueType(0);
8074     CC = N->getOperand(0);
8075     if (CC.getValueType() != MVT::i1)
8076       return false;
8077     Invert = !AllOnes;
8078     if (AllOnes)
8079       // When looking for an AllOnes constant, N is an sext, and the 'other'
8080       // value is 0.
8081       OtherOp = DAG.getConstant(0, dl, VT);
8082     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8083       // When looking for a 0 constant, N can be zext or sext.
8084       OtherOp = DAG.getConstant(1, dl, VT);
8085     else
8086       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8087                                 VT);
8088     return true;
8089   }
8090   }
8091 }
8092
8093 // Combine a constant select operand into its use:
8094 //
8095 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8096 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8097 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8098 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8099 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8100 //
8101 // The transform is rejected if the select doesn't have a constant operand that
8102 // is null, or all ones when AllOnes is set.
8103 //
8104 // Also recognize sext/zext from i1:
8105 //
8106 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8107 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8108 //
8109 // These transformations eventually create predicated instructions.
8110 //
8111 // @param N       The node to transform.
8112 // @param Slct    The N operand that is a select.
8113 // @param OtherOp The other N operand (x above).
8114 // @param DCI     Context.
8115 // @param AllOnes Require the select constant to be all ones instead of null.
8116 // @returns The new node, or SDValue() on failure.
8117 static
8118 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8119                             TargetLowering::DAGCombinerInfo &DCI,
8120                             bool AllOnes = false) {
8121   SelectionDAG &DAG = DCI.DAG;
8122   EVT VT = N->getValueType(0);
8123   SDValue NonConstantVal;
8124   SDValue CCOp;
8125   bool SwapSelectOps;
8126   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8127                                   NonConstantVal, DAG))
8128     return SDValue();
8129
8130   // Slct is now know to be the desired identity constant when CC is true.
8131   SDValue TrueVal = OtherOp;
8132   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8133                                  OtherOp, NonConstantVal);
8134   // Unless SwapSelectOps says CC should be false.
8135   if (SwapSelectOps)
8136     std::swap(TrueVal, FalseVal);
8137
8138   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8139                      CCOp, TrueVal, FalseVal);
8140 }
8141
8142 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8143 static
8144 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8145                                        TargetLowering::DAGCombinerInfo &DCI) {
8146   SDValue N0 = N->getOperand(0);
8147   SDValue N1 = N->getOperand(1);
8148   if (N0.getNode()->hasOneUse()) {
8149     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8150     if (Result.getNode())
8151       return Result;
8152   }
8153   if (N1.getNode()->hasOneUse()) {
8154     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8155     if (Result.getNode())
8156       return Result;
8157   }
8158   return SDValue();
8159 }
8160
8161 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8162 // (only after legalization).
8163 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8164                                  TargetLowering::DAGCombinerInfo &DCI,
8165                                  const ARMSubtarget *Subtarget) {
8166
8167   // Only perform optimization if after legalize, and if NEON is available. We
8168   // also expected both operands to be BUILD_VECTORs.
8169   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8170       || N0.getOpcode() != ISD::BUILD_VECTOR
8171       || N1.getOpcode() != ISD::BUILD_VECTOR)
8172     return SDValue();
8173
8174   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8175   EVT VT = N->getValueType(0);
8176   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8177     return SDValue();
8178
8179   // Check that the vector operands are of the right form.
8180   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8181   // operands, where N is the size of the formed vector.
8182   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8183   // index such that we have a pair wise add pattern.
8184
8185   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8186   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8187     return SDValue();
8188   SDValue Vec = N0->getOperand(0)->getOperand(0);
8189   SDNode *V = Vec.getNode();
8190   unsigned nextIndex = 0;
8191
8192   // For each operands to the ADD which are BUILD_VECTORs,
8193   // check to see if each of their operands are an EXTRACT_VECTOR with
8194   // the same vector and appropriate index.
8195   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8196     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8197         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8198
8199       SDValue ExtVec0 = N0->getOperand(i);
8200       SDValue ExtVec1 = N1->getOperand(i);
8201
8202       // First operand is the vector, verify its the same.
8203       if (V != ExtVec0->getOperand(0).getNode() ||
8204           V != ExtVec1->getOperand(0).getNode())
8205         return SDValue();
8206
8207       // Second is the constant, verify its correct.
8208       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8209       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8210
8211       // For the constant, we want to see all the even or all the odd.
8212       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8213           || C1->getZExtValue() != nextIndex+1)
8214         return SDValue();
8215
8216       // Increment index.
8217       nextIndex+=2;
8218     } else
8219       return SDValue();
8220   }
8221
8222   // Create VPADDL node.
8223   SelectionDAG &DAG = DCI.DAG;
8224   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8225
8226   SDLoc dl(N);
8227
8228   // Build operand list.
8229   SmallVector<SDValue, 8> Ops;
8230   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8231                                 TLI.getPointerTy(DAG.getDataLayout())));
8232
8233   // Input is the vector.
8234   Ops.push_back(Vec);
8235
8236   // Get widened type and narrowed type.
8237   MVT widenType;
8238   unsigned numElem = VT.getVectorNumElements();
8239   
8240   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8241   switch (inputLaneType.getSimpleVT().SimpleTy) {
8242     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8243     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8244     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8245     default:
8246       llvm_unreachable("Invalid vector element type for padd optimization.");
8247   }
8248
8249   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8250   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8251   return DAG.getNode(ExtOp, dl, VT, tmp);
8252 }
8253
8254 static SDValue findMUL_LOHI(SDValue V) {
8255   if (V->getOpcode() == ISD::UMUL_LOHI ||
8256       V->getOpcode() == ISD::SMUL_LOHI)
8257     return V;
8258   return SDValue();
8259 }
8260
8261 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8262                                      TargetLowering::DAGCombinerInfo &DCI,
8263                                      const ARMSubtarget *Subtarget) {
8264
8265   if (Subtarget->isThumb1Only()) return SDValue();
8266
8267   // Only perform the checks after legalize when the pattern is available.
8268   if (DCI.isBeforeLegalize()) return SDValue();
8269
8270   // Look for multiply add opportunities.
8271   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8272   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8273   // a glue link from the first add to the second add.
8274   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8275   // a S/UMLAL instruction.
8276   //                  UMUL_LOHI
8277   //                 / :lo    \ :hi
8278   //                /          \          [no multiline comment]
8279   //    loAdd ->  ADDE         |
8280   //                 \ :glue  /
8281   //                  \      /
8282   //                    ADDC   <- hiAdd
8283   //
8284   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8285   SDValue AddcOp0 = AddcNode->getOperand(0);
8286   SDValue AddcOp1 = AddcNode->getOperand(1);
8287
8288   // Check if the two operands are from the same mul_lohi node.
8289   if (AddcOp0.getNode() == AddcOp1.getNode())
8290     return SDValue();
8291
8292   assert(AddcNode->getNumValues() == 2 &&
8293          AddcNode->getValueType(0) == MVT::i32 &&
8294          "Expect ADDC with two result values. First: i32");
8295
8296   // Check that we have a glued ADDC node.
8297   if (AddcNode->getValueType(1) != MVT::Glue)
8298     return SDValue();
8299
8300   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8301   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8302       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8303       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8304       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8305     return SDValue();
8306
8307   // Look for the glued ADDE.
8308   SDNode* AddeNode = AddcNode->getGluedUser();
8309   if (!AddeNode)
8310     return SDValue();
8311
8312   // Make sure it is really an ADDE.
8313   if (AddeNode->getOpcode() != ISD::ADDE)
8314     return SDValue();
8315
8316   assert(AddeNode->getNumOperands() == 3 &&
8317          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8318          "ADDE node has the wrong inputs");
8319
8320   // Check for the triangle shape.
8321   SDValue AddeOp0 = AddeNode->getOperand(0);
8322   SDValue AddeOp1 = AddeNode->getOperand(1);
8323
8324   // Make sure that the ADDE operands are not coming from the same node.
8325   if (AddeOp0.getNode() == AddeOp1.getNode())
8326     return SDValue();
8327
8328   // Find the MUL_LOHI node walking up ADDE's operands.
8329   bool IsLeftOperandMUL = false;
8330   SDValue MULOp = findMUL_LOHI(AddeOp0);
8331   if (MULOp == SDValue())
8332    MULOp = findMUL_LOHI(AddeOp1);
8333   else
8334     IsLeftOperandMUL = true;
8335   if (MULOp == SDValue())
8336     return SDValue();
8337
8338   // Figure out the right opcode.
8339   unsigned Opc = MULOp->getOpcode();
8340   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8341
8342   // Figure out the high and low input values to the MLAL node.
8343   SDValue* HiAdd = nullptr;
8344   SDValue* LoMul = nullptr;
8345   SDValue* LowAdd = nullptr;
8346
8347   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8348   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8349     return SDValue();
8350
8351   if (IsLeftOperandMUL)
8352     HiAdd = &AddeOp1;
8353   else
8354     HiAdd = &AddeOp0;
8355
8356
8357   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8358   // whose low result is fed to the ADDC we are checking.
8359
8360   if (AddcOp0 == MULOp.getValue(0)) {
8361     LoMul = &AddcOp0;
8362     LowAdd = &AddcOp1;
8363   }
8364   if (AddcOp1 == MULOp.getValue(0)) {
8365     LoMul = &AddcOp1;
8366     LowAdd = &AddcOp0;
8367   }
8368
8369   if (!LoMul)
8370     return SDValue();
8371
8372   // Create the merged node.
8373   SelectionDAG &DAG = DCI.DAG;
8374
8375   // Build operand list.
8376   SmallVector<SDValue, 8> Ops;
8377   Ops.push_back(LoMul->getOperand(0));
8378   Ops.push_back(LoMul->getOperand(1));
8379   Ops.push_back(*LowAdd);
8380   Ops.push_back(*HiAdd);
8381
8382   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8383                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8384
8385   // Replace the ADDs' nodes uses by the MLA node's values.
8386   SDValue HiMLALResult(MLALNode.getNode(), 1);
8387   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8388
8389   SDValue LoMLALResult(MLALNode.getNode(), 0);
8390   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8391
8392   // Return original node to notify the driver to stop replacing.
8393   SDValue resNode(AddcNode, 0);
8394   return resNode;
8395 }
8396
8397 /// PerformADDCCombine - Target-specific dag combine transform from
8398 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8399 static SDValue PerformADDCCombine(SDNode *N,
8400                                  TargetLowering::DAGCombinerInfo &DCI,
8401                                  const ARMSubtarget *Subtarget) {
8402
8403   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8404
8405 }
8406
8407 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8408 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8409 /// called with the default operands, and if that fails, with commuted
8410 /// operands.
8411 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8412                                           TargetLowering::DAGCombinerInfo &DCI,
8413                                           const ARMSubtarget *Subtarget){
8414
8415   // Attempt to create vpaddl for this add.
8416   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8417   if (Result.getNode())
8418     return Result;
8419
8420   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8421   if (N0.getNode()->hasOneUse()) {
8422     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8423     if (Result.getNode()) return Result;
8424   }
8425   return SDValue();
8426 }
8427
8428 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8429 ///
8430 static SDValue PerformADDCombine(SDNode *N,
8431                                  TargetLowering::DAGCombinerInfo &DCI,
8432                                  const ARMSubtarget *Subtarget) {
8433   SDValue N0 = N->getOperand(0);
8434   SDValue N1 = N->getOperand(1);
8435
8436   // First try with the default operand order.
8437   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8438   if (Result.getNode())
8439     return Result;
8440
8441   // If that didn't work, try again with the operands commuted.
8442   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8443 }
8444
8445 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8446 ///
8447 static SDValue PerformSUBCombine(SDNode *N,
8448                                  TargetLowering::DAGCombinerInfo &DCI) {
8449   SDValue N0 = N->getOperand(0);
8450   SDValue N1 = N->getOperand(1);
8451
8452   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8453   if (N1.getNode()->hasOneUse()) {
8454     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8455     if (Result.getNode()) return Result;
8456   }
8457
8458   return SDValue();
8459 }
8460
8461 /// PerformVMULCombine
8462 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8463 /// special multiplier accumulator forwarding.
8464 ///   vmul d3, d0, d2
8465 ///   vmla d3, d1, d2
8466 /// is faster than
8467 ///   vadd d3, d0, d1
8468 ///   vmul d3, d3, d2
8469 //  However, for (A + B) * (A + B),
8470 //    vadd d2, d0, d1
8471 //    vmul d3, d0, d2
8472 //    vmla d3, d1, d2
8473 //  is slower than
8474 //    vadd d2, d0, d1
8475 //    vmul d3, d2, d2
8476 static SDValue PerformVMULCombine(SDNode *N,
8477                                   TargetLowering::DAGCombinerInfo &DCI,
8478                                   const ARMSubtarget *Subtarget) {
8479   if (!Subtarget->hasVMLxForwarding())
8480     return SDValue();
8481
8482   SelectionDAG &DAG = DCI.DAG;
8483   SDValue N0 = N->getOperand(0);
8484   SDValue N1 = N->getOperand(1);
8485   unsigned Opcode = N0.getOpcode();
8486   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8487       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8488     Opcode = N1.getOpcode();
8489     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8490         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8491       return SDValue();
8492     std::swap(N0, N1);
8493   }
8494
8495   if (N0 == N1)
8496     return SDValue();
8497
8498   EVT VT = N->getValueType(0);
8499   SDLoc DL(N);
8500   SDValue N00 = N0->getOperand(0);
8501   SDValue N01 = N0->getOperand(1);
8502   return DAG.getNode(Opcode, DL, VT,
8503                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8504                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8505 }
8506
8507 static SDValue PerformMULCombine(SDNode *N,
8508                                  TargetLowering::DAGCombinerInfo &DCI,
8509                                  const ARMSubtarget *Subtarget) {
8510   SelectionDAG &DAG = DCI.DAG;
8511
8512   if (Subtarget->isThumb1Only())
8513     return SDValue();
8514
8515   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8516     return SDValue();
8517
8518   EVT VT = N->getValueType(0);
8519   if (VT.is64BitVector() || VT.is128BitVector())
8520     return PerformVMULCombine(N, DCI, Subtarget);
8521   if (VT != MVT::i32)
8522     return SDValue();
8523
8524   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8525   if (!C)
8526     return SDValue();
8527
8528   int64_t MulAmt = C->getSExtValue();
8529   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8530
8531   ShiftAmt = ShiftAmt & (32 - 1);
8532   SDValue V = N->getOperand(0);
8533   SDLoc DL(N);
8534
8535   SDValue Res;
8536   MulAmt >>= ShiftAmt;
8537
8538   if (MulAmt >= 0) {
8539     if (isPowerOf2_32(MulAmt - 1)) {
8540       // (mul x, 2^N + 1) => (add (shl x, N), x)
8541       Res = DAG.getNode(ISD::ADD, DL, VT,
8542                         V,
8543                         DAG.getNode(ISD::SHL, DL, VT,
8544                                     V,
8545                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8546                                                     MVT::i32)));
8547     } else if (isPowerOf2_32(MulAmt + 1)) {
8548       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8549       Res = DAG.getNode(ISD::SUB, DL, VT,
8550                         DAG.getNode(ISD::SHL, DL, VT,
8551                                     V,
8552                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8553                                                     MVT::i32)),
8554                         V);
8555     } else
8556       return SDValue();
8557   } else {
8558     uint64_t MulAmtAbs = -MulAmt;
8559     if (isPowerOf2_32(MulAmtAbs + 1)) {
8560       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8561       Res = DAG.getNode(ISD::SUB, DL, VT,
8562                         V,
8563                         DAG.getNode(ISD::SHL, DL, VT,
8564                                     V,
8565                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8566                                                     MVT::i32)));
8567     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8568       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8569       Res = DAG.getNode(ISD::ADD, DL, VT,
8570                         V,
8571                         DAG.getNode(ISD::SHL, DL, VT,
8572                                     V,
8573                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8574                                                     MVT::i32)));
8575       Res = DAG.getNode(ISD::SUB, DL, VT,
8576                         DAG.getConstant(0, DL, MVT::i32), Res);
8577
8578     } else
8579       return SDValue();
8580   }
8581
8582   if (ShiftAmt != 0)
8583     Res = DAG.getNode(ISD::SHL, DL, VT,
8584                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8585
8586   // Do not add new nodes to DAG combiner worklist.
8587   DCI.CombineTo(N, Res, false);
8588   return SDValue();
8589 }
8590
8591 static SDValue PerformANDCombine(SDNode *N,
8592                                  TargetLowering::DAGCombinerInfo &DCI,
8593                                  const ARMSubtarget *Subtarget) {
8594
8595   // Attempt to use immediate-form VBIC
8596   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8597   SDLoc dl(N);
8598   EVT VT = N->getValueType(0);
8599   SelectionDAG &DAG = DCI.DAG;
8600
8601   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8602     return SDValue();
8603
8604   APInt SplatBits, SplatUndef;
8605   unsigned SplatBitSize;
8606   bool HasAnyUndefs;
8607   if (BVN &&
8608       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8609     if (SplatBitSize <= 64) {
8610       EVT VbicVT;
8611       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8612                                       SplatUndef.getZExtValue(), SplatBitSize,
8613                                       DAG, dl, VbicVT, VT.is128BitVector(),
8614                                       OtherModImm);
8615       if (Val.getNode()) {
8616         SDValue Input =
8617           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8618         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8619         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8620       }
8621     }
8622   }
8623
8624   if (!Subtarget->isThumb1Only()) {
8625     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8626     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8627     if (Result.getNode())
8628       return Result;
8629   }
8630
8631   return SDValue();
8632 }
8633
8634 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8635 static SDValue PerformORCombine(SDNode *N,
8636                                 TargetLowering::DAGCombinerInfo &DCI,
8637                                 const ARMSubtarget *Subtarget) {
8638   // Attempt to use immediate-form VORR
8639   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8640   SDLoc dl(N);
8641   EVT VT = N->getValueType(0);
8642   SelectionDAG &DAG = DCI.DAG;
8643
8644   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8645     return SDValue();
8646
8647   APInt SplatBits, SplatUndef;
8648   unsigned SplatBitSize;
8649   bool HasAnyUndefs;
8650   if (BVN && Subtarget->hasNEON() &&
8651       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8652     if (SplatBitSize <= 64) {
8653       EVT VorrVT;
8654       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8655                                       SplatUndef.getZExtValue(), SplatBitSize,
8656                                       DAG, dl, VorrVT, VT.is128BitVector(),
8657                                       OtherModImm);
8658       if (Val.getNode()) {
8659         SDValue Input =
8660           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8661         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8662         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8663       }
8664     }
8665   }
8666
8667   if (!Subtarget->isThumb1Only()) {
8668     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8669     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8670     if (Result.getNode())
8671       return Result;
8672   }
8673
8674   // The code below optimizes (or (and X, Y), Z).
8675   // The AND operand needs to have a single user to make these optimizations
8676   // profitable.
8677   SDValue N0 = N->getOperand(0);
8678   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8679     return SDValue();
8680   SDValue N1 = N->getOperand(1);
8681
8682   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8683   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8684       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8685     APInt SplatUndef;
8686     unsigned SplatBitSize;
8687     bool HasAnyUndefs;
8688
8689     APInt SplatBits0, SplatBits1;
8690     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8691     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8692     // Ensure that the second operand of both ands are constants
8693     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8694                                       HasAnyUndefs) && !HasAnyUndefs) {
8695         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8696                                           HasAnyUndefs) && !HasAnyUndefs) {
8697             // Ensure that the bit width of the constants are the same and that
8698             // the splat arguments are logical inverses as per the pattern we
8699             // are trying to simplify.
8700             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8701                 SplatBits0 == ~SplatBits1) {
8702                 // Canonicalize the vector type to make instruction selection
8703                 // simpler.
8704                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8705                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8706                                              N0->getOperand(1),
8707                                              N0->getOperand(0),
8708                                              N1->getOperand(0));
8709                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8710             }
8711         }
8712     }
8713   }
8714
8715   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8716   // reasonable.
8717
8718   // BFI is only available on V6T2+
8719   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8720     return SDValue();
8721
8722   SDLoc DL(N);
8723   // 1) or (and A, mask), val => ARMbfi A, val, mask
8724   //      iff (val & mask) == val
8725   //
8726   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8727   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8728   //          && mask == ~mask2
8729   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8730   //          && ~mask == mask2
8731   //  (i.e., copy a bitfield value into another bitfield of the same width)
8732
8733   if (VT != MVT::i32)
8734     return SDValue();
8735
8736   SDValue N00 = N0.getOperand(0);
8737
8738   // The value and the mask need to be constants so we can verify this is
8739   // actually a bitfield set. If the mask is 0xffff, we can do better
8740   // via a movt instruction, so don't use BFI in that case.
8741   SDValue MaskOp = N0.getOperand(1);
8742   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8743   if (!MaskC)
8744     return SDValue();
8745   unsigned Mask = MaskC->getZExtValue();
8746   if (Mask == 0xffff)
8747     return SDValue();
8748   SDValue Res;
8749   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8750   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8751   if (N1C) {
8752     unsigned Val = N1C->getZExtValue();
8753     if ((Val & ~Mask) != Val)
8754       return SDValue();
8755
8756     if (ARM::isBitFieldInvertedMask(Mask)) {
8757       Val >>= countTrailingZeros(~Mask);
8758
8759       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8760                         DAG.getConstant(Val, DL, MVT::i32),
8761                         DAG.getConstant(Mask, DL, MVT::i32));
8762
8763       // Do not add new nodes to DAG combiner worklist.
8764       DCI.CombineTo(N, Res, false);
8765       return SDValue();
8766     }
8767   } else if (N1.getOpcode() == ISD::AND) {
8768     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8769     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8770     if (!N11C)
8771       return SDValue();
8772     unsigned Mask2 = N11C->getZExtValue();
8773
8774     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8775     // as is to match.
8776     if (ARM::isBitFieldInvertedMask(Mask) &&
8777         (Mask == ~Mask2)) {
8778       // The pack halfword instruction works better for masks that fit it,
8779       // so use that when it's available.
8780       if (Subtarget->hasT2ExtractPack() &&
8781           (Mask == 0xffff || Mask == 0xffff0000))
8782         return SDValue();
8783       // 2a
8784       unsigned amt = countTrailingZeros(Mask2);
8785       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8786                         DAG.getConstant(amt, DL, MVT::i32));
8787       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8788                         DAG.getConstant(Mask, DL, MVT::i32));
8789       // Do not add new nodes to DAG combiner worklist.
8790       DCI.CombineTo(N, Res, false);
8791       return SDValue();
8792     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8793                (~Mask == Mask2)) {
8794       // The pack halfword instruction works better for masks that fit it,
8795       // so use that when it's available.
8796       if (Subtarget->hasT2ExtractPack() &&
8797           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8798         return SDValue();
8799       // 2b
8800       unsigned lsb = countTrailingZeros(Mask);
8801       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8802                         DAG.getConstant(lsb, DL, MVT::i32));
8803       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8804                         DAG.getConstant(Mask2, DL, MVT::i32));
8805       // Do not add new nodes to DAG combiner worklist.
8806       DCI.CombineTo(N, Res, false);
8807       return SDValue();
8808     }
8809   }
8810
8811   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8812       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8813       ARM::isBitFieldInvertedMask(~Mask)) {
8814     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8815     // where lsb(mask) == #shamt and masked bits of B are known zero.
8816     SDValue ShAmt = N00.getOperand(1);
8817     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8818     unsigned LSB = countTrailingZeros(Mask);
8819     if (ShAmtC != LSB)
8820       return SDValue();
8821
8822     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8823                       DAG.getConstant(~Mask, DL, MVT::i32));
8824
8825     // Do not add new nodes to DAG combiner worklist.
8826     DCI.CombineTo(N, Res, false);
8827   }
8828
8829   return SDValue();
8830 }
8831
8832 static SDValue PerformXORCombine(SDNode *N,
8833                                  TargetLowering::DAGCombinerInfo &DCI,
8834                                  const ARMSubtarget *Subtarget) {
8835   EVT VT = N->getValueType(0);
8836   SelectionDAG &DAG = DCI.DAG;
8837
8838   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8839     return SDValue();
8840
8841   if (!Subtarget->isThumb1Only()) {
8842     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8843     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8844     if (Result.getNode())
8845       return Result;
8846   }
8847
8848   return SDValue();
8849 }
8850
8851 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8852 /// the bits being cleared by the AND are not demanded by the BFI.
8853 static SDValue PerformBFICombine(SDNode *N,
8854                                  TargetLowering::DAGCombinerInfo &DCI) {
8855   SDValue N1 = N->getOperand(1);
8856   if (N1.getOpcode() == ISD::AND) {
8857     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8858     if (!N11C)
8859       return SDValue();
8860     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8861     unsigned LSB = countTrailingZeros(~InvMask);
8862     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8863     assert(Width <
8864                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8865            "undefined behavior");
8866     unsigned Mask = (1u << Width) - 1;
8867     unsigned Mask2 = N11C->getZExtValue();
8868     if ((Mask & (~Mask2)) == 0)
8869       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8870                              N->getOperand(0), N1.getOperand(0),
8871                              N->getOperand(2));
8872   }
8873   return SDValue();
8874 }
8875
8876 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8877 /// ARMISD::VMOVRRD.
8878 static SDValue PerformVMOVRRDCombine(SDNode *N,
8879                                      TargetLowering::DAGCombinerInfo &DCI,
8880                                      const ARMSubtarget *Subtarget) {
8881   // vmovrrd(vmovdrr x, y) -> x,y
8882   SDValue InDouble = N->getOperand(0);
8883   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8884     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8885
8886   // vmovrrd(load f64) -> (load i32), (load i32)
8887   SDNode *InNode = InDouble.getNode();
8888   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8889       InNode->getValueType(0) == MVT::f64 &&
8890       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8891       !cast<LoadSDNode>(InNode)->isVolatile()) {
8892     // TODO: Should this be done for non-FrameIndex operands?
8893     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8894
8895     SelectionDAG &DAG = DCI.DAG;
8896     SDLoc DL(LD);
8897     SDValue BasePtr = LD->getBasePtr();
8898     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8899                                  LD->getPointerInfo(), LD->isVolatile(),
8900                                  LD->isNonTemporal(), LD->isInvariant(),
8901                                  LD->getAlignment());
8902
8903     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8904                                     DAG.getConstant(4, DL, MVT::i32));
8905     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8906                                  LD->getPointerInfo(), LD->isVolatile(),
8907                                  LD->isNonTemporal(), LD->isInvariant(),
8908                                  std::min(4U, LD->getAlignment() / 2));
8909
8910     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8911     if (DCI.DAG.getDataLayout().isBigEndian())
8912       std::swap (NewLD1, NewLD2);
8913     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8914     return Result;
8915   }
8916
8917   return SDValue();
8918 }
8919
8920 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8921 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8922 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8923   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8924   SDValue Op0 = N->getOperand(0);
8925   SDValue Op1 = N->getOperand(1);
8926   if (Op0.getOpcode() == ISD::BITCAST)
8927     Op0 = Op0.getOperand(0);
8928   if (Op1.getOpcode() == ISD::BITCAST)
8929     Op1 = Op1.getOperand(0);
8930   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8931       Op0.getNode() == Op1.getNode() &&
8932       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8933     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8934                        N->getValueType(0), Op0.getOperand(0));
8935   return SDValue();
8936 }
8937
8938 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8939 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8940 /// i64 vector to have f64 elements, since the value can then be loaded
8941 /// directly into a VFP register.
8942 static bool hasNormalLoadOperand(SDNode *N) {
8943   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8944   for (unsigned i = 0; i < NumElts; ++i) {
8945     SDNode *Elt = N->getOperand(i).getNode();
8946     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8947       return true;
8948   }
8949   return false;
8950 }
8951
8952 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8953 /// ISD::BUILD_VECTOR.
8954 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8955                                           TargetLowering::DAGCombinerInfo &DCI,
8956                                           const ARMSubtarget *Subtarget) {
8957   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8958   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8959   // into a pair of GPRs, which is fine when the value is used as a scalar,
8960   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8961   SelectionDAG &DAG = DCI.DAG;
8962   if (N->getNumOperands() == 2) {
8963     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8964     if (RV.getNode())
8965       return RV;
8966   }
8967
8968   // Load i64 elements as f64 values so that type legalization does not split
8969   // them up into i32 values.
8970   EVT VT = N->getValueType(0);
8971   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8972     return SDValue();
8973   SDLoc dl(N);
8974   SmallVector<SDValue, 8> Ops;
8975   unsigned NumElts = VT.getVectorNumElements();
8976   for (unsigned i = 0; i < NumElts; ++i) {
8977     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8978     Ops.push_back(V);
8979     // Make the DAGCombiner fold the bitcast.
8980     DCI.AddToWorklist(V.getNode());
8981   }
8982   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8983   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8984   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8985 }
8986
8987 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8988 static SDValue
8989 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8990   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8991   // At that time, we may have inserted bitcasts from integer to float.
8992   // If these bitcasts have survived DAGCombine, change the lowering of this
8993   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8994   // force to use floating point types.
8995
8996   // Make sure we can change the type of the vector.
8997   // This is possible iff:
8998   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8999   //    1.1. Vector is used only once.
9000   //    1.2. Use is a bit convert to an integer type.
9001   // 2. The size of its operands are 32-bits (64-bits are not legal).
9002   EVT VT = N->getValueType(0);
9003   EVT EltVT = VT.getVectorElementType();
9004
9005   // Check 1.1. and 2.
9006   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9007     return SDValue();
9008
9009   // By construction, the input type must be float.
9010   assert(EltVT == MVT::f32 && "Unexpected type!");
9011
9012   // Check 1.2.
9013   SDNode *Use = *N->use_begin();
9014   if (Use->getOpcode() != ISD::BITCAST ||
9015       Use->getValueType(0).isFloatingPoint())
9016     return SDValue();
9017
9018   // Check profitability.
9019   // Model is, if more than half of the relevant operands are bitcast from
9020   // i32, turn the build_vector into a sequence of insert_vector_elt.
9021   // Relevant operands are everything that is not statically
9022   // (i.e., at compile time) bitcasted.
9023   unsigned NumOfBitCastedElts = 0;
9024   unsigned NumElts = VT.getVectorNumElements();
9025   unsigned NumOfRelevantElts = NumElts;
9026   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9027     SDValue Elt = N->getOperand(Idx);
9028     if (Elt->getOpcode() == ISD::BITCAST) {
9029       // Assume only bit cast to i32 will go away.
9030       if (Elt->getOperand(0).getValueType() == MVT::i32)
9031         ++NumOfBitCastedElts;
9032     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9033       // Constants are statically casted, thus do not count them as
9034       // relevant operands.
9035       --NumOfRelevantElts;
9036   }
9037
9038   // Check if more than half of the elements require a non-free bitcast.
9039   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9040     return SDValue();
9041
9042   SelectionDAG &DAG = DCI.DAG;
9043   // Create the new vector type.
9044   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9045   // Check if the type is legal.
9046   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9047   if (!TLI.isTypeLegal(VecVT))
9048     return SDValue();
9049
9050   // Combine:
9051   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9052   // => BITCAST INSERT_VECTOR_ELT
9053   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9054   //                      (BITCAST EN), N.
9055   SDValue Vec = DAG.getUNDEF(VecVT);
9056   SDLoc dl(N);
9057   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9058     SDValue V = N->getOperand(Idx);
9059     if (V.getOpcode() == ISD::UNDEF)
9060       continue;
9061     if (V.getOpcode() == ISD::BITCAST &&
9062         V->getOperand(0).getValueType() == MVT::i32)
9063       // Fold obvious case.
9064       V = V.getOperand(0);
9065     else {
9066       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9067       // Make the DAGCombiner fold the bitcasts.
9068       DCI.AddToWorklist(V.getNode());
9069     }
9070     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9071     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9072   }
9073   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9074   // Make the DAGCombiner fold the bitcasts.
9075   DCI.AddToWorklist(Vec.getNode());
9076   return Vec;
9077 }
9078
9079 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9080 /// ISD::INSERT_VECTOR_ELT.
9081 static SDValue PerformInsertEltCombine(SDNode *N,
9082                                        TargetLowering::DAGCombinerInfo &DCI) {
9083   // Bitcast an i64 load inserted into a vector to f64.
9084   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9085   EVT VT = N->getValueType(0);
9086   SDNode *Elt = N->getOperand(1).getNode();
9087   if (VT.getVectorElementType() != MVT::i64 ||
9088       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9089     return SDValue();
9090
9091   SelectionDAG &DAG = DCI.DAG;
9092   SDLoc dl(N);
9093   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9094                                  VT.getVectorNumElements());
9095   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9096   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9097   // Make the DAGCombiner fold the bitcasts.
9098   DCI.AddToWorklist(Vec.getNode());
9099   DCI.AddToWorklist(V.getNode());
9100   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9101                                Vec, V, N->getOperand(2));
9102   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9103 }
9104
9105 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9106 /// ISD::VECTOR_SHUFFLE.
9107 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9108   // The LLVM shufflevector instruction does not require the shuffle mask
9109   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9110   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9111   // operands do not match the mask length, they are extended by concatenating
9112   // them with undef vectors.  That is probably the right thing for other
9113   // targets, but for NEON it is better to concatenate two double-register
9114   // size vector operands into a single quad-register size vector.  Do that
9115   // transformation here:
9116   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9117   //   shuffle(concat(v1, v2), undef)
9118   SDValue Op0 = N->getOperand(0);
9119   SDValue Op1 = N->getOperand(1);
9120   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9121       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9122       Op0.getNumOperands() != 2 ||
9123       Op1.getNumOperands() != 2)
9124     return SDValue();
9125   SDValue Concat0Op1 = Op0.getOperand(1);
9126   SDValue Concat1Op1 = Op1.getOperand(1);
9127   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9128       Concat1Op1.getOpcode() != ISD::UNDEF)
9129     return SDValue();
9130   // Skip the transformation if any of the types are illegal.
9131   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9132   EVT VT = N->getValueType(0);
9133   if (!TLI.isTypeLegal(VT) ||
9134       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9135       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9136     return SDValue();
9137
9138   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9139                                   Op0.getOperand(0), Op1.getOperand(0));
9140   // Translate the shuffle mask.
9141   SmallVector<int, 16> NewMask;
9142   unsigned NumElts = VT.getVectorNumElements();
9143   unsigned HalfElts = NumElts/2;
9144   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9145   for (unsigned n = 0; n < NumElts; ++n) {
9146     int MaskElt = SVN->getMaskElt(n);
9147     int NewElt = -1;
9148     if (MaskElt < (int)HalfElts)
9149       NewElt = MaskElt;
9150     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9151       NewElt = HalfElts + MaskElt - NumElts;
9152     NewMask.push_back(NewElt);
9153   }
9154   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9155                               DAG.getUNDEF(VT), NewMask.data());
9156 }
9157
9158 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9159 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9160 /// base address updates.
9161 /// For generic load/stores, the memory type is assumed to be a vector.
9162 /// The caller is assumed to have checked legality.
9163 static SDValue CombineBaseUpdate(SDNode *N,
9164                                  TargetLowering::DAGCombinerInfo &DCI) {
9165   SelectionDAG &DAG = DCI.DAG;
9166   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9167                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9168   const bool isStore = N->getOpcode() == ISD::STORE;
9169   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9170   SDValue Addr = N->getOperand(AddrOpIdx);
9171   MemSDNode *MemN = cast<MemSDNode>(N);
9172   SDLoc dl(N);
9173
9174   // Search for a use of the address operand that is an increment.
9175   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9176          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9177     SDNode *User = *UI;
9178     if (User->getOpcode() != ISD::ADD ||
9179         UI.getUse().getResNo() != Addr.getResNo())
9180       continue;
9181
9182     // Check that the add is independent of the load/store.  Otherwise, folding
9183     // it would create a cycle.
9184     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9185       continue;
9186
9187     // Find the new opcode for the updating load/store.
9188     bool isLoadOp = true;
9189     bool isLaneOp = false;
9190     unsigned NewOpc = 0;
9191     unsigned NumVecs = 0;
9192     if (isIntrinsic) {
9193       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9194       switch (IntNo) {
9195       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9196       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9197         NumVecs = 1; break;
9198       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9199         NumVecs = 2; break;
9200       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9201         NumVecs = 3; break;
9202       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9203         NumVecs = 4; break;
9204       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9205         NumVecs = 2; isLaneOp = true; break;
9206       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9207         NumVecs = 3; isLaneOp = true; break;
9208       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9209         NumVecs = 4; isLaneOp = true; break;
9210       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9211         NumVecs = 1; isLoadOp = false; break;
9212       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9213         NumVecs = 2; isLoadOp = false; break;
9214       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9215         NumVecs = 3; isLoadOp = false; break;
9216       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9217         NumVecs = 4; isLoadOp = false; break;
9218       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9219         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9220       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9221         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9222       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9223         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9224       }
9225     } else {
9226       isLaneOp = true;
9227       switch (N->getOpcode()) {
9228       default: llvm_unreachable("unexpected opcode for Neon base update");
9229       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9230       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9231       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9232       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9233         NumVecs = 1; isLaneOp = false; break;
9234       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9235         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9236       }
9237     }
9238
9239     // Find the size of memory referenced by the load/store.
9240     EVT VecTy;
9241     if (isLoadOp) {
9242       VecTy = N->getValueType(0);
9243     } else if (isIntrinsic) {
9244       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9245     } else {
9246       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9247       VecTy = N->getOperand(1).getValueType();
9248     }
9249
9250     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9251     if (isLaneOp)
9252       NumBytes /= VecTy.getVectorNumElements();
9253
9254     // If the increment is a constant, it must match the memory ref size.
9255     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9256     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9257       uint64_t IncVal = CInc->getZExtValue();
9258       if (IncVal != NumBytes)
9259         continue;
9260     } else if (NumBytes >= 3 * 16) {
9261       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9262       // separate instructions that make it harder to use a non-constant update.
9263       continue;
9264     }
9265
9266     // OK, we found an ADD we can fold into the base update.
9267     // Now, create a _UPD node, taking care of not breaking alignment.
9268
9269     EVT AlignedVecTy = VecTy;
9270     unsigned Alignment = MemN->getAlignment();
9271
9272     // If this is a less-than-standard-aligned load/store, change the type to
9273     // match the standard alignment.
9274     // The alignment is overlooked when selecting _UPD variants; and it's
9275     // easier to introduce bitcasts here than fix that.
9276     // There are 3 ways to get to this base-update combine:
9277     // - intrinsics: they are assumed to be properly aligned (to the standard
9278     //   alignment of the memory type), so we don't need to do anything.
9279     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9280     //   intrinsics, so, likewise, there's nothing to do.
9281     // - generic load/store instructions: the alignment is specified as an
9282     //   explicit operand, rather than implicitly as the standard alignment
9283     //   of the memory type (like the intrisics).  We need to change the
9284     //   memory type to match the explicit alignment.  That way, we don't
9285     //   generate non-standard-aligned ARMISD::VLDx nodes.
9286     if (isa<LSBaseSDNode>(N)) {
9287       if (Alignment == 0)
9288         Alignment = 1;
9289       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9290         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9291         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9292         assert(!isLaneOp && "Unexpected generic load/store lane.");
9293         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9294         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9295       }
9296       // Don't set an explicit alignment on regular load/stores that we want
9297       // to transform to VLD/VST 1_UPD nodes.
9298       // This matches the behavior of regular load/stores, which only get an
9299       // explicit alignment if the MMO alignment is larger than the standard
9300       // alignment of the memory type.
9301       // Intrinsics, however, always get an explicit alignment, set to the
9302       // alignment of the MMO.
9303       Alignment = 1;
9304     }
9305
9306     // Create the new updating load/store node.
9307     // First, create an SDVTList for the new updating node's results.
9308     EVT Tys[6];
9309     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9310     unsigned n;
9311     for (n = 0; n < NumResultVecs; ++n)
9312       Tys[n] = AlignedVecTy;
9313     Tys[n++] = MVT::i32;
9314     Tys[n] = MVT::Other;
9315     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9316
9317     // Then, gather the new node's operands.
9318     SmallVector<SDValue, 8> Ops;
9319     Ops.push_back(N->getOperand(0)); // incoming chain
9320     Ops.push_back(N->getOperand(AddrOpIdx));
9321     Ops.push_back(Inc);
9322
9323     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9324       // Try to match the intrinsic's signature
9325       Ops.push_back(StN->getValue());
9326     } else {
9327       // Loads (and of course intrinsics) match the intrinsics' signature,
9328       // so just add all but the alignment operand.
9329       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9330         Ops.push_back(N->getOperand(i));
9331     }
9332
9333     // For all node types, the alignment operand is always the last one.
9334     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9335
9336     // If this is a non-standard-aligned STORE, the penultimate operand is the
9337     // stored value.  Bitcast it to the aligned type.
9338     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9339       SDValue &StVal = Ops[Ops.size()-2];
9340       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9341     }
9342
9343     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9344                                            Ops, AlignedVecTy,
9345                                            MemN->getMemOperand());
9346
9347     // Update the uses.
9348     SmallVector<SDValue, 5> NewResults;
9349     for (unsigned i = 0; i < NumResultVecs; ++i)
9350       NewResults.push_back(SDValue(UpdN.getNode(), i));
9351
9352     // If this is an non-standard-aligned LOAD, the first result is the loaded
9353     // value.  Bitcast it to the expected result type.
9354     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9355       SDValue &LdVal = NewResults[0];
9356       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9357     }
9358
9359     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9360     DCI.CombineTo(N, NewResults);
9361     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9362
9363     break;
9364   }
9365   return SDValue();
9366 }
9367
9368 static SDValue PerformVLDCombine(SDNode *N,
9369                                  TargetLowering::DAGCombinerInfo &DCI) {
9370   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9371     return SDValue();
9372
9373   return CombineBaseUpdate(N, DCI);
9374 }
9375
9376 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9377 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9378 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9379 /// return true.
9380 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9381   SelectionDAG &DAG = DCI.DAG;
9382   EVT VT = N->getValueType(0);
9383   // vldN-dup instructions only support 64-bit vectors for N > 1.
9384   if (!VT.is64BitVector())
9385     return false;
9386
9387   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9388   SDNode *VLD = N->getOperand(0).getNode();
9389   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9390     return false;
9391   unsigned NumVecs = 0;
9392   unsigned NewOpc = 0;
9393   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9394   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9395     NumVecs = 2;
9396     NewOpc = ARMISD::VLD2DUP;
9397   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9398     NumVecs = 3;
9399     NewOpc = ARMISD::VLD3DUP;
9400   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9401     NumVecs = 4;
9402     NewOpc = ARMISD::VLD4DUP;
9403   } else {
9404     return false;
9405   }
9406
9407   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9408   // numbers match the load.
9409   unsigned VLDLaneNo =
9410     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9411   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9412        UI != UE; ++UI) {
9413     // Ignore uses of the chain result.
9414     if (UI.getUse().getResNo() == NumVecs)
9415       continue;
9416     SDNode *User = *UI;
9417     if (User->getOpcode() != ARMISD::VDUPLANE ||
9418         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9419       return false;
9420   }
9421
9422   // Create the vldN-dup node.
9423   EVT Tys[5];
9424   unsigned n;
9425   for (n = 0; n < NumVecs; ++n)
9426     Tys[n] = VT;
9427   Tys[n] = MVT::Other;
9428   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9429   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9430   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9431   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9432                                            Ops, VLDMemInt->getMemoryVT(),
9433                                            VLDMemInt->getMemOperand());
9434
9435   // Update the uses.
9436   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9437        UI != UE; ++UI) {
9438     unsigned ResNo = UI.getUse().getResNo();
9439     // Ignore uses of the chain result.
9440     if (ResNo == NumVecs)
9441       continue;
9442     SDNode *User = *UI;
9443     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9444   }
9445
9446   // Now the vldN-lane intrinsic is dead except for its chain result.
9447   // Update uses of the chain.
9448   std::vector<SDValue> VLDDupResults;
9449   for (unsigned n = 0; n < NumVecs; ++n)
9450     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9451   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9452   DCI.CombineTo(VLD, VLDDupResults);
9453
9454   return true;
9455 }
9456
9457 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9458 /// ARMISD::VDUPLANE.
9459 static SDValue PerformVDUPLANECombine(SDNode *N,
9460                                       TargetLowering::DAGCombinerInfo &DCI) {
9461   SDValue Op = N->getOperand(0);
9462
9463   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9464   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9465   if (CombineVLDDUP(N, DCI))
9466     return SDValue(N, 0);
9467
9468   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9469   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9470   while (Op.getOpcode() == ISD::BITCAST)
9471     Op = Op.getOperand(0);
9472   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9473     return SDValue();
9474
9475   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9476   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9477   // The canonical VMOV for a zero vector uses a 32-bit element size.
9478   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9479   unsigned EltBits;
9480   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9481     EltSize = 8;
9482   EVT VT = N->getValueType(0);
9483   if (EltSize > VT.getVectorElementType().getSizeInBits())
9484     return SDValue();
9485
9486   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9487 }
9488
9489 static SDValue PerformLOADCombine(SDNode *N,
9490                                   TargetLowering::DAGCombinerInfo &DCI) {
9491   EVT VT = N->getValueType(0);
9492
9493   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9494   if (ISD::isNormalLoad(N) && VT.isVector() &&
9495       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9496     return CombineBaseUpdate(N, DCI);
9497
9498   return SDValue();
9499 }
9500
9501 /// PerformSTORECombine - Target-specific dag combine xforms for
9502 /// ISD::STORE.
9503 static SDValue PerformSTORECombine(SDNode *N,
9504                                    TargetLowering::DAGCombinerInfo &DCI) {
9505   StoreSDNode *St = cast<StoreSDNode>(N);
9506   if (St->isVolatile())
9507     return SDValue();
9508
9509   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9510   // pack all of the elements in one place.  Next, store to memory in fewer
9511   // chunks.
9512   SDValue StVal = St->getValue();
9513   EVT VT = StVal.getValueType();
9514   if (St->isTruncatingStore() && VT.isVector()) {
9515     SelectionDAG &DAG = DCI.DAG;
9516     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9517     EVT StVT = St->getMemoryVT();
9518     unsigned NumElems = VT.getVectorNumElements();
9519     assert(StVT != VT && "Cannot truncate to the same type");
9520     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9521     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9522
9523     // From, To sizes and ElemCount must be pow of two
9524     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9525
9526     // We are going to use the original vector elt for storing.
9527     // Accumulated smaller vector elements must be a multiple of the store size.
9528     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9529
9530     unsigned SizeRatio  = FromEltSz / ToEltSz;
9531     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9532
9533     // Create a type on which we perform the shuffle.
9534     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9535                                      NumElems*SizeRatio);
9536     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9537
9538     SDLoc DL(St);
9539     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9540     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9541     for (unsigned i = 0; i < NumElems; ++i)
9542       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9543                           ? (i + 1) * SizeRatio - 1
9544                           : i * SizeRatio;
9545
9546     // Can't shuffle using an illegal type.
9547     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9548
9549     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9550                                 DAG.getUNDEF(WideVec.getValueType()),
9551                                 ShuffleVec.data());
9552     // At this point all of the data is stored at the bottom of the
9553     // register. We now need to save it to mem.
9554
9555     // Find the largest store unit
9556     MVT StoreType = MVT::i8;
9557     for (MVT Tp : MVT::integer_valuetypes()) {
9558       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9559         StoreType = Tp;
9560     }
9561     // Didn't find a legal store type.
9562     if (!TLI.isTypeLegal(StoreType))
9563       return SDValue();
9564
9565     // Bitcast the original vector into a vector of store-size units
9566     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9567             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9568     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9569     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9570     SmallVector<SDValue, 8> Chains;
9571     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9572                                         TLI.getPointerTy(DAG.getDataLayout()));
9573     SDValue BasePtr = St->getBasePtr();
9574
9575     // Perform one or more big stores into memory.
9576     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9577     for (unsigned I = 0; I < E; I++) {
9578       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9579                                    StoreType, ShuffWide,
9580                                    DAG.getIntPtrConstant(I, DL));
9581       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9582                                 St->getPointerInfo(), St->isVolatile(),
9583                                 St->isNonTemporal(), St->getAlignment());
9584       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9585                             Increment);
9586       Chains.push_back(Ch);
9587     }
9588     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9589   }
9590
9591   if (!ISD::isNormalStore(St))
9592     return SDValue();
9593
9594   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9595   // ARM stores of arguments in the same cache line.
9596   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9597       StVal.getNode()->hasOneUse()) {
9598     SelectionDAG  &DAG = DCI.DAG;
9599     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9600     SDLoc DL(St);
9601     SDValue BasePtr = St->getBasePtr();
9602     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9603                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9604                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9605                                   St->isNonTemporal(), St->getAlignment());
9606
9607     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9608                                     DAG.getConstant(4, DL, MVT::i32));
9609     return DAG.getStore(NewST1.getValue(0), DL,
9610                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9611                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9612                         St->isNonTemporal(),
9613                         std::min(4U, St->getAlignment() / 2));
9614   }
9615
9616   if (StVal.getValueType() == MVT::i64 &&
9617       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9618
9619     // Bitcast an i64 store extracted from a vector to f64.
9620     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9621     SelectionDAG &DAG = DCI.DAG;
9622     SDLoc dl(StVal);
9623     SDValue IntVec = StVal.getOperand(0);
9624     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9625                                    IntVec.getValueType().getVectorNumElements());
9626     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9627     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9628                                  Vec, StVal.getOperand(1));
9629     dl = SDLoc(N);
9630     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9631     // Make the DAGCombiner fold the bitcasts.
9632     DCI.AddToWorklist(Vec.getNode());
9633     DCI.AddToWorklist(ExtElt.getNode());
9634     DCI.AddToWorklist(V.getNode());
9635     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9636                         St->getPointerInfo(), St->isVolatile(),
9637                         St->isNonTemporal(), St->getAlignment(),
9638                         St->getAAInfo());
9639   }
9640
9641   // If this is a legal vector store, try to combine it into a VST1_UPD.
9642   if (ISD::isNormalStore(N) && VT.isVector() &&
9643       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9644     return CombineBaseUpdate(N, DCI);
9645
9646   return SDValue();
9647 }
9648
9649 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9650 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9651 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9652 {
9653   integerPart cN;
9654   integerPart c0 = 0;
9655   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9656        I != E; I++) {
9657     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9658     if (!C)
9659       return false;
9660
9661     bool isExact;
9662     APFloat APF = C->getValueAPF();
9663     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9664         != APFloat::opOK || !isExact)
9665       return false;
9666
9667     c0 = (I == 0) ? cN : c0;
9668     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9669       return false;
9670   }
9671   C = c0;
9672   return true;
9673 }
9674
9675 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9676 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9677 /// when the VMUL has a constant operand that is a power of 2.
9678 ///
9679 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9680 ///  vmul.f32        d16, d17, d16
9681 ///  vcvt.s32.f32    d16, d16
9682 /// becomes:
9683 ///  vcvt.s32.f32    d16, d16, #3
9684 static SDValue PerformVCVTCombine(SDNode *N,
9685                                   TargetLowering::DAGCombinerInfo &DCI,
9686                                   const ARMSubtarget *Subtarget) {
9687   SelectionDAG &DAG = DCI.DAG;
9688   SDValue Op = N->getOperand(0);
9689
9690   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9691       Op.getOpcode() != ISD::FMUL)
9692     return SDValue();
9693
9694   uint64_t C;
9695   SDValue N0 = Op->getOperand(0);
9696   SDValue ConstVec = Op->getOperand(1);
9697   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9698
9699   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9700       !isConstVecPow2(ConstVec, isSigned, C))
9701     return SDValue();
9702
9703   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9704   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9705   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9706   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9707       NumLanes > 4) {
9708     // These instructions only exist converting from f32 to i32. We can handle
9709     // smaller integers by generating an extra truncate, but larger ones would
9710     // be lossy. We also can't handle more then 4 lanes, since these intructions
9711     // only support v2i32/v4i32 types.
9712     return SDValue();
9713   }
9714
9715   SDLoc dl(N);
9716   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9717     Intrinsic::arm_neon_vcvtfp2fxu;
9718   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9719                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9720                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9721                                  N0,
9722                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9723
9724   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9725     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9726
9727   return FixConv;
9728 }
9729
9730 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9731 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9732 /// when the VDIV has a constant operand that is a power of 2.
9733 ///
9734 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9735 ///  vcvt.f32.s32    d16, d16
9736 ///  vdiv.f32        d16, d17, d16
9737 /// becomes:
9738 ///  vcvt.f32.s32    d16, d16, #3
9739 static SDValue PerformVDIVCombine(SDNode *N,
9740                                   TargetLowering::DAGCombinerInfo &DCI,
9741                                   const ARMSubtarget *Subtarget) {
9742   SelectionDAG &DAG = DCI.DAG;
9743   SDValue Op = N->getOperand(0);
9744   unsigned OpOpcode = Op.getNode()->getOpcode();
9745
9746   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9747       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9748     return SDValue();
9749
9750   uint64_t C;
9751   SDValue ConstVec = N->getOperand(1);
9752   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9753
9754   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9755       !isConstVecPow2(ConstVec, isSigned, C))
9756     return SDValue();
9757
9758   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9759   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9760   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9761     // These instructions only exist converting from i32 to f32. We can handle
9762     // smaller integers by generating an extra extend, but larger ones would
9763     // be lossy.
9764     return SDValue();
9765   }
9766
9767   SDLoc dl(N);
9768   SDValue ConvInput = Op.getOperand(0);
9769   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9770   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9771     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9772                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9773                             ConvInput);
9774
9775   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9776     Intrinsic::arm_neon_vcvtfxu2fp;
9777   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9778                      Op.getValueType(),
9779                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9780                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9781 }
9782
9783 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9784 /// operand of a vector shift operation, where all the elements of the
9785 /// build_vector must have the same constant integer value.
9786 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9787   // Ignore bit_converts.
9788   while (Op.getOpcode() == ISD::BITCAST)
9789     Op = Op.getOperand(0);
9790   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9791   APInt SplatBits, SplatUndef;
9792   unsigned SplatBitSize;
9793   bool HasAnyUndefs;
9794   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9795                                       HasAnyUndefs, ElementBits) ||
9796       SplatBitSize > ElementBits)
9797     return false;
9798   Cnt = SplatBits.getSExtValue();
9799   return true;
9800 }
9801
9802 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9803 /// operand of a vector shift left operation.  That value must be in the range:
9804 ///   0 <= Value < ElementBits for a left shift; or
9805 ///   0 <= Value <= ElementBits for a long left shift.
9806 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9807   assert(VT.isVector() && "vector shift count is not a vector type");
9808   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9809   if (! getVShiftImm(Op, ElementBits, Cnt))
9810     return false;
9811   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9812 }
9813
9814 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9815 /// operand of a vector shift right operation.  For a shift opcode, the value
9816 /// is positive, but for an intrinsic the value count must be negative. The
9817 /// absolute value must be in the range:
9818 ///   1 <= |Value| <= ElementBits for a right shift; or
9819 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9820 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9821                          int64_t &Cnt) {
9822   assert(VT.isVector() && "vector shift count is not a vector type");
9823   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9824   if (! getVShiftImm(Op, ElementBits, Cnt))
9825     return false;
9826   if (!isIntrinsic)
9827     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9828   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9829     Cnt = -Cnt;
9830     return true;
9831   }
9832   return false;
9833 }
9834
9835 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9836 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9837   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9838   switch (IntNo) {
9839   default:
9840     // Don't do anything for most intrinsics.
9841     break;
9842
9843   case Intrinsic::arm_neon_vabds:
9844     if (!N->getValueType(0).isInteger())
9845       return SDValue();
9846     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9847                        N->getOperand(1), N->getOperand(2));
9848   case Intrinsic::arm_neon_vabdu:
9849     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9850                        N->getOperand(1), N->getOperand(2));
9851
9852   // Vector shifts: check for immediate versions and lower them.
9853   // Note: This is done during DAG combining instead of DAG legalizing because
9854   // the build_vectors for 64-bit vector element shift counts are generally
9855   // not legal, and it is hard to see their values after they get legalized to
9856   // loads from a constant pool.
9857   case Intrinsic::arm_neon_vshifts:
9858   case Intrinsic::arm_neon_vshiftu:
9859   case Intrinsic::arm_neon_vrshifts:
9860   case Intrinsic::arm_neon_vrshiftu:
9861   case Intrinsic::arm_neon_vrshiftn:
9862   case Intrinsic::arm_neon_vqshifts:
9863   case Intrinsic::arm_neon_vqshiftu:
9864   case Intrinsic::arm_neon_vqshiftsu:
9865   case Intrinsic::arm_neon_vqshiftns:
9866   case Intrinsic::arm_neon_vqshiftnu:
9867   case Intrinsic::arm_neon_vqshiftnsu:
9868   case Intrinsic::arm_neon_vqrshiftns:
9869   case Intrinsic::arm_neon_vqrshiftnu:
9870   case Intrinsic::arm_neon_vqrshiftnsu: {
9871     EVT VT = N->getOperand(1).getValueType();
9872     int64_t Cnt;
9873     unsigned VShiftOpc = 0;
9874
9875     switch (IntNo) {
9876     case Intrinsic::arm_neon_vshifts:
9877     case Intrinsic::arm_neon_vshiftu:
9878       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9879         VShiftOpc = ARMISD::VSHL;
9880         break;
9881       }
9882       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9883         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9884                      ARMISD::VSHRs : ARMISD::VSHRu);
9885         break;
9886       }
9887       return SDValue();
9888
9889     case Intrinsic::arm_neon_vrshifts:
9890     case Intrinsic::arm_neon_vrshiftu:
9891       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9892         break;
9893       return SDValue();
9894
9895     case Intrinsic::arm_neon_vqshifts:
9896     case Intrinsic::arm_neon_vqshiftu:
9897       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9898         break;
9899       return SDValue();
9900
9901     case Intrinsic::arm_neon_vqshiftsu:
9902       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9903         break;
9904       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9905
9906     case Intrinsic::arm_neon_vrshiftn:
9907     case Intrinsic::arm_neon_vqshiftns:
9908     case Intrinsic::arm_neon_vqshiftnu:
9909     case Intrinsic::arm_neon_vqshiftnsu:
9910     case Intrinsic::arm_neon_vqrshiftns:
9911     case Intrinsic::arm_neon_vqrshiftnu:
9912     case Intrinsic::arm_neon_vqrshiftnsu:
9913       // Narrowing shifts require an immediate right shift.
9914       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9915         break;
9916       llvm_unreachable("invalid shift count for narrowing vector shift "
9917                        "intrinsic");
9918
9919     default:
9920       llvm_unreachable("unhandled vector shift");
9921     }
9922
9923     switch (IntNo) {
9924     case Intrinsic::arm_neon_vshifts:
9925     case Intrinsic::arm_neon_vshiftu:
9926       // Opcode already set above.
9927       break;
9928     case Intrinsic::arm_neon_vrshifts:
9929       VShiftOpc = ARMISD::VRSHRs; break;
9930     case Intrinsic::arm_neon_vrshiftu:
9931       VShiftOpc = ARMISD::VRSHRu; break;
9932     case Intrinsic::arm_neon_vrshiftn:
9933       VShiftOpc = ARMISD::VRSHRN; break;
9934     case Intrinsic::arm_neon_vqshifts:
9935       VShiftOpc = ARMISD::VQSHLs; break;
9936     case Intrinsic::arm_neon_vqshiftu:
9937       VShiftOpc = ARMISD::VQSHLu; break;
9938     case Intrinsic::arm_neon_vqshiftsu:
9939       VShiftOpc = ARMISD::VQSHLsu; break;
9940     case Intrinsic::arm_neon_vqshiftns:
9941       VShiftOpc = ARMISD::VQSHRNs; break;
9942     case Intrinsic::arm_neon_vqshiftnu:
9943       VShiftOpc = ARMISD::VQSHRNu; break;
9944     case Intrinsic::arm_neon_vqshiftnsu:
9945       VShiftOpc = ARMISD::VQSHRNsu; break;
9946     case Intrinsic::arm_neon_vqrshiftns:
9947       VShiftOpc = ARMISD::VQRSHRNs; break;
9948     case Intrinsic::arm_neon_vqrshiftnu:
9949       VShiftOpc = ARMISD::VQRSHRNu; break;
9950     case Intrinsic::arm_neon_vqrshiftnsu:
9951       VShiftOpc = ARMISD::VQRSHRNsu; break;
9952     }
9953
9954     SDLoc dl(N);
9955     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9956                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9957   }
9958
9959   case Intrinsic::arm_neon_vshiftins: {
9960     EVT VT = N->getOperand(1).getValueType();
9961     int64_t Cnt;
9962     unsigned VShiftOpc = 0;
9963
9964     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9965       VShiftOpc = ARMISD::VSLI;
9966     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9967       VShiftOpc = ARMISD::VSRI;
9968     else {
9969       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9970     }
9971
9972     SDLoc dl(N);
9973     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9974                        N->getOperand(1), N->getOperand(2),
9975                        DAG.getConstant(Cnt, dl, MVT::i32));
9976   }
9977
9978   case Intrinsic::arm_neon_vqrshifts:
9979   case Intrinsic::arm_neon_vqrshiftu:
9980     // No immediate versions of these to check for.
9981     break;
9982   }
9983
9984   return SDValue();
9985 }
9986
9987 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9988 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9989 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9990 /// vector element shift counts are generally not legal, and it is hard to see
9991 /// their values after they get legalized to loads from a constant pool.
9992 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9993                                    const ARMSubtarget *ST) {
9994   EVT VT = N->getValueType(0);
9995   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9996     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9997     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9998     SDValue N1 = N->getOperand(1);
9999     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10000       SDValue N0 = N->getOperand(0);
10001       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10002           DAG.MaskedValueIsZero(N0.getOperand(0),
10003                                 APInt::getHighBitsSet(32, 16)))
10004         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10005     }
10006   }
10007
10008   // Nothing to be done for scalar shifts.
10009   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10010   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10011     return SDValue();
10012
10013   assert(ST->hasNEON() && "unexpected vector shift");
10014   int64_t Cnt;
10015
10016   switch (N->getOpcode()) {
10017   default: llvm_unreachable("unexpected shift opcode");
10018
10019   case ISD::SHL:
10020     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10021       SDLoc dl(N);
10022       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10023                          DAG.getConstant(Cnt, dl, MVT::i32));
10024     }
10025     break;
10026
10027   case ISD::SRA:
10028   case ISD::SRL:
10029     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10030       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10031                             ARMISD::VSHRs : ARMISD::VSHRu);
10032       SDLoc dl(N);
10033       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10034                          DAG.getConstant(Cnt, dl, MVT::i32));
10035     }
10036   }
10037   return SDValue();
10038 }
10039
10040 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10041 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10042 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10043                                     const ARMSubtarget *ST) {
10044   SDValue N0 = N->getOperand(0);
10045
10046   // Check for sign- and zero-extensions of vector extract operations of 8-
10047   // and 16-bit vector elements.  NEON supports these directly.  They are
10048   // handled during DAG combining because type legalization will promote them
10049   // to 32-bit types and it is messy to recognize the operations after that.
10050   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10051     SDValue Vec = N0.getOperand(0);
10052     SDValue Lane = N0.getOperand(1);
10053     EVT VT = N->getValueType(0);
10054     EVT EltVT = N0.getValueType();
10055     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10056
10057     if (VT == MVT::i32 &&
10058         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10059         TLI.isTypeLegal(Vec.getValueType()) &&
10060         isa<ConstantSDNode>(Lane)) {
10061
10062       unsigned Opc = 0;
10063       switch (N->getOpcode()) {
10064       default: llvm_unreachable("unexpected opcode");
10065       case ISD::SIGN_EXTEND:
10066         Opc = ARMISD::VGETLANEs;
10067         break;
10068       case ISD::ZERO_EXTEND:
10069       case ISD::ANY_EXTEND:
10070         Opc = ARMISD::VGETLANEu;
10071         break;
10072       }
10073       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10074     }
10075   }
10076
10077   return SDValue();
10078 }
10079
10080 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10081 SDValue
10082 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10083   SDValue Cmp = N->getOperand(4);
10084   if (Cmp.getOpcode() != ARMISD::CMPZ)
10085     // Only looking at EQ and NE cases.
10086     return SDValue();
10087
10088   EVT VT = N->getValueType(0);
10089   SDLoc dl(N);
10090   SDValue LHS = Cmp.getOperand(0);
10091   SDValue RHS = Cmp.getOperand(1);
10092   SDValue FalseVal = N->getOperand(0);
10093   SDValue TrueVal = N->getOperand(1);
10094   SDValue ARMcc = N->getOperand(2);
10095   ARMCC::CondCodes CC =
10096     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10097
10098   // Simplify
10099   //   mov     r1, r0
10100   //   cmp     r1, x
10101   //   mov     r0, y
10102   //   moveq   r0, x
10103   // to
10104   //   cmp     r0, x
10105   //   movne   r0, y
10106   //
10107   //   mov     r1, r0
10108   //   cmp     r1, x
10109   //   mov     r0, x
10110   //   movne   r0, y
10111   // to
10112   //   cmp     r0, x
10113   //   movne   r0, y
10114   /// FIXME: Turn this into a target neutral optimization?
10115   SDValue Res;
10116   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10117     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10118                       N->getOperand(3), Cmp);
10119   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10120     SDValue ARMcc;
10121     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10122     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10123                       N->getOperand(3), NewCmp);
10124   }
10125
10126   if (Res.getNode()) {
10127     APInt KnownZero, KnownOne;
10128     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10129     // Capture demanded bits information that would be otherwise lost.
10130     if (KnownZero == 0xfffffffe)
10131       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10132                         DAG.getValueType(MVT::i1));
10133     else if (KnownZero == 0xffffff00)
10134       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10135                         DAG.getValueType(MVT::i8));
10136     else if (KnownZero == 0xffff0000)
10137       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10138                         DAG.getValueType(MVT::i16));
10139   }
10140
10141   return Res;
10142 }
10143
10144 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10145                                              DAGCombinerInfo &DCI) const {
10146   switch (N->getOpcode()) {
10147   default: break;
10148   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10149   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10150   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10151   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10152   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10153   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10154   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10155   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10156   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10157   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10158   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10159   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10160   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10161   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10162   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10163   case ISD::FP_TO_SINT:
10164   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10165   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10166   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10167   case ISD::SHL:
10168   case ISD::SRA:
10169   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10170   case ISD::SIGN_EXTEND:
10171   case ISD::ZERO_EXTEND:
10172   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10173   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10174   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10175   case ARMISD::VLD2DUP:
10176   case ARMISD::VLD3DUP:
10177   case ARMISD::VLD4DUP:
10178     return PerformVLDCombine(N, DCI);
10179   case ARMISD::BUILD_VECTOR:
10180     return PerformARMBUILD_VECTORCombine(N, DCI);
10181   case ISD::INTRINSIC_VOID:
10182   case ISD::INTRINSIC_W_CHAIN:
10183     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10184     case Intrinsic::arm_neon_vld1:
10185     case Intrinsic::arm_neon_vld2:
10186     case Intrinsic::arm_neon_vld3:
10187     case Intrinsic::arm_neon_vld4:
10188     case Intrinsic::arm_neon_vld2lane:
10189     case Intrinsic::arm_neon_vld3lane:
10190     case Intrinsic::arm_neon_vld4lane:
10191     case Intrinsic::arm_neon_vst1:
10192     case Intrinsic::arm_neon_vst2:
10193     case Intrinsic::arm_neon_vst3:
10194     case Intrinsic::arm_neon_vst4:
10195     case Intrinsic::arm_neon_vst2lane:
10196     case Intrinsic::arm_neon_vst3lane:
10197     case Intrinsic::arm_neon_vst4lane:
10198       return PerformVLDCombine(N, DCI);
10199     default: break;
10200     }
10201     break;
10202   }
10203   return SDValue();
10204 }
10205
10206 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10207                                                           EVT VT) const {
10208   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10209 }
10210
10211 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10212                                                        unsigned,
10213                                                        unsigned,
10214                                                        bool *Fast) const {
10215   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10216   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10217
10218   switch (VT.getSimpleVT().SimpleTy) {
10219   default:
10220     return false;
10221   case MVT::i8:
10222   case MVT::i16:
10223   case MVT::i32: {
10224     // Unaligned access can use (for example) LRDB, LRDH, LDR
10225     if (AllowsUnaligned) {
10226       if (Fast)
10227         *Fast = Subtarget->hasV7Ops();
10228       return true;
10229     }
10230     return false;
10231   }
10232   case MVT::f64:
10233   case MVT::v2f64: {
10234     // For any little-endian targets with neon, we can support unaligned ld/st
10235     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10236     // A big-endian target may also explicitly support unaligned accesses
10237     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10238       if (Fast)
10239         *Fast = true;
10240       return true;
10241     }
10242     return false;
10243   }
10244   }
10245 }
10246
10247 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10248                        unsigned AlignCheck) {
10249   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10250           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10251 }
10252
10253 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10254                                            unsigned DstAlign, unsigned SrcAlign,
10255                                            bool IsMemset, bool ZeroMemset,
10256                                            bool MemcpyStrSrc,
10257                                            MachineFunction &MF) const {
10258   const Function *F = MF.getFunction();
10259
10260   // See if we can use NEON instructions for this...
10261   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10262       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10263     bool Fast;
10264     if (Size >= 16 &&
10265         (memOpAlign(SrcAlign, DstAlign, 16) ||
10266          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10267       return MVT::v2f64;
10268     } else if (Size >= 8 &&
10269                (memOpAlign(SrcAlign, DstAlign, 8) ||
10270                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10271                  Fast))) {
10272       return MVT::f64;
10273     }
10274   }
10275
10276   // Lowering to i32/i16 if the size permits.
10277   if (Size >= 4)
10278     return MVT::i32;
10279   else if (Size >= 2)
10280     return MVT::i16;
10281
10282   // Let the target-independent logic figure it out.
10283   return MVT::Other;
10284 }
10285
10286 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10287   if (Val.getOpcode() != ISD::LOAD)
10288     return false;
10289
10290   EVT VT1 = Val.getValueType();
10291   if (!VT1.isSimple() || !VT1.isInteger() ||
10292       !VT2.isSimple() || !VT2.isInteger())
10293     return false;
10294
10295   switch (VT1.getSimpleVT().SimpleTy) {
10296   default: break;
10297   case MVT::i1:
10298   case MVT::i8:
10299   case MVT::i16:
10300     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10301     return true;
10302   }
10303
10304   return false;
10305 }
10306
10307 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10308   EVT VT = ExtVal.getValueType();
10309
10310   if (!isTypeLegal(VT))
10311     return false;
10312
10313   // Don't create a loadext if we can fold the extension into a wide/long
10314   // instruction.
10315   // If there's more than one user instruction, the loadext is desirable no
10316   // matter what.  There can be two uses by the same instruction.
10317   if (ExtVal->use_empty() ||
10318       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10319     return true;
10320
10321   SDNode *U = *ExtVal->use_begin();
10322   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10323        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10324     return false;
10325
10326   return true;
10327 }
10328
10329 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10330   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10331     return false;
10332
10333   if (!isTypeLegal(EVT::getEVT(Ty1)))
10334     return false;
10335
10336   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10337
10338   // Assuming the caller doesn't have a zeroext or signext return parameter,
10339   // truncation all the way down to i1 is valid.
10340   return true;
10341 }
10342
10343
10344 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10345   if (V < 0)
10346     return false;
10347
10348   unsigned Scale = 1;
10349   switch (VT.getSimpleVT().SimpleTy) {
10350   default: return false;
10351   case MVT::i1:
10352   case MVT::i8:
10353     // Scale == 1;
10354     break;
10355   case MVT::i16:
10356     // Scale == 2;
10357     Scale = 2;
10358     break;
10359   case MVT::i32:
10360     // Scale == 4;
10361     Scale = 4;
10362     break;
10363   }
10364
10365   if ((V & (Scale - 1)) != 0)
10366     return false;
10367   V /= Scale;
10368   return V == (V & ((1LL << 5) - 1));
10369 }
10370
10371 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10372                                       const ARMSubtarget *Subtarget) {
10373   bool isNeg = false;
10374   if (V < 0) {
10375     isNeg = true;
10376     V = - V;
10377   }
10378
10379   switch (VT.getSimpleVT().SimpleTy) {
10380   default: return false;
10381   case MVT::i1:
10382   case MVT::i8:
10383   case MVT::i16:
10384   case MVT::i32:
10385     // + imm12 or - imm8
10386     if (isNeg)
10387       return V == (V & ((1LL << 8) - 1));
10388     return V == (V & ((1LL << 12) - 1));
10389   case MVT::f32:
10390   case MVT::f64:
10391     // Same as ARM mode. FIXME: NEON?
10392     if (!Subtarget->hasVFP2())
10393       return false;
10394     if ((V & 3) != 0)
10395       return false;
10396     V >>= 2;
10397     return V == (V & ((1LL << 8) - 1));
10398   }
10399 }
10400
10401 /// isLegalAddressImmediate - Return true if the integer value can be used
10402 /// as the offset of the target addressing mode for load / store of the
10403 /// given type.
10404 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10405                                     const ARMSubtarget *Subtarget) {
10406   if (V == 0)
10407     return true;
10408
10409   if (!VT.isSimple())
10410     return false;
10411
10412   if (Subtarget->isThumb1Only())
10413     return isLegalT1AddressImmediate(V, VT);
10414   else if (Subtarget->isThumb2())
10415     return isLegalT2AddressImmediate(V, VT, Subtarget);
10416
10417   // ARM mode.
10418   if (V < 0)
10419     V = - V;
10420   switch (VT.getSimpleVT().SimpleTy) {
10421   default: return false;
10422   case MVT::i1:
10423   case MVT::i8:
10424   case MVT::i32:
10425     // +- imm12
10426     return V == (V & ((1LL << 12) - 1));
10427   case MVT::i16:
10428     // +- imm8
10429     return V == (V & ((1LL << 8) - 1));
10430   case MVT::f32:
10431   case MVT::f64:
10432     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10433       return false;
10434     if ((V & 3) != 0)
10435       return false;
10436     V >>= 2;
10437     return V == (V & ((1LL << 8) - 1));
10438   }
10439 }
10440
10441 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10442                                                       EVT VT) const {
10443   int Scale = AM.Scale;
10444   if (Scale < 0)
10445     return false;
10446
10447   switch (VT.getSimpleVT().SimpleTy) {
10448   default: return false;
10449   case MVT::i1:
10450   case MVT::i8:
10451   case MVT::i16:
10452   case MVT::i32:
10453     if (Scale == 1)
10454       return true;
10455     // r + r << imm
10456     Scale = Scale & ~1;
10457     return Scale == 2 || Scale == 4 || Scale == 8;
10458   case MVT::i64:
10459     // r + r
10460     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10461       return true;
10462     return false;
10463   case MVT::isVoid:
10464     // Note, we allow "void" uses (basically, uses that aren't loads or
10465     // stores), because arm allows folding a scale into many arithmetic
10466     // operations.  This should be made more precise and revisited later.
10467
10468     // Allow r << imm, but the imm has to be a multiple of two.
10469     if (Scale & 1) return false;
10470     return isPowerOf2_32(Scale);
10471   }
10472 }
10473
10474 /// isLegalAddressingMode - Return true if the addressing mode represented
10475 /// by AM is legal for this target, for a load/store of the specified type.
10476 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10477                                               const AddrMode &AM, Type *Ty,
10478                                               unsigned AS) const {
10479   EVT VT = getValueType(DL, Ty, true);
10480   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10481     return false;
10482
10483   // Can never fold addr of global into load/store.
10484   if (AM.BaseGV)
10485     return false;
10486
10487   switch (AM.Scale) {
10488   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10489     break;
10490   case 1:
10491     if (Subtarget->isThumb1Only())
10492       return false;
10493     // FALL THROUGH.
10494   default:
10495     // ARM doesn't support any R+R*scale+imm addr modes.
10496     if (AM.BaseOffs)
10497       return false;
10498
10499     if (!VT.isSimple())
10500       return false;
10501
10502     if (Subtarget->isThumb2())
10503       return isLegalT2ScaledAddressingMode(AM, VT);
10504
10505     int Scale = AM.Scale;
10506     switch (VT.getSimpleVT().SimpleTy) {
10507     default: return false;
10508     case MVT::i1:
10509     case MVT::i8:
10510     case MVT::i32:
10511       if (Scale < 0) Scale = -Scale;
10512       if (Scale == 1)
10513         return true;
10514       // r + r << imm
10515       return isPowerOf2_32(Scale & ~1);
10516     case MVT::i16:
10517     case MVT::i64:
10518       // r + r
10519       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10520         return true;
10521       return false;
10522
10523     case MVT::isVoid:
10524       // Note, we allow "void" uses (basically, uses that aren't loads or
10525       // stores), because arm allows folding a scale into many arithmetic
10526       // operations.  This should be made more precise and revisited later.
10527
10528       // Allow r << imm, but the imm has to be a multiple of two.
10529       if (Scale & 1) return false;
10530       return isPowerOf2_32(Scale);
10531     }
10532   }
10533   return true;
10534 }
10535
10536 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10537 /// icmp immediate, that is the target has icmp instructions which can compare
10538 /// a register against the immediate without having to materialize the
10539 /// immediate into a register.
10540 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10541   // Thumb2 and ARM modes can use cmn for negative immediates.
10542   if (!Subtarget->isThumb())
10543     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10544   if (Subtarget->isThumb2())
10545     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10546   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10547   return Imm >= 0 && Imm <= 255;
10548 }
10549
10550 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10551 /// *or sub* immediate, that is the target has add or sub instructions which can
10552 /// add a register with the immediate without having to materialize the
10553 /// immediate into a register.
10554 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10555   // Same encoding for add/sub, just flip the sign.
10556   int64_t AbsImm = std::abs(Imm);
10557   if (!Subtarget->isThumb())
10558     return ARM_AM::getSOImmVal(AbsImm) != -1;
10559   if (Subtarget->isThumb2())
10560     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10561   // Thumb1 only has 8-bit unsigned immediate.
10562   return AbsImm >= 0 && AbsImm <= 255;
10563 }
10564
10565 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10566                                       bool isSEXTLoad, SDValue &Base,
10567                                       SDValue &Offset, bool &isInc,
10568                                       SelectionDAG &DAG) {
10569   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10570     return false;
10571
10572   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10573     // AddressingMode 3
10574     Base = Ptr->getOperand(0);
10575     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10576       int RHSC = (int)RHS->getZExtValue();
10577       if (RHSC < 0 && RHSC > -256) {
10578         assert(Ptr->getOpcode() == ISD::ADD);
10579         isInc = false;
10580         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10581         return true;
10582       }
10583     }
10584     isInc = (Ptr->getOpcode() == ISD::ADD);
10585     Offset = Ptr->getOperand(1);
10586     return true;
10587   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10588     // AddressingMode 2
10589     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10590       int RHSC = (int)RHS->getZExtValue();
10591       if (RHSC < 0 && RHSC > -0x1000) {
10592         assert(Ptr->getOpcode() == ISD::ADD);
10593         isInc = false;
10594         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10595         Base = Ptr->getOperand(0);
10596         return true;
10597       }
10598     }
10599
10600     if (Ptr->getOpcode() == ISD::ADD) {
10601       isInc = true;
10602       ARM_AM::ShiftOpc ShOpcVal=
10603         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10604       if (ShOpcVal != ARM_AM::no_shift) {
10605         Base = Ptr->getOperand(1);
10606         Offset = Ptr->getOperand(0);
10607       } else {
10608         Base = Ptr->getOperand(0);
10609         Offset = Ptr->getOperand(1);
10610       }
10611       return true;
10612     }
10613
10614     isInc = (Ptr->getOpcode() == ISD::ADD);
10615     Base = Ptr->getOperand(0);
10616     Offset = Ptr->getOperand(1);
10617     return true;
10618   }
10619
10620   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10621   return false;
10622 }
10623
10624 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10625                                      bool isSEXTLoad, SDValue &Base,
10626                                      SDValue &Offset, bool &isInc,
10627                                      SelectionDAG &DAG) {
10628   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10629     return false;
10630
10631   Base = Ptr->getOperand(0);
10632   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10633     int RHSC = (int)RHS->getZExtValue();
10634     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10635       assert(Ptr->getOpcode() == ISD::ADD);
10636       isInc = false;
10637       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10638       return true;
10639     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10640       isInc = Ptr->getOpcode() == ISD::ADD;
10641       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10642       return true;
10643     }
10644   }
10645
10646   return false;
10647 }
10648
10649 /// getPreIndexedAddressParts - returns true by value, base pointer and
10650 /// offset pointer and addressing mode by reference if the node's address
10651 /// can be legally represented as pre-indexed load / store address.
10652 bool
10653 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10654                                              SDValue &Offset,
10655                                              ISD::MemIndexedMode &AM,
10656                                              SelectionDAG &DAG) const {
10657   if (Subtarget->isThumb1Only())
10658     return false;
10659
10660   EVT VT;
10661   SDValue Ptr;
10662   bool isSEXTLoad = false;
10663   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10664     Ptr = LD->getBasePtr();
10665     VT  = LD->getMemoryVT();
10666     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10667   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10668     Ptr = ST->getBasePtr();
10669     VT  = ST->getMemoryVT();
10670   } else
10671     return false;
10672
10673   bool isInc;
10674   bool isLegal = false;
10675   if (Subtarget->isThumb2())
10676     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10677                                        Offset, isInc, DAG);
10678   else
10679     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10680                                         Offset, isInc, DAG);
10681   if (!isLegal)
10682     return false;
10683
10684   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10685   return true;
10686 }
10687
10688 /// getPostIndexedAddressParts - returns true by value, base pointer and
10689 /// offset pointer and addressing mode by reference if this node can be
10690 /// combined with a load / store to form a post-indexed load / store.
10691 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10692                                                    SDValue &Base,
10693                                                    SDValue &Offset,
10694                                                    ISD::MemIndexedMode &AM,
10695                                                    SelectionDAG &DAG) const {
10696   if (Subtarget->isThumb1Only())
10697     return false;
10698
10699   EVT VT;
10700   SDValue Ptr;
10701   bool isSEXTLoad = false;
10702   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10703     VT  = LD->getMemoryVT();
10704     Ptr = LD->getBasePtr();
10705     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10706   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10707     VT  = ST->getMemoryVT();
10708     Ptr = ST->getBasePtr();
10709   } else
10710     return false;
10711
10712   bool isInc;
10713   bool isLegal = false;
10714   if (Subtarget->isThumb2())
10715     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10716                                        isInc, DAG);
10717   else
10718     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10719                                         isInc, DAG);
10720   if (!isLegal)
10721     return false;
10722
10723   if (Ptr != Base) {
10724     // Swap base ptr and offset to catch more post-index load / store when
10725     // it's legal. In Thumb2 mode, offset must be an immediate.
10726     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10727         !Subtarget->isThumb2())
10728       std::swap(Base, Offset);
10729
10730     // Post-indexed load / store update the base pointer.
10731     if (Ptr != Base)
10732       return false;
10733   }
10734
10735   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10736   return true;
10737 }
10738
10739 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10740                                                       APInt &KnownZero,
10741                                                       APInt &KnownOne,
10742                                                       const SelectionDAG &DAG,
10743                                                       unsigned Depth) const {
10744   unsigned BitWidth = KnownOne.getBitWidth();
10745   KnownZero = KnownOne = APInt(BitWidth, 0);
10746   switch (Op.getOpcode()) {
10747   default: break;
10748   case ARMISD::ADDC:
10749   case ARMISD::ADDE:
10750   case ARMISD::SUBC:
10751   case ARMISD::SUBE:
10752     // These nodes' second result is a boolean
10753     if (Op.getResNo() == 0)
10754       break;
10755     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10756     break;
10757   case ARMISD::CMOV: {
10758     // Bits are known zero/one if known on the LHS and RHS.
10759     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10760     if (KnownZero == 0 && KnownOne == 0) return;
10761
10762     APInt KnownZeroRHS, KnownOneRHS;
10763     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10764     KnownZero &= KnownZeroRHS;
10765     KnownOne  &= KnownOneRHS;
10766     return;
10767   }
10768   case ISD::INTRINSIC_W_CHAIN: {
10769     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10770     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10771     switch (IntID) {
10772     default: return;
10773     case Intrinsic::arm_ldaex:
10774     case Intrinsic::arm_ldrex: {
10775       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10776       unsigned MemBits = VT.getScalarType().getSizeInBits();
10777       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10778       return;
10779     }
10780     }
10781   }
10782   }
10783 }
10784
10785 //===----------------------------------------------------------------------===//
10786 //                           ARM Inline Assembly Support
10787 //===----------------------------------------------------------------------===//
10788
10789 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10790   // Looking for "rev" which is V6+.
10791   if (!Subtarget->hasV6Ops())
10792     return false;
10793
10794   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10795   std::string AsmStr = IA->getAsmString();
10796   SmallVector<StringRef, 4> AsmPieces;
10797   SplitString(AsmStr, AsmPieces, ";\n");
10798
10799   switch (AsmPieces.size()) {
10800   default: return false;
10801   case 1:
10802     AsmStr = AsmPieces[0];
10803     AsmPieces.clear();
10804     SplitString(AsmStr, AsmPieces, " \t,");
10805
10806     // rev $0, $1
10807     if (AsmPieces.size() == 3 &&
10808         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10809         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10810       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10811       if (Ty && Ty->getBitWidth() == 32)
10812         return IntrinsicLowering::LowerToByteSwap(CI);
10813     }
10814     break;
10815   }
10816
10817   return false;
10818 }
10819
10820 /// getConstraintType - Given a constraint letter, return the type of
10821 /// constraint it is for this target.
10822 ARMTargetLowering::ConstraintType
10823 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10824   if (Constraint.size() == 1) {
10825     switch (Constraint[0]) {
10826     default:  break;
10827     case 'l': return C_RegisterClass;
10828     case 'w': return C_RegisterClass;
10829     case 'h': return C_RegisterClass;
10830     case 'x': return C_RegisterClass;
10831     case 't': return C_RegisterClass;
10832     case 'j': return C_Other; // Constant for movw.
10833       // An address with a single base register. Due to the way we
10834       // currently handle addresses it is the same as an 'r' memory constraint.
10835     case 'Q': return C_Memory;
10836     }
10837   } else if (Constraint.size() == 2) {
10838     switch (Constraint[0]) {
10839     default: break;
10840     // All 'U+' constraints are addresses.
10841     case 'U': return C_Memory;
10842     }
10843   }
10844   return TargetLowering::getConstraintType(Constraint);
10845 }
10846
10847 /// Examine constraint type and operand type and determine a weight value.
10848 /// This object must already have been set up with the operand type
10849 /// and the current alternative constraint selected.
10850 TargetLowering::ConstraintWeight
10851 ARMTargetLowering::getSingleConstraintMatchWeight(
10852     AsmOperandInfo &info, const char *constraint) const {
10853   ConstraintWeight weight = CW_Invalid;
10854   Value *CallOperandVal = info.CallOperandVal;
10855     // If we don't have a value, we can't do a match,
10856     // but allow it at the lowest weight.
10857   if (!CallOperandVal)
10858     return CW_Default;
10859   Type *type = CallOperandVal->getType();
10860   // Look at the constraint type.
10861   switch (*constraint) {
10862   default:
10863     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10864     break;
10865   case 'l':
10866     if (type->isIntegerTy()) {
10867       if (Subtarget->isThumb())
10868         weight = CW_SpecificReg;
10869       else
10870         weight = CW_Register;
10871     }
10872     break;
10873   case 'w':
10874     if (type->isFloatingPointTy())
10875       weight = CW_Register;
10876     break;
10877   }
10878   return weight;
10879 }
10880
10881 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10882 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
10883     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
10884   if (Constraint.size() == 1) {
10885     // GCC ARM Constraint Letters
10886     switch (Constraint[0]) {
10887     case 'l': // Low regs or general regs.
10888       if (Subtarget->isThumb())
10889         return RCPair(0U, &ARM::tGPRRegClass);
10890       return RCPair(0U, &ARM::GPRRegClass);
10891     case 'h': // High regs or no regs.
10892       if (Subtarget->isThumb())
10893         return RCPair(0U, &ARM::hGPRRegClass);
10894       break;
10895     case 'r':
10896       if (Subtarget->isThumb1Only())
10897         return RCPair(0U, &ARM::tGPRRegClass);
10898       return RCPair(0U, &ARM::GPRRegClass);
10899     case 'w':
10900       if (VT == MVT::Other)
10901         break;
10902       if (VT == MVT::f32)
10903         return RCPair(0U, &ARM::SPRRegClass);
10904       if (VT.getSizeInBits() == 64)
10905         return RCPair(0U, &ARM::DPRRegClass);
10906       if (VT.getSizeInBits() == 128)
10907         return RCPair(0U, &ARM::QPRRegClass);
10908       break;
10909     case 'x':
10910       if (VT == MVT::Other)
10911         break;
10912       if (VT == MVT::f32)
10913         return RCPair(0U, &ARM::SPR_8RegClass);
10914       if (VT.getSizeInBits() == 64)
10915         return RCPair(0U, &ARM::DPR_8RegClass);
10916       if (VT.getSizeInBits() == 128)
10917         return RCPair(0U, &ARM::QPR_8RegClass);
10918       break;
10919     case 't':
10920       if (VT == MVT::f32)
10921         return RCPair(0U, &ARM::SPRRegClass);
10922       break;
10923     }
10924   }
10925   if (StringRef("{cc}").equals_lower(Constraint))
10926     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10927
10928   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10929 }
10930
10931 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10932 /// vector.  If it is invalid, don't add anything to Ops.
10933 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10934                                                      std::string &Constraint,
10935                                                      std::vector<SDValue>&Ops,
10936                                                      SelectionDAG &DAG) const {
10937   SDValue Result;
10938
10939   // Currently only support length 1 constraints.
10940   if (Constraint.length() != 1) return;
10941
10942   char ConstraintLetter = Constraint[0];
10943   switch (ConstraintLetter) {
10944   default: break;
10945   case 'j':
10946   case 'I': case 'J': case 'K': case 'L':
10947   case 'M': case 'N': case 'O':
10948     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10949     if (!C)
10950       return;
10951
10952     int64_t CVal64 = C->getSExtValue();
10953     int CVal = (int) CVal64;
10954     // None of these constraints allow values larger than 32 bits.  Check
10955     // that the value fits in an int.
10956     if (CVal != CVal64)
10957       return;
10958
10959     switch (ConstraintLetter) {
10960       case 'j':
10961         // Constant suitable for movw, must be between 0 and
10962         // 65535.
10963         if (Subtarget->hasV6T2Ops())
10964           if (CVal >= 0 && CVal <= 65535)
10965             break;
10966         return;
10967       case 'I':
10968         if (Subtarget->isThumb1Only()) {
10969           // This must be a constant between 0 and 255, for ADD
10970           // immediates.
10971           if (CVal >= 0 && CVal <= 255)
10972             break;
10973         } else if (Subtarget->isThumb2()) {
10974           // A constant that can be used as an immediate value in a
10975           // data-processing instruction.
10976           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10977             break;
10978         } else {
10979           // A constant that can be used as an immediate value in a
10980           // data-processing instruction.
10981           if (ARM_AM::getSOImmVal(CVal) != -1)
10982             break;
10983         }
10984         return;
10985
10986       case 'J':
10987         if (Subtarget->isThumb()) {  // FIXME thumb2
10988           // This must be a constant between -255 and -1, for negated ADD
10989           // immediates. This can be used in GCC with an "n" modifier that
10990           // prints the negated value, for use with SUB instructions. It is
10991           // not useful otherwise but is implemented for compatibility.
10992           if (CVal >= -255 && CVal <= -1)
10993             break;
10994         } else {
10995           // This must be a constant between -4095 and 4095. It is not clear
10996           // what this constraint is intended for. Implemented for
10997           // compatibility with GCC.
10998           if (CVal >= -4095 && CVal <= 4095)
10999             break;
11000         }
11001         return;
11002
11003       case 'K':
11004         if (Subtarget->isThumb1Only()) {
11005           // A 32-bit value where only one byte has a nonzero value. Exclude
11006           // zero to match GCC. This constraint is used by GCC internally for
11007           // constants that can be loaded with a move/shift combination.
11008           // It is not useful otherwise but is implemented for compatibility.
11009           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11010             break;
11011         } else if (Subtarget->isThumb2()) {
11012           // A constant whose bitwise inverse can be used as an immediate
11013           // value in a data-processing instruction. This can be used in GCC
11014           // with a "B" modifier that prints the inverted value, for use with
11015           // BIC and MVN instructions. It is not useful otherwise but is
11016           // implemented for compatibility.
11017           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11018             break;
11019         } else {
11020           // A constant whose bitwise inverse can be used as an immediate
11021           // value in a data-processing instruction. This can be used in GCC
11022           // with a "B" modifier that prints the inverted value, for use with
11023           // BIC and MVN instructions. It is not useful otherwise but is
11024           // implemented for compatibility.
11025           if (ARM_AM::getSOImmVal(~CVal) != -1)
11026             break;
11027         }
11028         return;
11029
11030       case 'L':
11031         if (Subtarget->isThumb1Only()) {
11032           // This must be a constant between -7 and 7,
11033           // for 3-operand ADD/SUB immediate instructions.
11034           if (CVal >= -7 && CVal < 7)
11035             break;
11036         } else if (Subtarget->isThumb2()) {
11037           // A constant whose negation can be used as an immediate value in a
11038           // data-processing instruction. This can be used in GCC with an "n"
11039           // modifier that prints the negated value, for use with SUB
11040           // instructions. It is not useful otherwise but is implemented for
11041           // compatibility.
11042           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11043             break;
11044         } else {
11045           // A constant whose negation can be used as an immediate value in a
11046           // data-processing instruction. This can be used in GCC with an "n"
11047           // modifier that prints the negated value, for use with SUB
11048           // instructions. It is not useful otherwise but is implemented for
11049           // compatibility.
11050           if (ARM_AM::getSOImmVal(-CVal) != -1)
11051             break;
11052         }
11053         return;
11054
11055       case 'M':
11056         if (Subtarget->isThumb()) { // FIXME thumb2
11057           // This must be a multiple of 4 between 0 and 1020, for
11058           // ADD sp + immediate.
11059           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11060             break;
11061         } else {
11062           // A power of two or a constant between 0 and 32.  This is used in
11063           // GCC for the shift amount on shifted register operands, but it is
11064           // useful in general for any shift amounts.
11065           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11066             break;
11067         }
11068         return;
11069
11070       case 'N':
11071         if (Subtarget->isThumb()) {  // FIXME thumb2
11072           // This must be a constant between 0 and 31, for shift amounts.
11073           if (CVal >= 0 && CVal <= 31)
11074             break;
11075         }
11076         return;
11077
11078       case 'O':
11079         if (Subtarget->isThumb()) {  // FIXME thumb2
11080           // This must be a multiple of 4 between -508 and 508, for
11081           // ADD/SUB sp = sp + immediate.
11082           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11083             break;
11084         }
11085         return;
11086     }
11087     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11088     break;
11089   }
11090
11091   if (Result.getNode()) {
11092     Ops.push_back(Result);
11093     return;
11094   }
11095   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11096 }
11097
11098 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11099   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11100          "Register-based DivRem lowering only");
11101   unsigned Opcode = Op->getOpcode();
11102   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11103          "Invalid opcode for Div/Rem lowering");
11104   bool isSigned = (Opcode == ISD::SDIVREM);
11105   EVT VT = Op->getValueType(0);
11106   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11107
11108   RTLIB::Libcall LC;
11109   switch (VT.getSimpleVT().SimpleTy) {
11110   default: llvm_unreachable("Unexpected request for libcall!");
11111   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11112   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11113   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11114   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11115   }
11116
11117   SDValue InChain = DAG.getEntryNode();
11118
11119   TargetLowering::ArgListTy Args;
11120   TargetLowering::ArgListEntry Entry;
11121   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11122     EVT ArgVT = Op->getOperand(i).getValueType();
11123     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11124     Entry.Node = Op->getOperand(i);
11125     Entry.Ty = ArgTy;
11126     Entry.isSExt = isSigned;
11127     Entry.isZExt = !isSigned;
11128     Args.push_back(Entry);
11129   }
11130
11131   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11132                                          getPointerTy(DAG.getDataLayout()));
11133
11134   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11135
11136   SDLoc dl(Op);
11137   TargetLowering::CallLoweringInfo CLI(DAG);
11138   CLI.setDebugLoc(dl).setChain(InChain)
11139     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11140     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11141
11142   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11143   return CallInfo.first;
11144 }
11145
11146 SDValue
11147 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11148   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11149   SDLoc DL(Op);
11150
11151   // Get the inputs.
11152   SDValue Chain = Op.getOperand(0);
11153   SDValue Size  = Op.getOperand(1);
11154
11155   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11156                               DAG.getConstant(2, DL, MVT::i32));
11157
11158   SDValue Flag;
11159   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11160   Flag = Chain.getValue(1);
11161
11162   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11163   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11164
11165   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11166   Chain = NewSP.getValue(1);
11167
11168   SDValue Ops[2] = { NewSP, Chain };
11169   return DAG.getMergeValues(Ops, DL);
11170 }
11171
11172 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11173   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11174          "Unexpected type for custom-lowering FP_EXTEND");
11175
11176   RTLIB::Libcall LC;
11177   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11178
11179   SDValue SrcVal = Op.getOperand(0);
11180   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11181                      /*isSigned*/ false, SDLoc(Op)).first;
11182 }
11183
11184 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11185   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11186          Subtarget->isFPOnlySP() &&
11187          "Unexpected type for custom-lowering FP_ROUND");
11188
11189   RTLIB::Libcall LC;
11190   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11191
11192   SDValue SrcVal = Op.getOperand(0);
11193   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11194                      /*isSigned*/ false, SDLoc(Op)).first;
11195 }
11196
11197 bool
11198 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11199   // The ARM target isn't yet aware of offsets.
11200   return false;
11201 }
11202
11203 bool ARM::isBitFieldInvertedMask(unsigned v) {
11204   if (v == 0xffffffff)
11205     return false;
11206
11207   // there can be 1's on either or both "outsides", all the "inside"
11208   // bits must be 0's
11209   return isShiftedMask_32(~v);
11210 }
11211
11212 /// isFPImmLegal - Returns true if the target can instruction select the
11213 /// specified FP immediate natively. If false, the legalizer will
11214 /// materialize the FP immediate as a load from a constant pool.
11215 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11216   if (!Subtarget->hasVFP3())
11217     return false;
11218   if (VT == MVT::f32)
11219     return ARM_AM::getFP32Imm(Imm) != -1;
11220   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11221     return ARM_AM::getFP64Imm(Imm) != -1;
11222   return false;
11223 }
11224
11225 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11226 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11227 /// specified in the intrinsic calls.
11228 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11229                                            const CallInst &I,
11230                                            unsigned Intrinsic) const {
11231   switch (Intrinsic) {
11232   case Intrinsic::arm_neon_vld1:
11233   case Intrinsic::arm_neon_vld2:
11234   case Intrinsic::arm_neon_vld3:
11235   case Intrinsic::arm_neon_vld4:
11236   case Intrinsic::arm_neon_vld2lane:
11237   case Intrinsic::arm_neon_vld3lane:
11238   case Intrinsic::arm_neon_vld4lane: {
11239     Info.opc = ISD::INTRINSIC_W_CHAIN;
11240     // Conservatively set memVT to the entire set of vectors loaded.
11241     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11242     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11243     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11244     Info.ptrVal = I.getArgOperand(0);
11245     Info.offset = 0;
11246     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11247     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11248     Info.vol = false; // volatile loads with NEON intrinsics not supported
11249     Info.readMem = true;
11250     Info.writeMem = false;
11251     return true;
11252   }
11253   case Intrinsic::arm_neon_vst1:
11254   case Intrinsic::arm_neon_vst2:
11255   case Intrinsic::arm_neon_vst3:
11256   case Intrinsic::arm_neon_vst4:
11257   case Intrinsic::arm_neon_vst2lane:
11258   case Intrinsic::arm_neon_vst3lane:
11259   case Intrinsic::arm_neon_vst4lane: {
11260     Info.opc = ISD::INTRINSIC_VOID;
11261     // Conservatively set memVT to the entire set of vectors stored.
11262     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11263     unsigned NumElts = 0;
11264     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11265       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11266       if (!ArgTy->isVectorTy())
11267         break;
11268       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11269     }
11270     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11271     Info.ptrVal = I.getArgOperand(0);
11272     Info.offset = 0;
11273     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11274     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11275     Info.vol = false; // volatile stores with NEON intrinsics not supported
11276     Info.readMem = false;
11277     Info.writeMem = true;
11278     return true;
11279   }
11280   case Intrinsic::arm_ldaex:
11281   case Intrinsic::arm_ldrex: {
11282     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11283     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11284     Info.opc = ISD::INTRINSIC_W_CHAIN;
11285     Info.memVT = MVT::getVT(PtrTy->getElementType());
11286     Info.ptrVal = I.getArgOperand(0);
11287     Info.offset = 0;
11288     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11289     Info.vol = true;
11290     Info.readMem = true;
11291     Info.writeMem = false;
11292     return true;
11293   }
11294   case Intrinsic::arm_stlex:
11295   case Intrinsic::arm_strex: {
11296     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11297     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11298     Info.opc = ISD::INTRINSIC_W_CHAIN;
11299     Info.memVT = MVT::getVT(PtrTy->getElementType());
11300     Info.ptrVal = I.getArgOperand(1);
11301     Info.offset = 0;
11302     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11303     Info.vol = true;
11304     Info.readMem = false;
11305     Info.writeMem = true;
11306     return true;
11307   }
11308   case Intrinsic::arm_stlexd:
11309   case Intrinsic::arm_strexd: {
11310     Info.opc = ISD::INTRINSIC_W_CHAIN;
11311     Info.memVT = MVT::i64;
11312     Info.ptrVal = I.getArgOperand(2);
11313     Info.offset = 0;
11314     Info.align = 8;
11315     Info.vol = true;
11316     Info.readMem = false;
11317     Info.writeMem = true;
11318     return true;
11319   }
11320   case Intrinsic::arm_ldaexd:
11321   case Intrinsic::arm_ldrexd: {
11322     Info.opc = ISD::INTRINSIC_W_CHAIN;
11323     Info.memVT = MVT::i64;
11324     Info.ptrVal = I.getArgOperand(0);
11325     Info.offset = 0;
11326     Info.align = 8;
11327     Info.vol = true;
11328     Info.readMem = true;
11329     Info.writeMem = false;
11330     return true;
11331   }
11332   default:
11333     break;
11334   }
11335
11336   return false;
11337 }
11338
11339 /// \brief Returns true if it is beneficial to convert a load of a constant
11340 /// to just the constant itself.
11341 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11342                                                           Type *Ty) const {
11343   assert(Ty->isIntegerTy());
11344
11345   unsigned Bits = Ty->getPrimitiveSizeInBits();
11346   if (Bits == 0 || Bits > 32)
11347     return false;
11348   return true;
11349 }
11350
11351 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11352
11353 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11354                                         ARM_MB::MemBOpt Domain) const {
11355   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11356
11357   // First, if the target has no DMB, see what fallback we can use.
11358   if (!Subtarget->hasDataBarrier()) {
11359     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11360     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11361     // here.
11362     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11363       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11364       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11365                         Builder.getInt32(0), Builder.getInt32(7),
11366                         Builder.getInt32(10), Builder.getInt32(5)};
11367       return Builder.CreateCall(MCR, args);
11368     } else {
11369       // Instead of using barriers, atomic accesses on these subtargets use
11370       // libcalls.
11371       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11372     }
11373   } else {
11374     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11375     // Only a full system barrier exists in the M-class architectures.
11376     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11377     Constant *CDomain = Builder.getInt32(Domain);
11378     return Builder.CreateCall(DMB, CDomain);
11379   }
11380 }
11381
11382 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11383 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11384                                          AtomicOrdering Ord, bool IsStore,
11385                                          bool IsLoad) const {
11386   if (!getInsertFencesForAtomic())
11387     return nullptr;
11388
11389   switch (Ord) {
11390   case NotAtomic:
11391   case Unordered:
11392     llvm_unreachable("Invalid fence: unordered/non-atomic");
11393   case Monotonic:
11394   case Acquire:
11395     return nullptr; // Nothing to do
11396   case SequentiallyConsistent:
11397     if (!IsStore)
11398       return nullptr; // Nothing to do
11399     /*FALLTHROUGH*/
11400   case Release:
11401   case AcquireRelease:
11402     if (Subtarget->isSwift())
11403       return makeDMB(Builder, ARM_MB::ISHST);
11404     // FIXME: add a comment with a link to documentation justifying this.
11405     else
11406       return makeDMB(Builder, ARM_MB::ISH);
11407   }
11408   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11409 }
11410
11411 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11412                                           AtomicOrdering Ord, bool IsStore,
11413                                           bool IsLoad) const {
11414   if (!getInsertFencesForAtomic())
11415     return nullptr;
11416
11417   switch (Ord) {
11418   case NotAtomic:
11419   case Unordered:
11420     llvm_unreachable("Invalid fence: unordered/not-atomic");
11421   case Monotonic:
11422   case Release:
11423     return nullptr; // Nothing to do
11424   case Acquire:
11425   case AcquireRelease:
11426   case SequentiallyConsistent:
11427     return makeDMB(Builder, ARM_MB::ISH);
11428   }
11429   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11430 }
11431
11432 // Loads and stores less than 64-bits are already atomic; ones above that
11433 // are doomed anyway, so defer to the default libcall and blame the OS when
11434 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11435 // anything for those.
11436 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11437   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11438   return (Size == 64) && !Subtarget->isMClass();
11439 }
11440
11441 // Loads and stores less than 64-bits are already atomic; ones above that
11442 // are doomed anyway, so defer to the default libcall and blame the OS when
11443 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11444 // anything for those.
11445 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11446 // guarantee, see DDI0406C ARM architecture reference manual,
11447 // sections A8.8.72-74 LDRD)
11448 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11449   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11450   return (Size == 64) && !Subtarget->isMClass();
11451 }
11452
11453 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11454 // and up to 64 bits on the non-M profiles
11455 TargetLoweringBase::AtomicRMWExpansionKind
11456 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11457   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11458   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11459              ? AtomicRMWExpansionKind::LLSC
11460              : AtomicRMWExpansionKind::None;
11461 }
11462
11463 // This has so far only been implemented for MachO.
11464 bool ARMTargetLowering::useLoadStackGuardNode() const {
11465   return Subtarget->isTargetMachO();
11466 }
11467
11468 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11469                                                   unsigned &Cost) const {
11470   // If we do not have NEON, vector types are not natively supported.
11471   if (!Subtarget->hasNEON())
11472     return false;
11473
11474   // Floating point values and vector values map to the same register file.
11475   // Therefore, although we could do a store extract of a vector type, this is
11476   // better to leave at float as we have more freedom in the addressing mode for
11477   // those.
11478   if (VectorTy->isFPOrFPVectorTy())
11479     return false;
11480
11481   // If the index is unknown at compile time, this is very expensive to lower
11482   // and it is not possible to combine the store with the extract.
11483   if (!isa<ConstantInt>(Idx))
11484     return false;
11485
11486   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11487   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11488   // We can do a store + vector extract on any vector that fits perfectly in a D
11489   // or Q register.
11490   if (BitWidth == 64 || BitWidth == 128) {
11491     Cost = 0;
11492     return true;
11493   }
11494   return false;
11495 }
11496
11497 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11498                                          AtomicOrdering Ord) const {
11499   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11500   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11501   bool IsAcquire = isAtLeastAcquire(Ord);
11502
11503   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11504   // intrinsic must return {i32, i32} and we have to recombine them into a
11505   // single i64 here.
11506   if (ValTy->getPrimitiveSizeInBits() == 64) {
11507     Intrinsic::ID Int =
11508         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11509     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11510
11511     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11512     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11513
11514     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11515     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11516     if (!Subtarget->isLittle())
11517       std::swap (Lo, Hi);
11518     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11519     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11520     return Builder.CreateOr(
11521         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11522   }
11523
11524   Type *Tys[] = { Addr->getType() };
11525   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11526   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11527
11528   return Builder.CreateTruncOrBitCast(
11529       Builder.CreateCall(Ldrex, Addr),
11530       cast<PointerType>(Addr->getType())->getElementType());
11531 }
11532
11533 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11534                                                Value *Addr,
11535                                                AtomicOrdering Ord) const {
11536   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11537   bool IsRelease = isAtLeastRelease(Ord);
11538
11539   // Since the intrinsics must have legal type, the i64 intrinsics take two
11540   // parameters: "i32, i32". We must marshal Val into the appropriate form
11541   // before the call.
11542   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11543     Intrinsic::ID Int =
11544         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11545     Function *Strex = Intrinsic::getDeclaration(M, Int);
11546     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11547
11548     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11549     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11550     if (!Subtarget->isLittle())
11551       std::swap (Lo, Hi);
11552     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11553     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11554   }
11555
11556   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11557   Type *Tys[] = { Addr->getType() };
11558   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11559
11560   return Builder.CreateCall(
11561       Strex, {Builder.CreateZExtOrBitCast(
11562                   Val, Strex->getFunctionType()->getParamType(0)),
11563               Addr});
11564 }
11565
11566 /// \brief Lower an interleaved load into a vldN intrinsic.
11567 ///
11568 /// E.g. Lower an interleaved load (Factor = 2):
11569 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11570 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11571 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11572 ///
11573 ///      Into:
11574 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11575 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11576 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11577 bool ARMTargetLowering::lowerInterleavedLoad(
11578     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11579     ArrayRef<unsigned> Indices, unsigned Factor) const {
11580   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11581          "Invalid interleave factor");
11582   assert(!Shuffles.empty() && "Empty shufflevector input");
11583   assert(Shuffles.size() == Indices.size() &&
11584          "Unmatched number of shufflevectors and indices");
11585
11586   VectorType *VecTy = Shuffles[0]->getType();
11587   Type *EltTy = VecTy->getVectorElementType();
11588
11589   const DataLayout &DL = LI->getModule()->getDataLayout();
11590   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11591   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11592
11593   // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11594   // support i64/f64 element).
11595   if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11596     return false;
11597
11598   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11599   // load integer vectors first and then convert to pointer vectors.
11600   if (EltTy->isPointerTy())
11601     VecTy =
11602         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11603
11604   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11605                                             Intrinsic::arm_neon_vld3,
11606                                             Intrinsic::arm_neon_vld4};
11607
11608   Function *VldnFunc =
11609       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11610
11611   IRBuilder<> Builder(LI);
11612   SmallVector<Value *, 2> Ops;
11613
11614   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11615   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11616   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11617
11618   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11619
11620   // Replace uses of each shufflevector with the corresponding vector loaded
11621   // by ldN.
11622   for (unsigned i = 0; i < Shuffles.size(); i++) {
11623     ShuffleVectorInst *SV = Shuffles[i];
11624     unsigned Index = Indices[i];
11625
11626     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11627
11628     // Convert the integer vector to pointer vector if the element is pointer.
11629     if (EltTy->isPointerTy())
11630       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11631
11632     SV->replaceAllUsesWith(SubVec);
11633   }
11634
11635   return true;
11636 }
11637
11638 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11639 ///
11640 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11641 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11642                                    unsigned NumElts) {
11643   SmallVector<Constant *, 16> Mask;
11644   for (unsigned i = 0; i < NumElts; i++)
11645     Mask.push_back(Builder.getInt32(Start + i));
11646
11647   return ConstantVector::get(Mask);
11648 }
11649
11650 /// \brief Lower an interleaved store into a vstN intrinsic.
11651 ///
11652 /// E.g. Lower an interleaved store (Factor = 3):
11653 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11654 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11655 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11656 ///
11657 ///      Into:
11658 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11659 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11660 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11661 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11662 ///
11663 /// Note that the new shufflevectors will be removed and we'll only generate one
11664 /// vst3 instruction in CodeGen.
11665 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11666                                               ShuffleVectorInst *SVI,
11667                                               unsigned Factor) const {
11668   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11669          "Invalid interleave factor");
11670
11671   VectorType *VecTy = SVI->getType();
11672   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11673          "Invalid interleaved store");
11674
11675   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11676   Type *EltTy = VecTy->getVectorElementType();
11677   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11678
11679   const DataLayout &DL = SI->getModule()->getDataLayout();
11680   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11681   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11682
11683   // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11684   // doesn't support i64/f64 element).
11685   if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11686     return false;
11687
11688   Value *Op0 = SVI->getOperand(0);
11689   Value *Op1 = SVI->getOperand(1);
11690   IRBuilder<> Builder(SI);
11691
11692   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11693   // vectors to integer vectors.
11694   if (EltTy->isPointerTy()) {
11695     Type *IntTy = DL.getIntPtrType(EltTy);
11696
11697     // Convert to the corresponding integer vector.
11698     Type *IntVecTy =
11699         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11700     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11701     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11702
11703     SubVecTy = VectorType::get(IntTy, NumSubElts);
11704   }
11705
11706   static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11707                                        Intrinsic::arm_neon_vst3,
11708                                        Intrinsic::arm_neon_vst4};
11709   Function *VstNFunc = Intrinsic::getDeclaration(
11710       SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11711
11712   SmallVector<Value *, 6> Ops;
11713
11714   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11715   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11716
11717   // Split the shufflevector operands into sub vectors for the new vstN call.
11718   for (unsigned i = 0; i < Factor; i++)
11719     Ops.push_back(Builder.CreateShuffleVector(
11720         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11721
11722   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11723   Builder.CreateCall(VstNFunc, Ops);
11724   return true;
11725 }
11726
11727 enum HABaseType {
11728   HA_UNKNOWN = 0,
11729   HA_FLOAT,
11730   HA_DOUBLE,
11731   HA_VECT64,
11732   HA_VECT128
11733 };
11734
11735 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11736                                    uint64_t &Members) {
11737   if (auto *ST = dyn_cast<StructType>(Ty)) {
11738     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11739       uint64_t SubMembers = 0;
11740       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11741         return false;
11742       Members += SubMembers;
11743     }
11744   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11745     uint64_t SubMembers = 0;
11746     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11747       return false;
11748     Members += SubMembers * AT->getNumElements();
11749   } else if (Ty->isFloatTy()) {
11750     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11751       return false;
11752     Members = 1;
11753     Base = HA_FLOAT;
11754   } else if (Ty->isDoubleTy()) {
11755     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11756       return false;
11757     Members = 1;
11758     Base = HA_DOUBLE;
11759   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11760     Members = 1;
11761     switch (Base) {
11762     case HA_FLOAT:
11763     case HA_DOUBLE:
11764       return false;
11765     case HA_VECT64:
11766       return VT->getBitWidth() == 64;
11767     case HA_VECT128:
11768       return VT->getBitWidth() == 128;
11769     case HA_UNKNOWN:
11770       switch (VT->getBitWidth()) {
11771       case 64:
11772         Base = HA_VECT64;
11773         return true;
11774       case 128:
11775         Base = HA_VECT128;
11776         return true;
11777       default:
11778         return false;
11779       }
11780     }
11781   }
11782
11783   return (Members > 0 && Members <= 4);
11784 }
11785
11786 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11787 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11788 /// passing according to AAPCS rules.
11789 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11790     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11791   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11792       CallingConv::ARM_AAPCS_VFP)
11793     return false;
11794
11795   HABaseType Base = HA_UNKNOWN;
11796   uint64_t Members = 0;
11797   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11798   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11799
11800   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11801   return IsHA || IsIntArray;
11802 }