Rip out hand-rolled matching code for VMIN, VMAX, VMINNM and VMAXNM
[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 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::DPairRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
163                                      const ARMSubtarget &STI)
164     : TargetLowering(TM), Subtarget(&STI) {
165   RegInfo = Subtarget->getRegisterInfo();
166   Itins = Subtarget->getInstrItineraryData();
167
168   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
169
170   if (Subtarget->isTargetMachO()) {
171     // Uses VFP for Thumb libfuncs if available.
172     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
173         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
174       static const struct {
175         const RTLIB::Libcall Op;
176         const char * const Name;
177         const ISD::CondCode Cond;
178       } LibraryCalls[] = {
179         // Single-precision floating-point arithmetic.
180         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
181         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
182         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
183         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
184
185         // Double-precision floating-point arithmetic.
186         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
187         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
188         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
189         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
190
191         // Single-precision comparisons.
192         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
193         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
194         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
195         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
196         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
197         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
198         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
199         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
200
201         // Double-precision comparisons.
202         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
203         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
204         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
205         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
206         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
207         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
208         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
209         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
210
211         // Floating-point to integer conversions.
212         // i64 conversions are done via library routines even when generating VFP
213         // instructions, so use the same ones.
214         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
215         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
216         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
217         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
218
219         // Conversions between floating types.
220         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
221         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
222
223         // Integer to floating-point conversions.
224         // i64 conversions are done via library routines even when generating VFP
225         // instructions, so use the same ones.
226         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
227         // e.g., __floatunsidf vs. __floatunssidfvfp.
228         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
229         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
230         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
231         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
232       };
233
234       for (const auto &LC : LibraryCalls) {
235         setLibcallName(LC.Op, LC.Name);
236         if (LC.Cond != ISD::SETCC_INVALID)
237           setCmpLibcallCC(LC.Op, LC.Cond);
238       }
239     }
240   }
241
242   // These libcalls are not available in 32-bit.
243   setLibcallName(RTLIB::SHL_I128, nullptr);
244   setLibcallName(RTLIB::SRL_I128, nullptr);
245   setLibcallName(RTLIB::SRA_I128, nullptr);
246
247   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
248       !Subtarget->isTargetWindows()) {
249     static const struct {
250       const RTLIB::Libcall Op;
251       const char * const Name;
252       const CallingConv::ID CC;
253       const ISD::CondCode Cond;
254     } LibraryCalls[] = {
255       // Double-precision floating-point arithmetic helper functions
256       // RTABI chapter 4.1.2, Table 2
257       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
258       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
259       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
260       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
261
262       // Double-precision floating-point comparison helper functions
263       // RTABI chapter 4.1.2, Table 3
264       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
265       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
266       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
267       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
268       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
269       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
270       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
271       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
272
273       // Single-precision floating-point arithmetic helper functions
274       // RTABI chapter 4.1.2, Table 4
275       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
276       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
277       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
278       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
279
280       // Single-precision floating-point comparison helper functions
281       // RTABI chapter 4.1.2, Table 5
282       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
283       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
284       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
285       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
286       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
287       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
288       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
289       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
290
291       // Floating-point to integer conversions.
292       // RTABI chapter 4.1.2, Table 6
293       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
294       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
295       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
296       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
297       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
298       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301
302       // Conversions between floating types.
303       // RTABI chapter 4.1.2, Table 7
304       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307
308       // Integer to floating-point conversions.
309       // RTABI chapter 4.1.2, Table 8
310       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318
319       // Long long helper functions
320       // RTABI chapter 4.2, Table 9
321       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325
326       // Integer division functions
327       // RTABI chapter 4.3.1
328       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336
337       // Memory operations
338       // RTABI chapter 4.3.4
339       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342     };
343
344     for (const auto &LC : LibraryCalls) {
345       setLibcallName(LC.Op, LC.Name);
346       setLibcallCallingConv(LC.Op, LC.CC);
347       if (LC.Cond != ISD::SETCC_INVALID)
348         setCmpLibcallCC(LC.Op, LC.Cond);
349     }
350   }
351
352   if (Subtarget->isTargetWindows()) {
353     static const struct {
354       const RTLIB::Libcall Op;
355       const char * const Name;
356       const CallingConv::ID CC;
357     } LibraryCalls[] = {
358       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
359       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
360       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
361       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
362       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
363       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
364       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
366
367       { RTLIB::SDIV_I32, "__rt_sdiv",   CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::UDIV_I32, "__rt_udiv",   CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::UDIV_I64, "__rt_udiv64", CallingConv::ARM_AAPCS_VFP },
371     };
372
373     for (const auto &LC : LibraryCalls) {
374       setLibcallName(LC.Op, LC.Name);
375       setLibcallCallingConv(LC.Op, LC.CC);
376     }
377   }
378
379   // Use divmod compiler-rt calls for iOS 5.0 and later.
380   if (Subtarget->getTargetTriple().isiOS() &&
381       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
382     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
383     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
384   }
385
386   // The half <-> float conversion functions are always soft-float, but are
387   // needed for some targets which use a hard-float calling convention by
388   // default.
389   if (Subtarget->isAAPCS_ABI()) {
390     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
393   } else {
394     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
395     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
396     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
397   }
398
399   if (Subtarget->isThumb1Only())
400     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
401   else
402     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
403   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
404       !Subtarget->isThumb1Only()) {
405     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
406     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
407   }
408
409   for (MVT VT : MVT::vector_valuetypes()) {
410     for (MVT InnerVT : MVT::vector_valuetypes()) {
411       setTruncStoreAction(VT, InnerVT, Expand);
412       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
413       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
414       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
415     }
416
417     setOperationAction(ISD::MULHS, VT, Expand);
418     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
419     setOperationAction(ISD::MULHU, VT, Expand);
420     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
421
422     setOperationAction(ISD::BSWAP, VT, Expand);
423   }
424
425   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
426   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
427
428   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
429   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
430
431   if (Subtarget->hasNEON()) {
432     addDRTypeForNEON(MVT::v2f32);
433     addDRTypeForNEON(MVT::v8i8);
434     addDRTypeForNEON(MVT::v4i16);
435     addDRTypeForNEON(MVT::v2i32);
436     addDRTypeForNEON(MVT::v1i64);
437
438     addQRTypeForNEON(MVT::v4f32);
439     addQRTypeForNEON(MVT::v2f64);
440     addQRTypeForNEON(MVT::v16i8);
441     addQRTypeForNEON(MVT::v8i16);
442     addQRTypeForNEON(MVT::v4i32);
443     addQRTypeForNEON(MVT::v2i64);
444
445     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
446     // neither Neon nor VFP support any arithmetic operations on it.
447     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
448     // supported for v4f32.
449     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
450     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
451     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
452     // FIXME: Code duplication: FDIV and FREM are expanded always, see
453     // ARMTargetLowering::addTypeForNEON method for details.
454     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
455     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
456     // FIXME: Create unittest.
457     // In another words, find a way when "copysign" appears in DAG with vector
458     // operands.
459     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
460     // FIXME: Code duplication: SETCC has custom operation action, see
461     // ARMTargetLowering::addTypeForNEON method for details.
462     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
463     // FIXME: Create unittest for FNEG and for FABS.
464     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
465     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
466     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
467     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
468     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
469     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
470     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
471     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
472     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
473     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
474     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
475     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
476     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
477     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
478     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
479     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
480     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
481     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
482     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
483
484     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
485     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
486     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
487     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
488     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
489     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
490     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
491     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
492     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
493     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
494     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
495     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
496     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
497     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
498     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
499
500     // Mark v2f32 intrinsics.
501     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
502     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
503     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
504     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
505     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
506     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
507     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
508     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
509     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
510     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
511     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
512     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
513     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
514     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
515     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
516
517     // Neon does not support some operations on v1i64 and v2i64 types.
518     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
519     // Custom handling for some quad-vector types to detect VMULL.
520     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
521     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
522     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
523     // Custom handling for some vector types to avoid expensive expansions
524     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
525     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
526     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
527     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
528     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
529     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
530     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
531     // a destination type that is wider than the source, and nor does
532     // it have a FP_TO_[SU]INT instruction with a narrower destination than
533     // source.
534     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
535     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
536     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
537     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
538
539     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
540     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
541
542     // NEON does not have single instruction CTPOP for vectors with element
543     // types wider than 8-bits.  However, custom lowering can leverage the
544     // v8i8/v16i8 vcnt instruction.
545     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
546     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
547     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
548     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
549
550     // NEON does not have single instruction CTTZ for vectors.
551     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
552     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
553     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
554     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
555
556     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
557     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
558     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
559     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
560
561     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
562     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
563     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
564     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
565
566     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
567     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
568     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
569     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
570
571     // NEON only has FMA instructions as of VFP4.
572     if (!Subtarget->hasVFP4()) {
573       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
574       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
575     }
576
577     setTargetDAGCombine(ISD::INTRINSIC_VOID);
578     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
579     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
580     setTargetDAGCombine(ISD::SHL);
581     setTargetDAGCombine(ISD::SRL);
582     setTargetDAGCombine(ISD::SRA);
583     setTargetDAGCombine(ISD::SIGN_EXTEND);
584     setTargetDAGCombine(ISD::ZERO_EXTEND);
585     setTargetDAGCombine(ISD::ANY_EXTEND);
586     setTargetDAGCombine(ISD::BUILD_VECTOR);
587     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
588     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
589     setTargetDAGCombine(ISD::STORE);
590     setTargetDAGCombine(ISD::FP_TO_SINT);
591     setTargetDAGCombine(ISD::FP_TO_UINT);
592     setTargetDAGCombine(ISD::FDIV);
593     setTargetDAGCombine(ISD::LOAD);
594
595     // It is legal to extload from v4i8 to v4i16 or v4i32.
596     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
597                    MVT::v2i32}) {
598       for (MVT VT : MVT::integer_vector_valuetypes()) {
599         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
600         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
601         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
602       }
603     }
604   }
605
606   // ARM and Thumb2 support UMLAL/SMLAL.
607   if (!Subtarget->isThumb1Only())
608     setTargetDAGCombine(ISD::ADDC);
609
610   if (Subtarget->isFPOnlySP()) {
611     // When targeting a floating-point unit with only single-precision
612     // operations, f64 is legal for the few double-precision instructions which
613     // are present However, no double-precision operations other than moves,
614     // loads and stores are provided by the hardware.
615     setOperationAction(ISD::FADD,       MVT::f64, Expand);
616     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
617     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
618     setOperationAction(ISD::FMA,        MVT::f64, Expand);
619     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
620     setOperationAction(ISD::FREM,       MVT::f64, Expand);
621     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
622     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
623     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
624     setOperationAction(ISD::FABS,       MVT::f64, Expand);
625     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
626     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
627     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
628     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
629     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
630     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
631     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
632     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
633     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
634     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
635     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
636     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
637     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
638     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
639     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
640     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
641     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
642     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
643     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
644     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
645     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
646     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
647     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
648   }
649
650   computeRegisterProperties(Subtarget->getRegisterInfo());
651
652   // ARM does not have floating-point extending loads.
653   for (MVT VT : MVT::fp_valuetypes()) {
654     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
655     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
656   }
657
658   // ... or truncating stores
659   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
660   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
661   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
662
663   // ARM does not have i1 sign extending load.
664   for (MVT VT : MVT::integer_valuetypes())
665     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
666
667   // ARM supports all 4 flavors of integer indexed load / store.
668   if (!Subtarget->isThumb1Only()) {
669     for (unsigned im = (unsigned)ISD::PRE_INC;
670          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
671       setIndexedLoadAction(im,  MVT::i1,  Legal);
672       setIndexedLoadAction(im,  MVT::i8,  Legal);
673       setIndexedLoadAction(im,  MVT::i16, Legal);
674       setIndexedLoadAction(im,  MVT::i32, Legal);
675       setIndexedStoreAction(im, MVT::i1,  Legal);
676       setIndexedStoreAction(im, MVT::i8,  Legal);
677       setIndexedStoreAction(im, MVT::i16, Legal);
678       setIndexedStoreAction(im, MVT::i32, Legal);
679     }
680   }
681
682   setOperationAction(ISD::SADDO, MVT::i32, Custom);
683   setOperationAction(ISD::UADDO, MVT::i32, Custom);
684   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
685   setOperationAction(ISD::USUBO, MVT::i32, Custom);
686
687   // i64 operation support.
688   setOperationAction(ISD::MUL,     MVT::i64, Expand);
689   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
690   if (Subtarget->isThumb1Only()) {
691     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
692     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
693   }
694   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
695       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
696     setOperationAction(ISD::MULHS, MVT::i32, Expand);
697
698   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
699   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
700   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
701   setOperationAction(ISD::SRL,       MVT::i64, Custom);
702   setOperationAction(ISD::SRA,       MVT::i64, Custom);
703
704   if (!Subtarget->isThumb1Only()) {
705     // FIXME: We should do this for Thumb1 as well.
706     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
707     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
708     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
709     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
710   }
711
712   // ARM does not have ROTL.
713   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
714   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
715   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
716   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
717     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
718
719   // These just redirect to CTTZ and CTLZ on ARM.
720   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
721   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
722
723   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
724
725   // Only ARMv6 has BSWAP.
726   if (!Subtarget->hasV6Ops())
727     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
728
729   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
730       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
731     // These are expanded into libcalls if the cpu doesn't have HW divider.
732     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
733     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
734   }
735
736   // FIXME: Also set divmod for SREM on EABI/androideabi
737   setOperationAction(ISD::SREM,  MVT::i32, Expand);
738   setOperationAction(ISD::UREM,  MVT::i32, Expand);
739   // Register based DivRem for AEABI (RTABI 4.2)
740   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
741     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
742     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
743     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
744     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
745     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
746     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
747     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
748     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
749
750     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
751     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
752     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
753     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
754     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
755     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
756     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
757     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
758
759     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
760     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
761   } else {
762     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
763     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
764   }
765
766   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
767   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
768   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
769   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
770   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
771
772   setOperationAction(ISD::TRAP, MVT::Other, Legal);
773
774   // Use the default implementation.
775   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
776   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
777   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
778   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
779   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
780   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
781
782   if (!Subtarget->isTargetMachO()) {
783     // Non-MachO platforms may return values in these registers via the
784     // personality function.
785     setExceptionPointerRegister(ARM::R0);
786     setExceptionSelectorRegister(ARM::R1);
787   }
788
789   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
790     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
791   else
792     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
793
794   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
795   // the default expansion. If we are targeting a single threaded system,
796   // then set them all for expand so we can lower them later into their
797   // non-atomic form.
798   if (TM.Options.ThreadModel == ThreadModel::Single)
799     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
800   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
801     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
802     // to ldrex/strex loops already.
803     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
804
805     // On v8, we have particularly efficient implementations of atomic fences
806     // if they can be combined with nearby atomic loads and stores.
807     if (!Subtarget->hasV8Ops()) {
808       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
809       setInsertFencesForAtomic(true);
810     }
811   } else {
812     // If there's anything we can use as a barrier, go through custom lowering
813     // for ATOMIC_FENCE.
814     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
815                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
816
817     // Set them all for expansion, which will force libcalls.
818     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
819     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
820     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
821     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
822     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
823     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
824     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
825     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
826     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
827     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
828     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
829     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
830     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
831     // Unordered/Monotonic case.
832     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
833     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
834   }
835
836   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
837
838   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
839   if (!Subtarget->hasV6Ops()) {
840     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
841     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
842   }
843   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
844
845   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
846       !Subtarget->isThumb1Only()) {
847     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
848     // iff target supports vfp2.
849     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
850     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
851   }
852
853   // We want to custom lower some of our intrinsics.
854   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
855   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
856   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
857   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
858   if (Subtarget->isTargetDarwin())
859     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
860
861   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
862   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
863   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
864   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
865   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
866   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
867   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
868   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
869   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
870
871   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
872   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
873   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
874   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
875   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
876
877   // We don't support sin/cos/fmod/copysign/pow
878   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
879   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
880   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
881   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
882   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
883   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
884   setOperationAction(ISD::FREM,      MVT::f64, Expand);
885   setOperationAction(ISD::FREM,      MVT::f32, Expand);
886   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
887       !Subtarget->isThumb1Only()) {
888     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
889     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
890   }
891   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
892   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
893
894   if (!Subtarget->hasVFP4()) {
895     setOperationAction(ISD::FMA, MVT::f64, Expand);
896     setOperationAction(ISD::FMA, MVT::f32, Expand);
897   }
898
899   // Various VFP goodness
900   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
901     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
902     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
903       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
904       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
905     }
906
907     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
908     if (!Subtarget->hasFP16()) {
909       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
910       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
911     }
912   }
913
914   // Combine sin / cos into one node or libcall if possible.
915   if (Subtarget->hasSinCos()) {
916     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
917     setLibcallName(RTLIB::SINCOS_F64, "sincos");
918     if (Subtarget->getTargetTriple().isiOS()) {
919       // For iOS, we don't want to the normal expansion of a libcall to
920       // sincos. We want to issue a libcall to __sincos_stret.
921       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
922       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
923     }
924   }
925
926   // FP-ARMv8 implements a lot of rounding-like FP operations.
927   if (Subtarget->hasFPARMv8()) {
928     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
929     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
930     setOperationAction(ISD::FROUND, MVT::f32, Legal);
931     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
932     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
933     setOperationAction(ISD::FRINT, MVT::f32, Legal);
934     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
935     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
936     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
937     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
938     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
939     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
940
941     if (!Subtarget->isFPOnlySP()) {
942       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
943       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
944       setOperationAction(ISD::FROUND, MVT::f64, Legal);
945       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
946       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
947       setOperationAction(ISD::FRINT, MVT::f64, Legal);
948       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
949       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
950     }
951   }
952
953   if (Subtarget->hasVFP3()) {
954     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
955     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
956   }
957   if (Subtarget->hasNEON()) {
958     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
959     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
960     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
961     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
962   }
963
964   // We have target-specific dag combine patterns for the following nodes:
965   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
966   setTargetDAGCombine(ISD::ADD);
967   setTargetDAGCombine(ISD::SUB);
968   setTargetDAGCombine(ISD::MUL);
969   setTargetDAGCombine(ISD::AND);
970   setTargetDAGCombine(ISD::OR);
971   setTargetDAGCombine(ISD::XOR);
972
973   if (Subtarget->hasV6Ops())
974     setTargetDAGCombine(ISD::SRL);
975
976   setStackPointerRegisterToSaveRestore(ARM::SP);
977
978   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
979       !Subtarget->hasVFP2())
980     setSchedulingPreference(Sched::RegPressure);
981   else
982     setSchedulingPreference(Sched::Hybrid);
983
984   //// temporary - rewrite interface to use type
985   MaxStoresPerMemset = 8;
986   MaxStoresPerMemsetOptSize = 4;
987   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
988   MaxStoresPerMemcpyOptSize = 2;
989   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
990   MaxStoresPerMemmoveOptSize = 2;
991
992   // On ARM arguments smaller than 4 bytes are extended, so all arguments
993   // are at least 4 bytes aligned.
994   setMinStackArgumentAlignment(4);
995
996   // Prefer likely predicted branches to selects on out-of-order cores.
997   PredictableSelectIsExpensive = Subtarget->isLikeA9();
998
999   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1000 }
1001
1002 bool ARMTargetLowering::useSoftFloat() const {
1003   return Subtarget->useSoftFloat();
1004 }
1005
1006 // FIXME: It might make sense to define the representative register class as the
1007 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1008 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1009 // SPR's representative would be DPR_VFP2. This should work well if register
1010 // pressure tracking were modified such that a register use would increment the
1011 // pressure of the register class's representative and all of it's super
1012 // classes' representatives transitively. We have not implemented this because
1013 // of the difficulty prior to coalescing of modeling operand register classes
1014 // due to the common occurrence of cross class copies and subregister insertions
1015 // and extractions.
1016 std::pair<const TargetRegisterClass *, uint8_t>
1017 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1018                                            MVT VT) const {
1019   const TargetRegisterClass *RRC = nullptr;
1020   uint8_t Cost = 1;
1021   switch (VT.SimpleTy) {
1022   default:
1023     return TargetLowering::findRepresentativeClass(TRI, VT);
1024   // Use DPR as representative register class for all floating point
1025   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1026   // the cost is 1 for both f32 and f64.
1027   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1028   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1029     RRC = &ARM::DPRRegClass;
1030     // When NEON is used for SP, only half of the register file is available
1031     // because operations that define both SP and DP results will be constrained
1032     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1033     // coalescing by double-counting the SP regs. See the FIXME above.
1034     if (Subtarget->useNEONForSinglePrecisionFP())
1035       Cost = 2;
1036     break;
1037   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1038   case MVT::v4f32: case MVT::v2f64:
1039     RRC = &ARM::DPRRegClass;
1040     Cost = 2;
1041     break;
1042   case MVT::v4i64:
1043     RRC = &ARM::DPRRegClass;
1044     Cost = 4;
1045     break;
1046   case MVT::v8i64:
1047     RRC = &ARM::DPRRegClass;
1048     Cost = 8;
1049     break;
1050   }
1051   return std::make_pair(RRC, Cost);
1052 }
1053
1054 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1055   switch ((ARMISD::NodeType)Opcode) {
1056   case ARMISD::FIRST_NUMBER:  break;
1057   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1058   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1059   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1060   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1061   case ARMISD::CALL:          return "ARMISD::CALL";
1062   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1063   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1064   case ARMISD::tCALL:         return "ARMISD::tCALL";
1065   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1066   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1067   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1068   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1069   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1070   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1071   case ARMISD::CMP:           return "ARMISD::CMP";
1072   case ARMISD::CMN:           return "ARMISD::CMN";
1073   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1074   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1075   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1076   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1077   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1078
1079   case ARMISD::CMOV:          return "ARMISD::CMOV";
1080
1081   case ARMISD::RBIT:          return "ARMISD::RBIT";
1082
1083   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1084   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1085   case ARMISD::RRX:           return "ARMISD::RRX";
1086
1087   case ARMISD::ADDC:          return "ARMISD::ADDC";
1088   case ARMISD::ADDE:          return "ARMISD::ADDE";
1089   case ARMISD::SUBC:          return "ARMISD::SUBC";
1090   case ARMISD::SUBE:          return "ARMISD::SUBE";
1091
1092   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1093   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1094
1095   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1096   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1097   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1098
1099   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1100
1101   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1102
1103   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1104
1105   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1106
1107   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1108
1109   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1110
1111   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1112   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1113   case ARMISD::VCGE:          return "ARMISD::VCGE";
1114   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1115   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1116   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1117   case ARMISD::VCGT:          return "ARMISD::VCGT";
1118   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1119   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1120   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1121   case ARMISD::VTST:          return "ARMISD::VTST";
1122
1123   case ARMISD::VSHL:          return "ARMISD::VSHL";
1124   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1125   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1126   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1127   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1128   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1129   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1130   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1131   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1132   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1133   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1134   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1135   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1136   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1137   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1138   case ARMISD::VSLI:          return "ARMISD::VSLI";
1139   case ARMISD::VSRI:          return "ARMISD::VSRI";
1140   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1141   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1142   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1143   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1144   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1145   case ARMISD::VDUP:          return "ARMISD::VDUP";
1146   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1147   case ARMISD::VEXT:          return "ARMISD::VEXT";
1148   case ARMISD::VREV64:        return "ARMISD::VREV64";
1149   case ARMISD::VREV32:        return "ARMISD::VREV32";
1150   case ARMISD::VREV16:        return "ARMISD::VREV16";
1151   case ARMISD::VZIP:          return "ARMISD::VZIP";
1152   case ARMISD::VUZP:          return "ARMISD::VUZP";
1153   case ARMISD::VTRN:          return "ARMISD::VTRN";
1154   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1155   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1156   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1157   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1158   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1159   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1160   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1161   case ARMISD::BFI:           return "ARMISD::BFI";
1162   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1163   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1164   case ARMISD::VBSL:          return "ARMISD::VBSL";
1165   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1166   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1167   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1168   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1169   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1170   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1171   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1172   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1173   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1174   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1175   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1176   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1177   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1178   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1179   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1180   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1181   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1182   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1183   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1184   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1185   }
1186   return nullptr;
1187 }
1188
1189 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1190                                           EVT VT) const {
1191   if (!VT.isVector())
1192     return getPointerTy(DL);
1193   return VT.changeVectorElementTypeToInteger();
1194 }
1195
1196 /// getRegClassFor - Return the register class that should be used for the
1197 /// specified value type.
1198 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1199   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1200   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1201   // load / store 4 to 8 consecutive D registers.
1202   if (Subtarget->hasNEON()) {
1203     if (VT == MVT::v4i64)
1204       return &ARM::QQPRRegClass;
1205     if (VT == MVT::v8i64)
1206       return &ARM::QQQQPRRegClass;
1207   }
1208   return TargetLowering::getRegClassFor(VT);
1209 }
1210
1211 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1212 // source/dest is aligned and the copy size is large enough. We therefore want
1213 // to align such objects passed to memory intrinsics.
1214 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1215                                                unsigned &PrefAlign) const {
1216   if (!isa<MemIntrinsic>(CI))
1217     return false;
1218   MinSize = 8;
1219   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1220   // cycle faster than 4-byte aligned LDM.
1221   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1222   return true;
1223 }
1224
1225 // Create a fast isel object.
1226 FastISel *
1227 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1228                                   const TargetLibraryInfo *libInfo) const {
1229   return ARM::createFastISel(funcInfo, libInfo);
1230 }
1231
1232 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1233   unsigned NumVals = N->getNumValues();
1234   if (!NumVals)
1235     return Sched::RegPressure;
1236
1237   for (unsigned i = 0; i != NumVals; ++i) {
1238     EVT VT = N->getValueType(i);
1239     if (VT == MVT::Glue || VT == MVT::Other)
1240       continue;
1241     if (VT.isFloatingPoint() || VT.isVector())
1242       return Sched::ILP;
1243   }
1244
1245   if (!N->isMachineOpcode())
1246     return Sched::RegPressure;
1247
1248   // Load are scheduled for latency even if there instruction itinerary
1249   // is not available.
1250   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1251   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1252
1253   if (MCID.getNumDefs() == 0)
1254     return Sched::RegPressure;
1255   if (!Itins->isEmpty() &&
1256       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1257     return Sched::ILP;
1258
1259   return Sched::RegPressure;
1260 }
1261
1262 //===----------------------------------------------------------------------===//
1263 // Lowering Code
1264 //===----------------------------------------------------------------------===//
1265
1266 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1267 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1268   switch (CC) {
1269   default: llvm_unreachable("Unknown condition code!");
1270   case ISD::SETNE:  return ARMCC::NE;
1271   case ISD::SETEQ:  return ARMCC::EQ;
1272   case ISD::SETGT:  return ARMCC::GT;
1273   case ISD::SETGE:  return ARMCC::GE;
1274   case ISD::SETLT:  return ARMCC::LT;
1275   case ISD::SETLE:  return ARMCC::LE;
1276   case ISD::SETUGT: return ARMCC::HI;
1277   case ISD::SETUGE: return ARMCC::HS;
1278   case ISD::SETULT: return ARMCC::LO;
1279   case ISD::SETULE: return ARMCC::LS;
1280   }
1281 }
1282
1283 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1284 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1285                         ARMCC::CondCodes &CondCode2) {
1286   CondCode2 = ARMCC::AL;
1287   switch (CC) {
1288   default: llvm_unreachable("Unknown FP condition!");
1289   case ISD::SETEQ:
1290   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1291   case ISD::SETGT:
1292   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1293   case ISD::SETGE:
1294   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1295   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1296   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1297   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1298   case ISD::SETO:   CondCode = ARMCC::VC; break;
1299   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1300   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1301   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1302   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1303   case ISD::SETLT:
1304   case ISD::SETULT: CondCode = ARMCC::LT; break;
1305   case ISD::SETLE:
1306   case ISD::SETULE: CondCode = ARMCC::LE; break;
1307   case ISD::SETNE:
1308   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1309   }
1310 }
1311
1312 //===----------------------------------------------------------------------===//
1313 //                      Calling Convention Implementation
1314 //===----------------------------------------------------------------------===//
1315
1316 #include "ARMGenCallingConv.inc"
1317
1318 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1319 /// account presence of floating point hardware and calling convention
1320 /// limitations, such as support for variadic functions.
1321 CallingConv::ID
1322 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1323                                            bool isVarArg) const {
1324   switch (CC) {
1325   default:
1326     llvm_unreachable("Unsupported calling convention");
1327   case CallingConv::ARM_AAPCS:
1328   case CallingConv::ARM_APCS:
1329   case CallingConv::GHC:
1330     return CC;
1331   case CallingConv::ARM_AAPCS_VFP:
1332     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1333   case CallingConv::C:
1334     if (!Subtarget->isAAPCS_ABI())
1335       return CallingConv::ARM_APCS;
1336     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1337              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1338              !isVarArg)
1339       return CallingConv::ARM_AAPCS_VFP;
1340     else
1341       return CallingConv::ARM_AAPCS;
1342   case CallingConv::Fast:
1343     if (!Subtarget->isAAPCS_ABI()) {
1344       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1345         return CallingConv::Fast;
1346       return CallingConv::ARM_APCS;
1347     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1348       return CallingConv::ARM_AAPCS_VFP;
1349     else
1350       return CallingConv::ARM_AAPCS;
1351   }
1352 }
1353
1354 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1355 /// CallingConvention.
1356 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1357                                                  bool Return,
1358                                                  bool isVarArg) const {
1359   switch (getEffectiveCallingConv(CC, isVarArg)) {
1360   default:
1361     llvm_unreachable("Unsupported calling convention");
1362   case CallingConv::ARM_APCS:
1363     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1364   case CallingConv::ARM_AAPCS:
1365     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1366   case CallingConv::ARM_AAPCS_VFP:
1367     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1368   case CallingConv::Fast:
1369     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1370   case CallingConv::GHC:
1371     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1372   }
1373 }
1374
1375 /// LowerCallResult - Lower the result values of a call into the
1376 /// appropriate copies out of appropriate physical registers.
1377 SDValue
1378 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1379                                    CallingConv::ID CallConv, bool isVarArg,
1380                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1381                                    SDLoc dl, SelectionDAG &DAG,
1382                                    SmallVectorImpl<SDValue> &InVals,
1383                                    bool isThisReturn, SDValue ThisVal) const {
1384
1385   // Assign locations to each value returned by this call.
1386   SmallVector<CCValAssign, 16> RVLocs;
1387   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1388                     *DAG.getContext(), Call);
1389   CCInfo.AnalyzeCallResult(Ins,
1390                            CCAssignFnForNode(CallConv, /* Return*/ true,
1391                                              isVarArg));
1392
1393   // Copy all of the result registers out of their specified physreg.
1394   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1395     CCValAssign VA = RVLocs[i];
1396
1397     // Pass 'this' value directly from the argument to return value, to avoid
1398     // reg unit interference
1399     if (i == 0 && isThisReturn) {
1400       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1401              "unexpected return calling convention register assignment");
1402       InVals.push_back(ThisVal);
1403       continue;
1404     }
1405
1406     SDValue Val;
1407     if (VA.needsCustom()) {
1408       // Handle f64 or half of a v2f64.
1409       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1410                                       InFlag);
1411       Chain = Lo.getValue(1);
1412       InFlag = Lo.getValue(2);
1413       VA = RVLocs[++i]; // skip ahead to next loc
1414       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1415                                       InFlag);
1416       Chain = Hi.getValue(1);
1417       InFlag = Hi.getValue(2);
1418       if (!Subtarget->isLittle())
1419         std::swap (Lo, Hi);
1420       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1421
1422       if (VA.getLocVT() == MVT::v2f64) {
1423         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1424         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1425                           DAG.getConstant(0, dl, MVT::i32));
1426
1427         VA = RVLocs[++i]; // skip ahead to next loc
1428         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1429         Chain = Lo.getValue(1);
1430         InFlag = Lo.getValue(2);
1431         VA = RVLocs[++i]; // skip ahead to next loc
1432         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1433         Chain = Hi.getValue(1);
1434         InFlag = Hi.getValue(2);
1435         if (!Subtarget->isLittle())
1436           std::swap (Lo, Hi);
1437         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1438         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1439                           DAG.getConstant(1, dl, MVT::i32));
1440       }
1441     } else {
1442       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1443                                InFlag);
1444       Chain = Val.getValue(1);
1445       InFlag = Val.getValue(2);
1446     }
1447
1448     switch (VA.getLocInfo()) {
1449     default: llvm_unreachable("Unknown loc info!");
1450     case CCValAssign::Full: break;
1451     case CCValAssign::BCvt:
1452       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1453       break;
1454     }
1455
1456     InVals.push_back(Val);
1457   }
1458
1459   return Chain;
1460 }
1461
1462 /// LowerMemOpCallTo - Store the argument to the stack.
1463 SDValue
1464 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1465                                     SDValue StackPtr, SDValue Arg,
1466                                     SDLoc dl, SelectionDAG &DAG,
1467                                     const CCValAssign &VA,
1468                                     ISD::ArgFlagsTy Flags) const {
1469   unsigned LocMemOffset = VA.getLocMemOffset();
1470   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1471   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1472                        StackPtr, PtrOff);
1473   return DAG.getStore(
1474       Chain, dl, Arg, PtrOff,
1475       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1476       false, false, 0);
1477 }
1478
1479 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1480                                          SDValue Chain, SDValue &Arg,
1481                                          RegsToPassVector &RegsToPass,
1482                                          CCValAssign &VA, CCValAssign &NextVA,
1483                                          SDValue &StackPtr,
1484                                          SmallVectorImpl<SDValue> &MemOpChains,
1485                                          ISD::ArgFlagsTy Flags) const {
1486
1487   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1488                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1489   unsigned id = Subtarget->isLittle() ? 0 : 1;
1490   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1491
1492   if (NextVA.isRegLoc())
1493     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1494   else {
1495     assert(NextVA.isMemLoc());
1496     if (!StackPtr.getNode())
1497       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1498                                     getPointerTy(DAG.getDataLayout()));
1499
1500     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1501                                            dl, DAG, NextVA,
1502                                            Flags));
1503   }
1504 }
1505
1506 /// LowerCall - Lowering a call into a callseq_start <-
1507 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1508 /// nodes.
1509 SDValue
1510 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1511                              SmallVectorImpl<SDValue> &InVals) const {
1512   SelectionDAG &DAG                     = CLI.DAG;
1513   SDLoc &dl                             = CLI.DL;
1514   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1515   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1516   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1517   SDValue Chain                         = CLI.Chain;
1518   SDValue Callee                        = CLI.Callee;
1519   bool &isTailCall                      = CLI.IsTailCall;
1520   CallingConv::ID CallConv              = CLI.CallConv;
1521   bool doesNotRet                       = CLI.DoesNotReturn;
1522   bool isVarArg                         = CLI.IsVarArg;
1523
1524   MachineFunction &MF = DAG.getMachineFunction();
1525   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1526   bool isThisReturn   = false;
1527   bool isSibCall      = false;
1528   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1529
1530   // Disable tail calls if they're not supported.
1531   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1532     isTailCall = false;
1533
1534   if (isTailCall) {
1535     // Check if it's really possible to do a tail call.
1536     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1537                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1538                                                    Outs, OutVals, Ins, DAG);
1539     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1540       report_fatal_error("failed to perform tail call elimination on a call "
1541                          "site marked musttail");
1542     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1543     // detected sibcalls.
1544     if (isTailCall) {
1545       ++NumTailCalls;
1546       isSibCall = true;
1547     }
1548   }
1549
1550   // Analyze operands of the call, assigning locations to each operand.
1551   SmallVector<CCValAssign, 16> ArgLocs;
1552   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1553                     *DAG.getContext(), Call);
1554   CCInfo.AnalyzeCallOperands(Outs,
1555                              CCAssignFnForNode(CallConv, /* Return*/ false,
1556                                                isVarArg));
1557
1558   // Get a count of how many bytes are to be pushed on the stack.
1559   unsigned NumBytes = CCInfo.getNextStackOffset();
1560
1561   // For tail calls, memory operands are available in our caller's stack.
1562   if (isSibCall)
1563     NumBytes = 0;
1564
1565   // Adjust the stack pointer for the new arguments...
1566   // These operations are automatically eliminated by the prolog/epilog pass
1567   if (!isSibCall)
1568     Chain = DAG.getCALLSEQ_START(Chain,
1569                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1570
1571   SDValue StackPtr =
1572       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1573
1574   RegsToPassVector RegsToPass;
1575   SmallVector<SDValue, 8> MemOpChains;
1576
1577   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1578   // of tail call optimization, arguments are handled later.
1579   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1580        i != e;
1581        ++i, ++realArgIdx) {
1582     CCValAssign &VA = ArgLocs[i];
1583     SDValue Arg = OutVals[realArgIdx];
1584     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1585     bool isByVal = Flags.isByVal();
1586
1587     // Promote the value if needed.
1588     switch (VA.getLocInfo()) {
1589     default: llvm_unreachable("Unknown loc info!");
1590     case CCValAssign::Full: break;
1591     case CCValAssign::SExt:
1592       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1593       break;
1594     case CCValAssign::ZExt:
1595       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1596       break;
1597     case CCValAssign::AExt:
1598       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1599       break;
1600     case CCValAssign::BCvt:
1601       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1602       break;
1603     }
1604
1605     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1606     if (VA.needsCustom()) {
1607       if (VA.getLocVT() == MVT::v2f64) {
1608         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1609                                   DAG.getConstant(0, dl, MVT::i32));
1610         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1611                                   DAG.getConstant(1, dl, MVT::i32));
1612
1613         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1614                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1615
1616         VA = ArgLocs[++i]; // skip ahead to next loc
1617         if (VA.isRegLoc()) {
1618           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1619                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1620         } else {
1621           assert(VA.isMemLoc());
1622
1623           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1624                                                  dl, DAG, VA, Flags));
1625         }
1626       } else {
1627         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1628                          StackPtr, MemOpChains, Flags);
1629       }
1630     } else if (VA.isRegLoc()) {
1631       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1632         assert(VA.getLocVT() == MVT::i32 &&
1633                "unexpected calling convention register assignment");
1634         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1635                "unexpected use of 'returned'");
1636         isThisReturn = true;
1637       }
1638       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1639     } else if (isByVal) {
1640       assert(VA.isMemLoc());
1641       unsigned offset = 0;
1642
1643       // True if this byval aggregate will be split between registers
1644       // and memory.
1645       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1646       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1647
1648       if (CurByValIdx < ByValArgsCount) {
1649
1650         unsigned RegBegin, RegEnd;
1651         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1652
1653         EVT PtrVT =
1654             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1655         unsigned int i, j;
1656         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1657           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1658           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1659           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1660                                      MachinePointerInfo(),
1661                                      false, false, false,
1662                                      DAG.InferPtrAlignment(AddArg));
1663           MemOpChains.push_back(Load.getValue(1));
1664           RegsToPass.push_back(std::make_pair(j, Load));
1665         }
1666
1667         // If parameter size outsides register area, "offset" value
1668         // helps us to calculate stack slot for remained part properly.
1669         offset = RegEnd - RegBegin;
1670
1671         CCInfo.nextInRegsParam();
1672       }
1673
1674       if (Flags.getByValSize() > 4*offset) {
1675         auto PtrVT = getPointerTy(DAG.getDataLayout());
1676         unsigned LocMemOffset = VA.getLocMemOffset();
1677         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1678         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1679         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1680         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1681         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1682                                            MVT::i32);
1683         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1684                                             MVT::i32);
1685
1686         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1687         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1688         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1689                                           Ops));
1690       }
1691     } else if (!isSibCall) {
1692       assert(VA.isMemLoc());
1693
1694       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1695                                              dl, DAG, VA, Flags));
1696     }
1697   }
1698
1699   if (!MemOpChains.empty())
1700     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1701
1702   // Build a sequence of copy-to-reg nodes chained together with token chain
1703   // and flag operands which copy the outgoing args into the appropriate regs.
1704   SDValue InFlag;
1705   // Tail call byval lowering might overwrite argument registers so in case of
1706   // tail call optimization the copies to registers are lowered later.
1707   if (!isTailCall)
1708     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1709       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1710                                RegsToPass[i].second, InFlag);
1711       InFlag = Chain.getValue(1);
1712     }
1713
1714   // For tail calls lower the arguments to the 'real' stack slot.
1715   if (isTailCall) {
1716     // Force all the incoming stack arguments to be loaded from the stack
1717     // before any new outgoing arguments are stored to the stack, because the
1718     // outgoing stack slots may alias the incoming argument stack slots, and
1719     // the alias isn't otherwise explicit. This is slightly more conservative
1720     // than necessary, because it means that each store effectively depends
1721     // on every argument instead of just those arguments it would clobber.
1722
1723     // Do not flag preceding copytoreg stuff together with the following stuff.
1724     InFlag = SDValue();
1725     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1726       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1727                                RegsToPass[i].second, InFlag);
1728       InFlag = Chain.getValue(1);
1729     }
1730     InFlag = SDValue();
1731   }
1732
1733   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1734   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1735   // node so that legalize doesn't hack it.
1736   bool isDirect = false;
1737   bool isARMFunc = false;
1738   bool isLocalARMFunc = false;
1739   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1740   auto PtrVt = getPointerTy(DAG.getDataLayout());
1741
1742   if (Subtarget->genLongCalls()) {
1743     assert((Subtarget->isTargetWindows() ||
1744             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1745            "long-calls with non-static relocation model!");
1746     // Handle a global address or an external symbol. If it's not one of
1747     // those, the target's already in a register, so we don't need to do
1748     // anything extra.
1749     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1750       const GlobalValue *GV = G->getGlobal();
1751       // Create a constant pool entry for the callee address
1752       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1753       ARMConstantPoolValue *CPV =
1754         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1755
1756       // Get the address of the callee into a register
1757       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1758       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1759       Callee = DAG.getLoad(
1760           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1761           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1762           false, false, 0);
1763     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1764       const char *Sym = S->getSymbol();
1765
1766       // Create a constant pool entry for the callee address
1767       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1768       ARMConstantPoolValue *CPV =
1769         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1770                                       ARMPCLabelIndex, 0);
1771       // Get the address of the callee into a register
1772       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1773       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1774       Callee = DAG.getLoad(
1775           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1776           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1777           false, false, 0);
1778     }
1779   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1780     const GlobalValue *GV = G->getGlobal();
1781     isDirect = true;
1782     bool isDef = GV->isStrongDefinitionForLinker();
1783     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1784                    getTargetMachine().getRelocationModel() != Reloc::Static;
1785     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1786     // ARM call to a local ARM function is predicable.
1787     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1788     // tBX takes a register source operand.
1789     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1790       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1791       Callee = DAG.getNode(
1792           ARMISD::WrapperPIC, dl, PtrVt,
1793           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1794       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1795                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1796                            false, false, true, 0);
1797     } else if (Subtarget->isTargetCOFF()) {
1798       assert(Subtarget->isTargetWindows() &&
1799              "Windows is the only supported COFF target");
1800       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1801                                  ? ARMII::MO_DLLIMPORT
1802                                  : ARMII::MO_NO_FLAG;
1803       Callee =
1804           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1805       if (GV->hasDLLImportStorageClass())
1806         Callee =
1807             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1808                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1809                         MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1810                         false, false, false, 0);
1811     } else {
1812       // On ELF targets for PIC code, direct calls should go through the PLT
1813       unsigned OpFlags = 0;
1814       if (Subtarget->isTargetELF() &&
1815           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1816         OpFlags = ARMII::MO_PLT;
1817       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1818     }
1819   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1820     isDirect = true;
1821     bool isStub = Subtarget->isTargetMachO() &&
1822                   getTargetMachine().getRelocationModel() != Reloc::Static;
1823     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1824     // tBX takes a register source operand.
1825     const char *Sym = S->getSymbol();
1826     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1827       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1828       ARMConstantPoolValue *CPV =
1829         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1830                                       ARMPCLabelIndex, 4);
1831       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1832       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1833       Callee = DAG.getLoad(
1834           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1835           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1836           false, false, 0);
1837       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1838       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1839     } else {
1840       unsigned OpFlags = 0;
1841       // On ELF targets for PIC code, direct calls should go through the PLT
1842       if (Subtarget->isTargetELF() &&
1843                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1844         OpFlags = ARMII::MO_PLT;
1845       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1846     }
1847   }
1848
1849   // FIXME: handle tail calls differently.
1850   unsigned CallOpc;
1851   if (Subtarget->isThumb()) {
1852     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1853       CallOpc = ARMISD::CALL_NOLINK;
1854     else
1855       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1856   } else {
1857     if (!isDirect && !Subtarget->hasV5TOps())
1858       CallOpc = ARMISD::CALL_NOLINK;
1859     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1860              // Emit regular call when code size is the priority
1861              !MF.getFunction()->optForMinSize())
1862       // "mov lr, pc; b _foo" to avoid confusing the RSP
1863       CallOpc = ARMISD::CALL_NOLINK;
1864     else
1865       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1866   }
1867
1868   std::vector<SDValue> Ops;
1869   Ops.push_back(Chain);
1870   Ops.push_back(Callee);
1871
1872   // Add argument registers to the end of the list so that they are known live
1873   // into the call.
1874   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1875     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1876                                   RegsToPass[i].second.getValueType()));
1877
1878   // Add a register mask operand representing the call-preserved registers.
1879   if (!isTailCall) {
1880     const uint32_t *Mask;
1881     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1882     if (isThisReturn) {
1883       // For 'this' returns, use the R0-preserving mask if applicable
1884       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1885       if (!Mask) {
1886         // Set isThisReturn to false if the calling convention is not one that
1887         // allows 'returned' to be modeled in this way, so LowerCallResult does
1888         // not try to pass 'this' straight through
1889         isThisReturn = false;
1890         Mask = ARI->getCallPreservedMask(MF, CallConv);
1891       }
1892     } else
1893       Mask = ARI->getCallPreservedMask(MF, CallConv);
1894
1895     assert(Mask && "Missing call preserved mask for calling convention");
1896     Ops.push_back(DAG.getRegisterMask(Mask));
1897   }
1898
1899   if (InFlag.getNode())
1900     Ops.push_back(InFlag);
1901
1902   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1903   if (isTailCall) {
1904     MF.getFrameInfo()->setHasTailCall();
1905     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1906   }
1907
1908   // Returns a chain and a flag for retval copy to use.
1909   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1910   InFlag = Chain.getValue(1);
1911
1912   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1913                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1914   if (!Ins.empty())
1915     InFlag = Chain.getValue(1);
1916
1917   // Handle result values, copying them out of physregs into vregs that we
1918   // return.
1919   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1920                          InVals, isThisReturn,
1921                          isThisReturn ? OutVals[0] : SDValue());
1922 }
1923
1924 /// HandleByVal - Every parameter *after* a byval parameter is passed
1925 /// on the stack.  Remember the next parameter register to allocate,
1926 /// and then confiscate the rest of the parameter registers to insure
1927 /// this.
1928 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1929                                     unsigned Align) const {
1930   assert((State->getCallOrPrologue() == Prologue ||
1931           State->getCallOrPrologue() == Call) &&
1932          "unhandled ParmContext");
1933
1934   // Byval (as with any stack) slots are always at least 4 byte aligned.
1935   Align = std::max(Align, 4U);
1936
1937   unsigned Reg = State->AllocateReg(GPRArgRegs);
1938   if (!Reg)
1939     return;
1940
1941   unsigned AlignInRegs = Align / 4;
1942   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1943   for (unsigned i = 0; i < Waste; ++i)
1944     Reg = State->AllocateReg(GPRArgRegs);
1945
1946   if (!Reg)
1947     return;
1948
1949   unsigned Excess = 4 * (ARM::R4 - Reg);
1950
1951   // Special case when NSAA != SP and parameter size greater than size of
1952   // all remained GPR regs. In that case we can't split parameter, we must
1953   // send it to stack. We also must set NCRN to R4, so waste all
1954   // remained registers.
1955   const unsigned NSAAOffset = State->getNextStackOffset();
1956   if (NSAAOffset != 0 && Size > Excess) {
1957     while (State->AllocateReg(GPRArgRegs))
1958       ;
1959     return;
1960   }
1961
1962   // First register for byval parameter is the first register that wasn't
1963   // allocated before this method call, so it would be "reg".
1964   // If parameter is small enough to be saved in range [reg, r4), then
1965   // the end (first after last) register would be reg + param-size-in-regs,
1966   // else parameter would be splitted between registers and stack,
1967   // end register would be r4 in this case.
1968   unsigned ByValRegBegin = Reg;
1969   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1970   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1971   // Note, first register is allocated in the beginning of function already,
1972   // allocate remained amount of registers we need.
1973   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1974     State->AllocateReg(GPRArgRegs);
1975   // A byval parameter that is split between registers and memory needs its
1976   // size truncated here.
1977   // In the case where the entire structure fits in registers, we set the
1978   // size in memory to zero.
1979   Size = std::max<int>(Size - Excess, 0);
1980 }
1981
1982 /// MatchingStackOffset - Return true if the given stack call argument is
1983 /// already available in the same position (relatively) of the caller's
1984 /// incoming argument stack.
1985 static
1986 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1987                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1988                          const TargetInstrInfo *TII) {
1989   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1990   int FI = INT_MAX;
1991   if (Arg.getOpcode() == ISD::CopyFromReg) {
1992     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1993     if (!TargetRegisterInfo::isVirtualRegister(VR))
1994       return false;
1995     MachineInstr *Def = MRI->getVRegDef(VR);
1996     if (!Def)
1997       return false;
1998     if (!Flags.isByVal()) {
1999       if (!TII->isLoadFromStackSlot(Def, FI))
2000         return false;
2001     } else {
2002       return false;
2003     }
2004   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2005     if (Flags.isByVal())
2006       // ByVal argument is passed in as a pointer but it's now being
2007       // dereferenced. e.g.
2008       // define @foo(%struct.X* %A) {
2009       //   tail call @bar(%struct.X* byval %A)
2010       // }
2011       return false;
2012     SDValue Ptr = Ld->getBasePtr();
2013     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2014     if (!FINode)
2015       return false;
2016     FI = FINode->getIndex();
2017   } else
2018     return false;
2019
2020   assert(FI != INT_MAX);
2021   if (!MFI->isFixedObjectIndex(FI))
2022     return false;
2023   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2024 }
2025
2026 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2027 /// for tail call optimization. Targets which want to do tail call
2028 /// optimization should implement this function.
2029 bool
2030 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2031                                                      CallingConv::ID CalleeCC,
2032                                                      bool isVarArg,
2033                                                      bool isCalleeStructRet,
2034                                                      bool isCallerStructRet,
2035                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2036                                     const SmallVectorImpl<SDValue> &OutVals,
2037                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2038                                                      SelectionDAG& DAG) const {
2039   const Function *CallerF = DAG.getMachineFunction().getFunction();
2040   CallingConv::ID CallerCC = CallerF->getCallingConv();
2041   bool CCMatch = CallerCC == CalleeCC;
2042
2043   // Look for obvious safe cases to perform tail call optimization that do not
2044   // require ABI changes. This is what gcc calls sibcall.
2045
2046   // Do not sibcall optimize vararg calls unless the call site is not passing
2047   // any arguments.
2048   if (isVarArg && !Outs.empty())
2049     return false;
2050
2051   // Exception-handling functions need a special set of instructions to indicate
2052   // a return to the hardware. Tail-calling another function would probably
2053   // break this.
2054   if (CallerF->hasFnAttribute("interrupt"))
2055     return false;
2056
2057   // Also avoid sibcall optimization if either caller or callee uses struct
2058   // return semantics.
2059   if (isCalleeStructRet || isCallerStructRet)
2060     return false;
2061
2062   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2063   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2064   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2065   // support in the assembler and linker to be used. This would need to be
2066   // fixed to fully support tail calls in Thumb1.
2067   //
2068   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2069   // LR.  This means if we need to reload LR, it takes an extra instructions,
2070   // which outweighs the value of the tail call; but here we don't know yet
2071   // whether LR is going to be used.  Probably the right approach is to
2072   // generate the tail call here and turn it back into CALL/RET in
2073   // emitEpilogue if LR is used.
2074
2075   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2076   // but we need to make sure there are enough registers; the only valid
2077   // registers are the 4 used for parameters.  We don't currently do this
2078   // case.
2079   if (Subtarget->isThumb1Only())
2080     return false;
2081
2082   // Externally-defined functions with weak linkage should not be
2083   // tail-called on ARM when the OS does not support dynamic
2084   // pre-emption of symbols, as the AAELF spec requires normal calls
2085   // to undefined weak functions to be replaced with a NOP or jump to the
2086   // next instruction. The behaviour of branch instructions in this
2087   // situation (as used for tail calls) is implementation-defined, so we
2088   // cannot rely on the linker replacing the tail call with a return.
2089   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2090     const GlobalValue *GV = G->getGlobal();
2091     const Triple &TT = getTargetMachine().getTargetTriple();
2092     if (GV->hasExternalWeakLinkage() &&
2093         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2094       return false;
2095   }
2096
2097   // If the calling conventions do not match, then we'd better make sure the
2098   // results are returned in the same way as what the caller expects.
2099   if (!CCMatch) {
2100     SmallVector<CCValAssign, 16> RVLocs1;
2101     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2102                        *DAG.getContext(), Call);
2103     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2104
2105     SmallVector<CCValAssign, 16> RVLocs2;
2106     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2107                        *DAG.getContext(), Call);
2108     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2109
2110     if (RVLocs1.size() != RVLocs2.size())
2111       return false;
2112     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2113       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2114         return false;
2115       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2116         return false;
2117       if (RVLocs1[i].isRegLoc()) {
2118         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2119           return false;
2120       } else {
2121         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2122           return false;
2123       }
2124     }
2125   }
2126
2127   // If Caller's vararg or byval argument has been split between registers and
2128   // stack, do not perform tail call, since part of the argument is in caller's
2129   // local frame.
2130   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2131                                       getInfo<ARMFunctionInfo>();
2132   if (AFI_Caller->getArgRegsSaveSize())
2133     return false;
2134
2135   // If the callee takes no arguments then go on to check the results of the
2136   // call.
2137   if (!Outs.empty()) {
2138     // Check if stack adjustment is needed. For now, do not do this if any
2139     // argument is passed on the stack.
2140     SmallVector<CCValAssign, 16> ArgLocs;
2141     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2142                       *DAG.getContext(), Call);
2143     CCInfo.AnalyzeCallOperands(Outs,
2144                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2145     if (CCInfo.getNextStackOffset()) {
2146       MachineFunction &MF = DAG.getMachineFunction();
2147
2148       // Check if the arguments are already laid out in the right way as
2149       // the caller's fixed stack objects.
2150       MachineFrameInfo *MFI = MF.getFrameInfo();
2151       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2152       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2153       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2154            i != e;
2155            ++i, ++realArgIdx) {
2156         CCValAssign &VA = ArgLocs[i];
2157         EVT RegVT = VA.getLocVT();
2158         SDValue Arg = OutVals[realArgIdx];
2159         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2160         if (VA.getLocInfo() == CCValAssign::Indirect)
2161           return false;
2162         if (VA.needsCustom()) {
2163           // f64 and vector types are split into multiple registers or
2164           // register/stack-slot combinations.  The types will not match
2165           // the registers; give up on memory f64 refs until we figure
2166           // out what to do about this.
2167           if (!VA.isRegLoc())
2168             return false;
2169           if (!ArgLocs[++i].isRegLoc())
2170             return false;
2171           if (RegVT == MVT::v2f64) {
2172             if (!ArgLocs[++i].isRegLoc())
2173               return false;
2174             if (!ArgLocs[++i].isRegLoc())
2175               return false;
2176           }
2177         } else if (!VA.isRegLoc()) {
2178           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2179                                    MFI, MRI, TII))
2180             return false;
2181         }
2182       }
2183     }
2184   }
2185
2186   return true;
2187 }
2188
2189 bool
2190 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2191                                   MachineFunction &MF, bool isVarArg,
2192                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2193                                   LLVMContext &Context) const {
2194   SmallVector<CCValAssign, 16> RVLocs;
2195   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2196   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2197                                                     isVarArg));
2198 }
2199
2200 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2201                                     SDLoc DL, SelectionDAG &DAG) {
2202   const MachineFunction &MF = DAG.getMachineFunction();
2203   const Function *F = MF.getFunction();
2204
2205   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2206
2207   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2208   // version of the "preferred return address". These offsets affect the return
2209   // instruction if this is a return from PL1 without hypervisor extensions.
2210   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2211   //    SWI:     0      "subs pc, lr, #0"
2212   //    ABORT:   +4     "subs pc, lr, #4"
2213   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2214   // UNDEF varies depending on where the exception came from ARM or Thumb
2215   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2216
2217   int64_t LROffset;
2218   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2219       IntKind == "ABORT")
2220     LROffset = 4;
2221   else if (IntKind == "SWI" || IntKind == "UNDEF")
2222     LROffset = 0;
2223   else
2224     report_fatal_error("Unsupported interrupt attribute. If present, value "
2225                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2226
2227   RetOps.insert(RetOps.begin() + 1,
2228                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2229
2230   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2231 }
2232
2233 SDValue
2234 ARMTargetLowering::LowerReturn(SDValue Chain,
2235                                CallingConv::ID CallConv, bool isVarArg,
2236                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2237                                const SmallVectorImpl<SDValue> &OutVals,
2238                                SDLoc dl, SelectionDAG &DAG) const {
2239
2240   // CCValAssign - represent the assignment of the return value to a location.
2241   SmallVector<CCValAssign, 16> RVLocs;
2242
2243   // CCState - Info about the registers and stack slots.
2244   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2245                     *DAG.getContext(), Call);
2246
2247   // Analyze outgoing return values.
2248   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2249                                                isVarArg));
2250
2251   SDValue Flag;
2252   SmallVector<SDValue, 4> RetOps;
2253   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2254   bool isLittleEndian = Subtarget->isLittle();
2255
2256   MachineFunction &MF = DAG.getMachineFunction();
2257   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2258   AFI->setReturnRegsCount(RVLocs.size());
2259
2260   // Copy the result values into the output registers.
2261   for (unsigned i = 0, realRVLocIdx = 0;
2262        i != RVLocs.size();
2263        ++i, ++realRVLocIdx) {
2264     CCValAssign &VA = RVLocs[i];
2265     assert(VA.isRegLoc() && "Can only return in registers!");
2266
2267     SDValue Arg = OutVals[realRVLocIdx];
2268
2269     switch (VA.getLocInfo()) {
2270     default: llvm_unreachable("Unknown loc info!");
2271     case CCValAssign::Full: break;
2272     case CCValAssign::BCvt:
2273       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2274       break;
2275     }
2276
2277     if (VA.needsCustom()) {
2278       if (VA.getLocVT() == MVT::v2f64) {
2279         // Extract the first half and return it in two registers.
2280         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2281                                    DAG.getConstant(0, dl, MVT::i32));
2282         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2283                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2284
2285         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2286                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2287                                  Flag);
2288         Flag = Chain.getValue(1);
2289         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2290         VA = RVLocs[++i]; // skip ahead to next loc
2291         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2292                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2293                                  Flag);
2294         Flag = Chain.getValue(1);
2295         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2296         VA = RVLocs[++i]; // skip ahead to next loc
2297
2298         // Extract the 2nd half and fall through to handle it as an f64 value.
2299         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2300                           DAG.getConstant(1, dl, MVT::i32));
2301       }
2302       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2303       // available.
2304       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2305                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2306       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2307                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2308                                Flag);
2309       Flag = Chain.getValue(1);
2310       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2311       VA = RVLocs[++i]; // skip ahead to next loc
2312       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2313                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2314                                Flag);
2315     } else
2316       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2317
2318     // Guarantee that all emitted copies are
2319     // stuck together, avoiding something bad.
2320     Flag = Chain.getValue(1);
2321     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2322   }
2323
2324   // Update chain and glue.
2325   RetOps[0] = Chain;
2326   if (Flag.getNode())
2327     RetOps.push_back(Flag);
2328
2329   // CPUs which aren't M-class use a special sequence to return from
2330   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2331   // though we use "subs pc, lr, #N").
2332   //
2333   // M-class CPUs actually use a normal return sequence with a special
2334   // (hardware-provided) value in LR, so the normal code path works.
2335   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2336       !Subtarget->isMClass()) {
2337     if (Subtarget->isThumb1Only())
2338       report_fatal_error("interrupt attribute is not supported in Thumb1");
2339     return LowerInterruptReturn(RetOps, dl, DAG);
2340   }
2341
2342   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2343 }
2344
2345 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2346   if (N->getNumValues() != 1)
2347     return false;
2348   if (!N->hasNUsesOfValue(1, 0))
2349     return false;
2350
2351   SDValue TCChain = Chain;
2352   SDNode *Copy = *N->use_begin();
2353   if (Copy->getOpcode() == ISD::CopyToReg) {
2354     // If the copy has a glue operand, we conservatively assume it isn't safe to
2355     // perform a tail call.
2356     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2357       return false;
2358     TCChain = Copy->getOperand(0);
2359   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2360     SDNode *VMov = Copy;
2361     // f64 returned in a pair of GPRs.
2362     SmallPtrSet<SDNode*, 2> Copies;
2363     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2364          UI != UE; ++UI) {
2365       if (UI->getOpcode() != ISD::CopyToReg)
2366         return false;
2367       Copies.insert(*UI);
2368     }
2369     if (Copies.size() > 2)
2370       return false;
2371
2372     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2373          UI != UE; ++UI) {
2374       SDValue UseChain = UI->getOperand(0);
2375       if (Copies.count(UseChain.getNode()))
2376         // Second CopyToReg
2377         Copy = *UI;
2378       else {
2379         // We are at the top of this chain.
2380         // If the copy has a glue operand, we conservatively assume it
2381         // isn't safe to perform a tail call.
2382         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2383           return false;
2384         // First CopyToReg
2385         TCChain = UseChain;
2386       }
2387     }
2388   } else if (Copy->getOpcode() == ISD::BITCAST) {
2389     // f32 returned in a single GPR.
2390     if (!Copy->hasOneUse())
2391       return false;
2392     Copy = *Copy->use_begin();
2393     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2394       return false;
2395     // If the copy has a glue operand, we conservatively assume it isn't safe to
2396     // perform a tail call.
2397     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2398       return false;
2399     TCChain = Copy->getOperand(0);
2400   } else {
2401     return false;
2402   }
2403
2404   bool HasRet = false;
2405   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2406        UI != UE; ++UI) {
2407     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2408         UI->getOpcode() != ARMISD::INTRET_FLAG)
2409       return false;
2410     HasRet = true;
2411   }
2412
2413   if (!HasRet)
2414     return false;
2415
2416   Chain = TCChain;
2417   return true;
2418 }
2419
2420 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2421   if (!Subtarget->supportsTailCall())
2422     return false;
2423
2424   auto Attr =
2425       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2426   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2427     return false;
2428
2429   return !Subtarget->isThumb1Only();
2430 }
2431
2432 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2433 // and pass the lower and high parts through.
2434 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2435   SDLoc DL(Op);
2436   SDValue WriteValue = Op->getOperand(2);
2437
2438   // This function is only supposed to be called for i64 type argument.
2439   assert(WriteValue.getValueType() == MVT::i64
2440           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2441
2442   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2443                            DAG.getConstant(0, DL, MVT::i32));
2444   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2445                            DAG.getConstant(1, DL, MVT::i32));
2446   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2447   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2448 }
2449
2450 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2451 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2452 // one of the above mentioned nodes. It has to be wrapped because otherwise
2453 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2454 // be used to form addressing mode. These wrapped nodes will be selected
2455 // into MOVi.
2456 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2457   EVT PtrVT = Op.getValueType();
2458   // FIXME there is no actual debug info here
2459   SDLoc dl(Op);
2460   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2461   SDValue Res;
2462   if (CP->isMachineConstantPoolEntry())
2463     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2464                                     CP->getAlignment());
2465   else
2466     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2467                                     CP->getAlignment());
2468   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2469 }
2470
2471 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2472   return MachineJumpTableInfo::EK_Inline;
2473 }
2474
2475 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2476                                              SelectionDAG &DAG) const {
2477   MachineFunction &MF = DAG.getMachineFunction();
2478   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2479   unsigned ARMPCLabelIndex = 0;
2480   SDLoc DL(Op);
2481   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2482   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2483   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2484   SDValue CPAddr;
2485   if (RelocM == Reloc::Static) {
2486     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2487   } else {
2488     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2489     ARMPCLabelIndex = AFI->createPICLabelUId();
2490     ARMConstantPoolValue *CPV =
2491       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2492                                       ARMCP::CPBlockAddress, PCAdj);
2493     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2494   }
2495   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2496   SDValue Result =
2497       DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2498                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2499                   false, false, false, 0);
2500   if (RelocM == Reloc::Static)
2501     return Result;
2502   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2503   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2504 }
2505
2506 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2507 SDValue
2508 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2509                                                  SelectionDAG &DAG) const {
2510   SDLoc dl(GA);
2511   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2512   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2513   MachineFunction &MF = DAG.getMachineFunction();
2514   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2515   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2516   ARMConstantPoolValue *CPV =
2517     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2518                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2519   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2520   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2521   Argument =
2522       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2523                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2524                   false, false, false, 0);
2525   SDValue Chain = Argument.getValue(1);
2526
2527   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2528   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2529
2530   // call __tls_get_addr.
2531   ArgListTy Args;
2532   ArgListEntry Entry;
2533   Entry.Node = Argument;
2534   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2535   Args.push_back(Entry);
2536
2537   // FIXME: is there useful debug info available here?
2538   TargetLowering::CallLoweringInfo CLI(DAG);
2539   CLI.setDebugLoc(dl).setChain(Chain)
2540     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2541                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2542                0);
2543
2544   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2545   return CallResult.first;
2546 }
2547
2548 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2549 // "local exec" model.
2550 SDValue
2551 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2552                                         SelectionDAG &DAG,
2553                                         TLSModel::Model model) const {
2554   const GlobalValue *GV = GA->getGlobal();
2555   SDLoc dl(GA);
2556   SDValue Offset;
2557   SDValue Chain = DAG.getEntryNode();
2558   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2559   // Get the Thread Pointer
2560   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2561
2562   if (model == TLSModel::InitialExec) {
2563     MachineFunction &MF = DAG.getMachineFunction();
2564     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2565     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2566     // Initial exec model.
2567     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2568     ARMConstantPoolValue *CPV =
2569       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2570                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2571                                       true);
2572     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2573     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2574     Offset = DAG.getLoad(
2575         PtrVT, dl, Chain, Offset,
2576         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2577         false, false, 0);
2578     Chain = Offset.getValue(1);
2579
2580     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2581     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2582
2583     Offset = DAG.getLoad(
2584         PtrVT, dl, Chain, Offset,
2585         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2586         false, false, 0);
2587   } else {
2588     // local exec model
2589     assert(model == TLSModel::LocalExec);
2590     ARMConstantPoolValue *CPV =
2591       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2592     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2593     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2594     Offset = DAG.getLoad(
2595         PtrVT, dl, Chain, Offset,
2596         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2597         false, false, 0);
2598   }
2599
2600   // The address of the thread local variable is the add of the thread
2601   // pointer with the offset of the variable.
2602   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2603 }
2604
2605 SDValue
2606 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2607   // TODO: implement the "local dynamic" model
2608   assert(Subtarget->isTargetELF() &&
2609          "TLS not implemented for non-ELF targets");
2610   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2611   if (DAG.getTarget().Options.EmulatedTLS)
2612     return LowerToTLSEmulatedModel(GA, DAG);
2613
2614   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2615
2616   switch (model) {
2617     case TLSModel::GeneralDynamic:
2618     case TLSModel::LocalDynamic:
2619       return LowerToTLSGeneralDynamicModel(GA, DAG);
2620     case TLSModel::InitialExec:
2621     case TLSModel::LocalExec:
2622       return LowerToTLSExecModels(GA, DAG, model);
2623   }
2624   llvm_unreachable("bogus TLS model");
2625 }
2626
2627 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2628                                                  SelectionDAG &DAG) const {
2629   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2630   SDLoc dl(Op);
2631   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2632   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2633     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2634     ARMConstantPoolValue *CPV =
2635       ARMConstantPoolConstant::Create(GV,
2636                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2637     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2638     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2639     SDValue Result = DAG.getLoad(
2640         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2641         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2642         false, false, 0);
2643     SDValue Chain = Result.getValue(1);
2644     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2645     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2646     if (!UseGOTOFF)
2647       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2648                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2649                            false, false, false, 0);
2650     return Result;
2651   }
2652
2653   // If we have T2 ops, we can materialize the address directly via movt/movw
2654   // pair. This is always cheaper.
2655   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2656     ++NumMovwMovt;
2657     // FIXME: Once remat is capable of dealing with instructions with register
2658     // operands, expand this into two nodes.
2659     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2660                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2661   } else {
2662     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2663     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2664     return DAG.getLoad(
2665         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2666         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2667         false, false, 0);
2668   }
2669 }
2670
2671 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2672                                                     SelectionDAG &DAG) const {
2673   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2674   SDLoc dl(Op);
2675   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2676   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2677
2678   if (Subtarget->useMovt(DAG.getMachineFunction()))
2679     ++NumMovwMovt;
2680
2681   // FIXME: Once remat is capable of dealing with instructions with register
2682   // operands, expand this into multiple nodes
2683   unsigned Wrapper =
2684       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2685
2686   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2687   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2688
2689   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2690     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2691                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2692                          false, false, false, 0);
2693   return Result;
2694 }
2695
2696 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2697                                                      SelectionDAG &DAG) const {
2698   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2699   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2700          "Windows on ARM expects to use movw/movt");
2701
2702   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2703   const ARMII::TOF TargetFlags =
2704     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2705   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2706   SDValue Result;
2707   SDLoc DL(Op);
2708
2709   ++NumMovwMovt;
2710
2711   // FIXME: Once remat is capable of dealing with instructions with register
2712   // operands, expand this into two nodes.
2713   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2714                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2715                                                   TargetFlags));
2716   if (GV->hasDLLImportStorageClass())
2717     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2718                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2719                          false, false, false, 0);
2720   return Result;
2721 }
2722
2723 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2724                                                     SelectionDAG &DAG) const {
2725   assert(Subtarget->isTargetELF() &&
2726          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2727   MachineFunction &MF = DAG.getMachineFunction();
2728   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2729   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2730   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2731   SDLoc dl(Op);
2732   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2733   ARMConstantPoolValue *CPV =
2734     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2735                                   ARMPCLabelIndex, PCAdj);
2736   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2737   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2738   SDValue Result =
2739       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2740                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2741                   false, false, false, 0);
2742   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2743   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2744 }
2745
2746 SDValue
2747 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2748   SDLoc dl(Op);
2749   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2750   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2751                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2752                      Op.getOperand(1), Val);
2753 }
2754
2755 SDValue
2756 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2757   SDLoc dl(Op);
2758   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2759                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2760 }
2761
2762 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2763                                                       SelectionDAG &DAG) const {
2764   SDLoc dl(Op);
2765   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2766                      Op.getOperand(0));
2767 }
2768
2769 SDValue
2770 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2771                                           const ARMSubtarget *Subtarget) const {
2772   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2773   SDLoc dl(Op);
2774   switch (IntNo) {
2775   default: return SDValue();    // Don't custom lower most intrinsics.
2776   case Intrinsic::arm_rbit: {
2777     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2778            "RBIT intrinsic must have i32 type!");
2779     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2780   }
2781   case Intrinsic::arm_thread_pointer: {
2782     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2783     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2784   }
2785   case Intrinsic::eh_sjlj_lsda: {
2786     MachineFunction &MF = DAG.getMachineFunction();
2787     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2788     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2789     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2790     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2791     SDValue CPAddr;
2792     unsigned PCAdj = (RelocM != Reloc::PIC_)
2793       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2794     ARMConstantPoolValue *CPV =
2795       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2796                                       ARMCP::CPLSDA, PCAdj);
2797     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2798     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2799     SDValue Result = DAG.getLoad(
2800         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2801         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2802         false, false, 0);
2803
2804     if (RelocM == Reloc::PIC_) {
2805       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2806       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2807     }
2808     return Result;
2809   }
2810   case Intrinsic::arm_neon_vmulls:
2811   case Intrinsic::arm_neon_vmullu: {
2812     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2813       ? ARMISD::VMULLs : ARMISD::VMULLu;
2814     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2815                        Op.getOperand(1), Op.getOperand(2));
2816   }
2817   case Intrinsic::arm_neon_vminnm:
2818   case Intrinsic::arm_neon_vmaxnm: {
2819     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2820       ? ISD::FMINNUM : ISD::FMAXNUM;
2821     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2822                        Op.getOperand(1), Op.getOperand(2));
2823   }
2824   case Intrinsic::arm_neon_vmins:
2825   case Intrinsic::arm_neon_vmaxs: {
2826     // v{min,max}s is overloaded between signed integers and floats.
2827     if (!Op.getValueType().isFloatingPoint())
2828       return SDValue();
2829     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2830       ? ISD::FMINNAN : ISD::FMAXNAN;
2831     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2832                        Op.getOperand(1), Op.getOperand(2));
2833   }
2834   }
2835 }
2836
2837 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2838                                  const ARMSubtarget *Subtarget) {
2839   // FIXME: handle "fence singlethread" more efficiently.
2840   SDLoc dl(Op);
2841   if (!Subtarget->hasDataBarrier()) {
2842     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2843     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2844     // here.
2845     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2846            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2847     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2848                        DAG.getConstant(0, dl, MVT::i32));
2849   }
2850
2851   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2852   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2853   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2854   if (Subtarget->isMClass()) {
2855     // Only a full system barrier exists in the M-class architectures.
2856     Domain = ARM_MB::SY;
2857   } else if (Subtarget->isSwift() && Ord == Release) {
2858     // Swift happens to implement ISHST barriers in a way that's compatible with
2859     // Release semantics but weaker than ISH so we'd be fools not to use
2860     // it. Beware: other processors probably don't!
2861     Domain = ARM_MB::ISHST;
2862   }
2863
2864   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2865                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2866                      DAG.getConstant(Domain, dl, MVT::i32));
2867 }
2868
2869 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2870                              const ARMSubtarget *Subtarget) {
2871   // ARM pre v5TE and Thumb1 does not have preload instructions.
2872   if (!(Subtarget->isThumb2() ||
2873         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2874     // Just preserve the chain.
2875     return Op.getOperand(0);
2876
2877   SDLoc dl(Op);
2878   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2879   if (!isRead &&
2880       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2881     // ARMv7 with MP extension has PLDW.
2882     return Op.getOperand(0);
2883
2884   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2885   if (Subtarget->isThumb()) {
2886     // Invert the bits.
2887     isRead = ~isRead & 1;
2888     isData = ~isData & 1;
2889   }
2890
2891   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2892                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2893                      DAG.getConstant(isData, dl, MVT::i32));
2894 }
2895
2896 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2897   MachineFunction &MF = DAG.getMachineFunction();
2898   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2899
2900   // vastart just stores the address of the VarArgsFrameIndex slot into the
2901   // memory location argument.
2902   SDLoc dl(Op);
2903   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2904   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2905   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2906   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2907                       MachinePointerInfo(SV), false, false, 0);
2908 }
2909
2910 SDValue
2911 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2912                                         SDValue &Root, SelectionDAG &DAG,
2913                                         SDLoc dl) const {
2914   MachineFunction &MF = DAG.getMachineFunction();
2915   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2916
2917   const TargetRegisterClass *RC;
2918   if (AFI->isThumb1OnlyFunction())
2919     RC = &ARM::tGPRRegClass;
2920   else
2921     RC = &ARM::GPRRegClass;
2922
2923   // Transform the arguments stored in physical registers into virtual ones.
2924   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2925   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2926
2927   SDValue ArgValue2;
2928   if (NextVA.isMemLoc()) {
2929     MachineFrameInfo *MFI = MF.getFrameInfo();
2930     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2931
2932     // Create load node to retrieve arguments from the stack.
2933     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2934     ArgValue2 = DAG.getLoad(
2935         MVT::i32, dl, Root, FIN,
2936         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2937         false, false, 0);
2938   } else {
2939     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2940     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2941   }
2942   if (!Subtarget->isLittle())
2943     std::swap (ArgValue, ArgValue2);
2944   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2945 }
2946
2947 // The remaining GPRs hold either the beginning of variable-argument
2948 // data, or the beginning of an aggregate passed by value (usually
2949 // byval).  Either way, we allocate stack slots adjacent to the data
2950 // provided by our caller, and store the unallocated registers there.
2951 // If this is a variadic function, the va_list pointer will begin with
2952 // these values; otherwise, this reassembles a (byval) structure that
2953 // was split between registers and memory.
2954 // Return: The frame index registers were stored into.
2955 int
2956 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2957                                   SDLoc dl, SDValue &Chain,
2958                                   const Value *OrigArg,
2959                                   unsigned InRegsParamRecordIdx,
2960                                   int ArgOffset,
2961                                   unsigned ArgSize) const {
2962   // Currently, two use-cases possible:
2963   // Case #1. Non-var-args function, and we meet first byval parameter.
2964   //          Setup first unallocated register as first byval register;
2965   //          eat all remained registers
2966   //          (these two actions are performed by HandleByVal method).
2967   //          Then, here, we initialize stack frame with
2968   //          "store-reg" instructions.
2969   // Case #2. Var-args function, that doesn't contain byval parameters.
2970   //          The same: eat all remained unallocated registers,
2971   //          initialize stack frame.
2972
2973   MachineFunction &MF = DAG.getMachineFunction();
2974   MachineFrameInfo *MFI = MF.getFrameInfo();
2975   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2976   unsigned RBegin, REnd;
2977   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2978     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2979   } else {
2980     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2981     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2982     REnd = ARM::R4;
2983   }
2984
2985   if (REnd != RBegin)
2986     ArgOffset = -4 * (ARM::R4 - RBegin);
2987
2988   auto PtrVT = getPointerTy(DAG.getDataLayout());
2989   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2990   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
2991
2992   SmallVector<SDValue, 4> MemOps;
2993   const TargetRegisterClass *RC =
2994       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2995
2996   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2997     unsigned VReg = MF.addLiveIn(Reg, RC);
2998     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2999     SDValue Store =
3000         DAG.getStore(Val.getValue(1), dl, Val, FIN,
3001                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3002     MemOps.push_back(Store);
3003     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3004   }
3005
3006   if (!MemOps.empty())
3007     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3008   return FrameIndex;
3009 }
3010
3011 // Setup stack frame, the va_list pointer will start from.
3012 void
3013 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3014                                         SDLoc dl, SDValue &Chain,
3015                                         unsigned ArgOffset,
3016                                         unsigned TotalArgRegsSaveSize,
3017                                         bool ForceMutable) const {
3018   MachineFunction &MF = DAG.getMachineFunction();
3019   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3020
3021   // Try to store any remaining integer argument regs
3022   // to their spots on the stack so that they may be loaded by deferencing
3023   // the result of va_next.
3024   // If there is no regs to be stored, just point address after last
3025   // argument passed via stack.
3026   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3027                                   CCInfo.getInRegsParamsCount(),
3028                                   CCInfo.getNextStackOffset(), 4);
3029   AFI->setVarArgsFrameIndex(FrameIndex);
3030 }
3031
3032 SDValue
3033 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3034                                         CallingConv::ID CallConv, bool isVarArg,
3035                                         const SmallVectorImpl<ISD::InputArg>
3036                                           &Ins,
3037                                         SDLoc dl, SelectionDAG &DAG,
3038                                         SmallVectorImpl<SDValue> &InVals)
3039                                           const {
3040   MachineFunction &MF = DAG.getMachineFunction();
3041   MachineFrameInfo *MFI = MF.getFrameInfo();
3042
3043   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3044
3045   // Assign locations to all of the incoming arguments.
3046   SmallVector<CCValAssign, 16> ArgLocs;
3047   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3048                     *DAG.getContext(), Prologue);
3049   CCInfo.AnalyzeFormalArguments(Ins,
3050                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3051                                                   isVarArg));
3052
3053   SmallVector<SDValue, 16> ArgValues;
3054   SDValue ArgValue;
3055   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3056   unsigned CurArgIdx = 0;
3057
3058   // Initially ArgRegsSaveSize is zero.
3059   // Then we increase this value each time we meet byval parameter.
3060   // We also increase this value in case of varargs function.
3061   AFI->setArgRegsSaveSize(0);
3062
3063   // Calculate the amount of stack space that we need to allocate to store
3064   // byval and variadic arguments that are passed in registers.
3065   // We need to know this before we allocate the first byval or variadic
3066   // argument, as they will be allocated a stack slot below the CFA (Canonical
3067   // Frame Address, the stack pointer at entry to the function).
3068   unsigned ArgRegBegin = ARM::R4;
3069   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3070     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3071       break;
3072
3073     CCValAssign &VA = ArgLocs[i];
3074     unsigned Index = VA.getValNo();
3075     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3076     if (!Flags.isByVal())
3077       continue;
3078
3079     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3080     unsigned RBegin, REnd;
3081     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3082     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3083
3084     CCInfo.nextInRegsParam();
3085   }
3086   CCInfo.rewindByValRegsInfo();
3087
3088   int lastInsIndex = -1;
3089   if (isVarArg && MFI->hasVAStart()) {
3090     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3091     if (RegIdx != array_lengthof(GPRArgRegs))
3092       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3093   }
3094
3095   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3096   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3097   auto PtrVT = getPointerTy(DAG.getDataLayout());
3098
3099   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3100     CCValAssign &VA = ArgLocs[i];
3101     if (Ins[VA.getValNo()].isOrigArg()) {
3102       std::advance(CurOrigArg,
3103                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3104       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3105     }
3106     // Arguments stored in registers.
3107     if (VA.isRegLoc()) {
3108       EVT RegVT = VA.getLocVT();
3109
3110       if (VA.needsCustom()) {
3111         // f64 and vector types are split up into multiple registers or
3112         // combinations of registers and stack slots.
3113         if (VA.getLocVT() == MVT::v2f64) {
3114           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3115                                                    Chain, DAG, dl);
3116           VA = ArgLocs[++i]; // skip ahead to next loc
3117           SDValue ArgValue2;
3118           if (VA.isMemLoc()) {
3119             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3120             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3121             ArgValue2 = DAG.getLoad(
3122                 MVT::f64, dl, Chain, FIN,
3123                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3124                 false, false, false, 0);
3125           } else {
3126             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3127                                              Chain, DAG, dl);
3128           }
3129           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3130           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3131                                  ArgValue, ArgValue1,
3132                                  DAG.getIntPtrConstant(0, dl));
3133           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3134                                  ArgValue, ArgValue2,
3135                                  DAG.getIntPtrConstant(1, dl));
3136         } else
3137           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3138
3139       } else {
3140         const TargetRegisterClass *RC;
3141
3142         if (RegVT == MVT::f32)
3143           RC = &ARM::SPRRegClass;
3144         else if (RegVT == MVT::f64)
3145           RC = &ARM::DPRRegClass;
3146         else if (RegVT == MVT::v2f64)
3147           RC = &ARM::QPRRegClass;
3148         else if (RegVT == MVT::i32)
3149           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3150                                            : &ARM::GPRRegClass;
3151         else
3152           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3153
3154         // Transform the arguments in physical registers into virtual ones.
3155         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3156         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3157       }
3158
3159       // If this is an 8 or 16-bit value, it is really passed promoted
3160       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3161       // truncate to the right size.
3162       switch (VA.getLocInfo()) {
3163       default: llvm_unreachable("Unknown loc info!");
3164       case CCValAssign::Full: break;
3165       case CCValAssign::BCvt:
3166         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3167         break;
3168       case CCValAssign::SExt:
3169         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3170                                DAG.getValueType(VA.getValVT()));
3171         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3172         break;
3173       case CCValAssign::ZExt:
3174         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3175                                DAG.getValueType(VA.getValVT()));
3176         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3177         break;
3178       }
3179
3180       InVals.push_back(ArgValue);
3181
3182     } else { // VA.isRegLoc()
3183
3184       // sanity check
3185       assert(VA.isMemLoc());
3186       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3187
3188       int index = VA.getValNo();
3189
3190       // Some Ins[] entries become multiple ArgLoc[] entries.
3191       // Process them only once.
3192       if (index != lastInsIndex)
3193         {
3194           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3195           // FIXME: For now, all byval parameter objects are marked mutable.
3196           // This can be changed with more analysis.
3197           // In case of tail call optimization mark all arguments mutable.
3198           // Since they could be overwritten by lowering of arguments in case of
3199           // a tail call.
3200           if (Flags.isByVal()) {
3201             assert(Ins[index].isOrigArg() &&
3202                    "Byval arguments cannot be implicit");
3203             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3204
3205             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3206                                             CurByValIndex, VA.getLocMemOffset(),
3207                                             Flags.getByValSize());
3208             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3209             CCInfo.nextInRegsParam();
3210           } else {
3211             unsigned FIOffset = VA.getLocMemOffset();
3212             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3213                                             FIOffset, true);
3214
3215             // Create load nodes to retrieve arguments from the stack.
3216             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3217             InVals.push_back(DAG.getLoad(
3218                 VA.getValVT(), dl, Chain, FIN,
3219                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3220                 false, false, false, 0));
3221           }
3222           lastInsIndex = index;
3223         }
3224     }
3225   }
3226
3227   // varargs
3228   if (isVarArg && MFI->hasVAStart())
3229     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3230                          CCInfo.getNextStackOffset(),
3231                          TotalArgRegsSaveSize);
3232
3233   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3234
3235   return Chain;
3236 }
3237
3238 /// isFloatingPointZero - Return true if this is +0.0.
3239 static bool isFloatingPointZero(SDValue Op) {
3240   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3241     return CFP->getValueAPF().isPosZero();
3242   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3243     // Maybe this has already been legalized into the constant pool?
3244     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3245       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3246       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3247         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3248           return CFP->getValueAPF().isPosZero();
3249     }
3250   } else if (Op->getOpcode() == ISD::BITCAST &&
3251              Op->getValueType(0) == MVT::f64) {
3252     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3253     // created by LowerConstantFP().
3254     SDValue BitcastOp = Op->getOperand(0);
3255     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3256       SDValue MoveOp = BitcastOp->getOperand(0);
3257       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3258           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3259         return true;
3260       }
3261     }
3262   }
3263   return false;
3264 }
3265
3266 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3267 /// the given operands.
3268 SDValue
3269 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3270                              SDValue &ARMcc, SelectionDAG &DAG,
3271                              SDLoc dl) const {
3272   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3273     unsigned C = RHSC->getZExtValue();
3274     if (!isLegalICmpImmediate(C)) {
3275       // Constant does not fit, try adjusting it by one?
3276       switch (CC) {
3277       default: break;
3278       case ISD::SETLT:
3279       case ISD::SETGE:
3280         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3281           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3282           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3283         }
3284         break;
3285       case ISD::SETULT:
3286       case ISD::SETUGE:
3287         if (C != 0 && isLegalICmpImmediate(C-1)) {
3288           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3289           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3290         }
3291         break;
3292       case ISD::SETLE:
3293       case ISD::SETGT:
3294         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3295           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3296           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3297         }
3298         break;
3299       case ISD::SETULE:
3300       case ISD::SETUGT:
3301         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3302           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3303           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3304         }
3305         break;
3306       }
3307     }
3308   }
3309
3310   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3311   ARMISD::NodeType CompareType;
3312   switch (CondCode) {
3313   default:
3314     CompareType = ARMISD::CMP;
3315     break;
3316   case ARMCC::EQ:
3317   case ARMCC::NE:
3318     // Uses only Z Flag
3319     CompareType = ARMISD::CMPZ;
3320     break;
3321   }
3322   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3323   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3324 }
3325
3326 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3327 SDValue
3328 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3329                              SDLoc dl) const {
3330   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3331   SDValue Cmp;
3332   if (!isFloatingPointZero(RHS))
3333     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3334   else
3335     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3336   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3337 }
3338
3339 /// duplicateCmp - Glue values can have only one use, so this function
3340 /// duplicates a comparison node.
3341 SDValue
3342 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3343   unsigned Opc = Cmp.getOpcode();
3344   SDLoc DL(Cmp);
3345   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3346     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3347
3348   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3349   Cmp = Cmp.getOperand(0);
3350   Opc = Cmp.getOpcode();
3351   if (Opc == ARMISD::CMPFP)
3352     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3353   else {
3354     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3355     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3356   }
3357   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3358 }
3359
3360 std::pair<SDValue, SDValue>
3361 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3362                                  SDValue &ARMcc) const {
3363   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3364
3365   SDValue Value, OverflowCmp;
3366   SDValue LHS = Op.getOperand(0);
3367   SDValue RHS = Op.getOperand(1);
3368   SDLoc dl(Op);
3369
3370   // FIXME: We are currently always generating CMPs because we don't support
3371   // generating CMN through the backend. This is not as good as the natural
3372   // CMP case because it causes a register dependency and cannot be folded
3373   // later.
3374
3375   switch (Op.getOpcode()) {
3376   default:
3377     llvm_unreachable("Unknown overflow instruction!");
3378   case ISD::SADDO:
3379     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3380     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3381     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3382     break;
3383   case ISD::UADDO:
3384     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3385     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3386     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3387     break;
3388   case ISD::SSUBO:
3389     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3390     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3391     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3392     break;
3393   case ISD::USUBO:
3394     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3395     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3396     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3397     break;
3398   } // switch (...)
3399
3400   return std::make_pair(Value, OverflowCmp);
3401 }
3402
3403
3404 SDValue
3405 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3406   // Let legalize expand this if it isn't a legal type yet.
3407   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3408     return SDValue();
3409
3410   SDValue Value, OverflowCmp;
3411   SDValue ARMcc;
3412   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3413   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3414   SDLoc dl(Op);
3415   // We use 0 and 1 as false and true values.
3416   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3417   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3418   EVT VT = Op.getValueType();
3419
3420   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3421                                  ARMcc, CCR, OverflowCmp);
3422
3423   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3424   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3425 }
3426
3427
3428 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3429   SDValue Cond = Op.getOperand(0);
3430   SDValue SelectTrue = Op.getOperand(1);
3431   SDValue SelectFalse = Op.getOperand(2);
3432   SDLoc dl(Op);
3433   unsigned Opc = Cond.getOpcode();
3434
3435   if (Cond.getResNo() == 1 &&
3436       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3437        Opc == ISD::USUBO)) {
3438     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3439       return SDValue();
3440
3441     SDValue Value, OverflowCmp;
3442     SDValue ARMcc;
3443     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3444     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3445     EVT VT = Op.getValueType();
3446
3447     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3448                    OverflowCmp, DAG);
3449   }
3450
3451   // Convert:
3452   //
3453   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3454   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3455   //
3456   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3457     const ConstantSDNode *CMOVTrue =
3458       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3459     const ConstantSDNode *CMOVFalse =
3460       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3461
3462     if (CMOVTrue && CMOVFalse) {
3463       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3464       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3465
3466       SDValue True;
3467       SDValue False;
3468       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3469         True = SelectTrue;
3470         False = SelectFalse;
3471       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3472         True = SelectFalse;
3473         False = SelectTrue;
3474       }
3475
3476       if (True.getNode() && False.getNode()) {
3477         EVT VT = Op.getValueType();
3478         SDValue ARMcc = Cond.getOperand(2);
3479         SDValue CCR = Cond.getOperand(3);
3480         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3481         assert(True.getValueType() == VT);
3482         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3483       }
3484     }
3485   }
3486
3487   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3488   // undefined bits before doing a full-word comparison with zero.
3489   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3490                      DAG.getConstant(1, dl, Cond.getValueType()));
3491
3492   return DAG.getSelectCC(dl, Cond,
3493                          DAG.getConstant(0, dl, Cond.getValueType()),
3494                          SelectTrue, SelectFalse, ISD::SETNE);
3495 }
3496
3497 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3498                                  bool &swpCmpOps, bool &swpVselOps) {
3499   // Start by selecting the GE condition code for opcodes that return true for
3500   // 'equality'
3501   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3502       CC == ISD::SETULE)
3503     CondCode = ARMCC::GE;
3504
3505   // and GT for opcodes that return false for 'equality'.
3506   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3507            CC == ISD::SETULT)
3508     CondCode = ARMCC::GT;
3509
3510   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3511   // to swap the compare operands.
3512   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3513       CC == ISD::SETULT)
3514     swpCmpOps = true;
3515
3516   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3517   // If we have an unordered opcode, we need to swap the operands to the VSEL
3518   // instruction (effectively negating the condition).
3519   //
3520   // This also has the effect of swapping which one of 'less' or 'greater'
3521   // returns true, so we also swap the compare operands. It also switches
3522   // whether we return true for 'equality', so we compensate by picking the
3523   // opposite condition code to our original choice.
3524   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3525       CC == ISD::SETUGT) {
3526     swpCmpOps = !swpCmpOps;
3527     swpVselOps = !swpVselOps;
3528     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3529   }
3530
3531   // 'ordered' is 'anything but unordered', so use the VS condition code and
3532   // swap the VSEL operands.
3533   if (CC == ISD::SETO) {
3534     CondCode = ARMCC::VS;
3535     swpVselOps = true;
3536   }
3537
3538   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3539   // code and swap the VSEL operands.
3540   if (CC == ISD::SETUNE) {
3541     CondCode = ARMCC::EQ;
3542     swpVselOps = true;
3543   }
3544 }
3545
3546 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3547                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3548                                    SDValue Cmp, SelectionDAG &DAG) const {
3549   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3550     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3551                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3552     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3553                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3554
3555     SDValue TrueLow = TrueVal.getValue(0);
3556     SDValue TrueHigh = TrueVal.getValue(1);
3557     SDValue FalseLow = FalseVal.getValue(0);
3558     SDValue FalseHigh = FalseVal.getValue(1);
3559
3560     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3561                               ARMcc, CCR, Cmp);
3562     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3563                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3564
3565     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3566   } else {
3567     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3568                        Cmp);
3569   }
3570 }
3571
3572 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3573   EVT VT = Op.getValueType();
3574   SDValue LHS = Op.getOperand(0);
3575   SDValue RHS = Op.getOperand(1);
3576   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3577   SDValue TrueVal = Op.getOperand(2);
3578   SDValue FalseVal = Op.getOperand(3);
3579   SDLoc dl(Op);
3580
3581   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3582     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3583                                                     dl);
3584
3585     // If softenSetCCOperands only returned one value, we should compare it to
3586     // zero.
3587     if (!RHS.getNode()) {
3588       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3589       CC = ISD::SETNE;
3590     }
3591   }
3592
3593   if (LHS.getValueType() == MVT::i32) {
3594     // Try to generate VSEL on ARMv8.
3595     // The VSEL instruction can't use all the usual ARM condition
3596     // codes: it only has two bits to select the condition code, so it's
3597     // constrained to use only GE, GT, VS and EQ.
3598     //
3599     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3600     // swap the operands of the previous compare instruction (effectively
3601     // inverting the compare condition, swapping 'less' and 'greater') and
3602     // sometimes need to swap the operands to the VSEL (which inverts the
3603     // condition in the sense of firing whenever the previous condition didn't)
3604     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3605                                     TrueVal.getValueType() == MVT::f64)) {
3606       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3607       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3608           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3609         CC = ISD::getSetCCInverse(CC, true);
3610         std::swap(TrueVal, FalseVal);
3611       }
3612     }
3613
3614     SDValue ARMcc;
3615     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3616     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3617     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3618   }
3619
3620   ARMCC::CondCodes CondCode, CondCode2;
3621   FPCCToARMCC(CC, CondCode, CondCode2);
3622
3623   // Try to generate VMAXNM/VMINNM on ARMv8.
3624   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3625                                   TrueVal.getValueType() == MVT::f64)) {
3626     bool swpCmpOps = false;
3627     bool swpVselOps = false;
3628     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3629
3630     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3631         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3632       if (swpCmpOps)
3633         std::swap(LHS, RHS);
3634       if (swpVselOps)
3635         std::swap(TrueVal, FalseVal);
3636     }
3637   }
3638
3639   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3640   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3641   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3642   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3643   if (CondCode2 != ARMCC::AL) {
3644     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3645     // FIXME: Needs another CMP because flag can have but one use.
3646     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3647     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3648   }
3649   return Result;
3650 }
3651
3652 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3653 /// to morph to an integer compare sequence.
3654 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3655                            const ARMSubtarget *Subtarget) {
3656   SDNode *N = Op.getNode();
3657   if (!N->hasOneUse())
3658     // Otherwise it requires moving the value from fp to integer registers.
3659     return false;
3660   if (!N->getNumValues())
3661     return false;
3662   EVT VT = Op.getValueType();
3663   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3664     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3665     // vmrs are very slow, e.g. cortex-a8.
3666     return false;
3667
3668   if (isFloatingPointZero(Op)) {
3669     SeenZero = true;
3670     return true;
3671   }
3672   return ISD::isNormalLoad(N);
3673 }
3674
3675 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3676   if (isFloatingPointZero(Op))
3677     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3678
3679   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3680     return DAG.getLoad(MVT::i32, SDLoc(Op),
3681                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3682                        Ld->isVolatile(), Ld->isNonTemporal(),
3683                        Ld->isInvariant(), Ld->getAlignment());
3684
3685   llvm_unreachable("Unknown VFP cmp argument!");
3686 }
3687
3688 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3689                            SDValue &RetVal1, SDValue &RetVal2) {
3690   SDLoc dl(Op);
3691
3692   if (isFloatingPointZero(Op)) {
3693     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3694     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3695     return;
3696   }
3697
3698   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3699     SDValue Ptr = Ld->getBasePtr();
3700     RetVal1 = DAG.getLoad(MVT::i32, dl,
3701                           Ld->getChain(), Ptr,
3702                           Ld->getPointerInfo(),
3703                           Ld->isVolatile(), Ld->isNonTemporal(),
3704                           Ld->isInvariant(), Ld->getAlignment());
3705
3706     EVT PtrType = Ptr.getValueType();
3707     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3708     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3709                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3710     RetVal2 = DAG.getLoad(MVT::i32, dl,
3711                           Ld->getChain(), NewPtr,
3712                           Ld->getPointerInfo().getWithOffset(4),
3713                           Ld->isVolatile(), Ld->isNonTemporal(),
3714                           Ld->isInvariant(), NewAlign);
3715     return;
3716   }
3717
3718   llvm_unreachable("Unknown VFP cmp argument!");
3719 }
3720
3721 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3722 /// f32 and even f64 comparisons to integer ones.
3723 SDValue
3724 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3725   SDValue Chain = Op.getOperand(0);
3726   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3727   SDValue LHS = Op.getOperand(2);
3728   SDValue RHS = Op.getOperand(3);
3729   SDValue Dest = Op.getOperand(4);
3730   SDLoc dl(Op);
3731
3732   bool LHSSeenZero = false;
3733   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3734   bool RHSSeenZero = false;
3735   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3736   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3737     // If unsafe fp math optimization is enabled and there are no other uses of
3738     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3739     // to an integer comparison.
3740     if (CC == ISD::SETOEQ)
3741       CC = ISD::SETEQ;
3742     else if (CC == ISD::SETUNE)
3743       CC = ISD::SETNE;
3744
3745     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3746     SDValue ARMcc;
3747     if (LHS.getValueType() == MVT::f32) {
3748       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3749                         bitcastf32Toi32(LHS, DAG), Mask);
3750       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3751                         bitcastf32Toi32(RHS, DAG), Mask);
3752       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3753       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3754       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3755                          Chain, Dest, ARMcc, CCR, Cmp);
3756     }
3757
3758     SDValue LHS1, LHS2;
3759     SDValue RHS1, RHS2;
3760     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3761     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3762     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3763     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3764     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3765     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3766     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3767     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3768     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3769   }
3770
3771   return SDValue();
3772 }
3773
3774 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3775   SDValue Chain = Op.getOperand(0);
3776   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3777   SDValue LHS = Op.getOperand(2);
3778   SDValue RHS = Op.getOperand(3);
3779   SDValue Dest = Op.getOperand(4);
3780   SDLoc dl(Op);
3781
3782   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3783     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3784                                                     dl);
3785
3786     // If softenSetCCOperands only returned one value, we should compare it to
3787     // zero.
3788     if (!RHS.getNode()) {
3789       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3790       CC = ISD::SETNE;
3791     }
3792   }
3793
3794   if (LHS.getValueType() == MVT::i32) {
3795     SDValue ARMcc;
3796     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3797     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3798     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3799                        Chain, Dest, ARMcc, CCR, Cmp);
3800   }
3801
3802   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3803
3804   if (getTargetMachine().Options.UnsafeFPMath &&
3805       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3806        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3807     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3808     if (Result.getNode())
3809       return Result;
3810   }
3811
3812   ARMCC::CondCodes CondCode, CondCode2;
3813   FPCCToARMCC(CC, CondCode, CondCode2);
3814
3815   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3816   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3817   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3818   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3819   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3820   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3821   if (CondCode2 != ARMCC::AL) {
3822     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3823     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3824     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3825   }
3826   return Res;
3827 }
3828
3829 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3830   SDValue Chain = Op.getOperand(0);
3831   SDValue Table = Op.getOperand(1);
3832   SDValue Index = Op.getOperand(2);
3833   SDLoc dl(Op);
3834
3835   EVT PTy = getPointerTy(DAG.getDataLayout());
3836   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3837   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3838   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3839   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3840   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3841   if (Subtarget->isThumb2()) {
3842     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3843     // which does another jump to the destination. This also makes it easier
3844     // to translate it to TBB / TBH later.
3845     // FIXME: This might not work if the function is extremely large.
3846     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3847                        Addr, Op.getOperand(2), JTI);
3848   }
3849   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3850     Addr =
3851         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3852                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3853                     false, false, false, 0);
3854     Chain = Addr.getValue(1);
3855     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3856     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3857   } else {
3858     Addr =
3859         DAG.getLoad(PTy, dl, Chain, Addr,
3860                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3861                     false, false, false, 0);
3862     Chain = Addr.getValue(1);
3863     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3864   }
3865 }
3866
3867 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3868   EVT VT = Op.getValueType();
3869   SDLoc dl(Op);
3870
3871   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3872     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3873       return Op;
3874     return DAG.UnrollVectorOp(Op.getNode());
3875   }
3876
3877   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3878          "Invalid type for custom lowering!");
3879   if (VT != MVT::v4i16)
3880     return DAG.UnrollVectorOp(Op.getNode());
3881
3882   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3883   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3884 }
3885
3886 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3887   EVT VT = Op.getValueType();
3888   if (VT.isVector())
3889     return LowerVectorFP_TO_INT(Op, DAG);
3890   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3891     RTLIB::Libcall LC;
3892     if (Op.getOpcode() == ISD::FP_TO_SINT)
3893       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3894                               Op.getValueType());
3895     else
3896       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3897                               Op.getValueType());
3898     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3899                        /*isSigned*/ false, SDLoc(Op)).first;
3900   }
3901
3902   return Op;
3903 }
3904
3905 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3906   EVT VT = Op.getValueType();
3907   SDLoc dl(Op);
3908
3909   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3910     if (VT.getVectorElementType() == MVT::f32)
3911       return Op;
3912     return DAG.UnrollVectorOp(Op.getNode());
3913   }
3914
3915   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3916          "Invalid type for custom lowering!");
3917   if (VT != MVT::v4f32)
3918     return DAG.UnrollVectorOp(Op.getNode());
3919
3920   unsigned CastOpc;
3921   unsigned Opc;
3922   switch (Op.getOpcode()) {
3923   default: llvm_unreachable("Invalid opcode!");
3924   case ISD::SINT_TO_FP:
3925     CastOpc = ISD::SIGN_EXTEND;
3926     Opc = ISD::SINT_TO_FP;
3927     break;
3928   case ISD::UINT_TO_FP:
3929     CastOpc = ISD::ZERO_EXTEND;
3930     Opc = ISD::UINT_TO_FP;
3931     break;
3932   }
3933
3934   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3935   return DAG.getNode(Opc, dl, VT, Op);
3936 }
3937
3938 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3939   EVT VT = Op.getValueType();
3940   if (VT.isVector())
3941     return LowerVectorINT_TO_FP(Op, DAG);
3942   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3943     RTLIB::Libcall LC;
3944     if (Op.getOpcode() == ISD::SINT_TO_FP)
3945       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3946                               Op.getValueType());
3947     else
3948       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3949                               Op.getValueType());
3950     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3951                        /*isSigned*/ false, SDLoc(Op)).first;
3952   }
3953
3954   return Op;
3955 }
3956
3957 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3958   // Implement fcopysign with a fabs and a conditional fneg.
3959   SDValue Tmp0 = Op.getOperand(0);
3960   SDValue Tmp1 = Op.getOperand(1);
3961   SDLoc dl(Op);
3962   EVT VT = Op.getValueType();
3963   EVT SrcVT = Tmp1.getValueType();
3964   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3965     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3966   bool UseNEON = !InGPR && Subtarget->hasNEON();
3967
3968   if (UseNEON) {
3969     // Use VBSL to copy the sign bit.
3970     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3971     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3972                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3973     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3974     if (VT == MVT::f64)
3975       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3976                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3977                          DAG.getConstant(32, dl, MVT::i32));
3978     else /*if (VT == MVT::f32)*/
3979       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3980     if (SrcVT == MVT::f32) {
3981       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3982       if (VT == MVT::f64)
3983         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3984                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3985                            DAG.getConstant(32, dl, MVT::i32));
3986     } else if (VT == MVT::f32)
3987       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3988                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3989                          DAG.getConstant(32, dl, MVT::i32));
3990     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3991     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3992
3993     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3994                                             dl, MVT::i32);
3995     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3996     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3997                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3998
3999     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4000                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4001                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4002     if (VT == MVT::f32) {
4003       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4004       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4005                         DAG.getConstant(0, dl, MVT::i32));
4006     } else {
4007       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4008     }
4009
4010     return Res;
4011   }
4012
4013   // Bitcast operand 1 to i32.
4014   if (SrcVT == MVT::f64)
4015     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4016                        Tmp1).getValue(1);
4017   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4018
4019   // Or in the signbit with integer operations.
4020   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4021   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4022   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4023   if (VT == MVT::f32) {
4024     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4025                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4026     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4027                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4028   }
4029
4030   // f64: Or the high part with signbit and then combine two parts.
4031   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4032                      Tmp0);
4033   SDValue Lo = Tmp0.getValue(0);
4034   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4035   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4036   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4037 }
4038
4039 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4040   MachineFunction &MF = DAG.getMachineFunction();
4041   MachineFrameInfo *MFI = MF.getFrameInfo();
4042   MFI->setReturnAddressIsTaken(true);
4043
4044   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4045     return SDValue();
4046
4047   EVT VT = Op.getValueType();
4048   SDLoc dl(Op);
4049   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4050   if (Depth) {
4051     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4052     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4053     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4054                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4055                        MachinePointerInfo(), false, false, false, 0);
4056   }
4057
4058   // Return LR, which contains the return address. Mark it an implicit live-in.
4059   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4060   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4061 }
4062
4063 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4064   const ARMBaseRegisterInfo &ARI =
4065     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4066   MachineFunction &MF = DAG.getMachineFunction();
4067   MachineFrameInfo *MFI = MF.getFrameInfo();
4068   MFI->setFrameAddressIsTaken(true);
4069
4070   EVT VT = Op.getValueType();
4071   SDLoc dl(Op);  // FIXME probably not meaningful
4072   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4073   unsigned FrameReg = ARI.getFrameRegister(MF);
4074   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4075   while (Depth--)
4076     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4077                             MachinePointerInfo(),
4078                             false, false, false, 0);
4079   return FrameAddr;
4080 }
4081
4082 // FIXME? Maybe this could be a TableGen attribute on some registers and
4083 // this table could be generated automatically from RegInfo.
4084 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4085                                               SelectionDAG &DAG) const {
4086   unsigned Reg = StringSwitch<unsigned>(RegName)
4087                        .Case("sp", ARM::SP)
4088                        .Default(0);
4089   if (Reg)
4090     return Reg;
4091   report_fatal_error(Twine("Invalid register name \""
4092                               + StringRef(RegName)  + "\"."));
4093 }
4094
4095 // Result is 64 bit value so split into two 32 bit values and return as a
4096 // pair of values.
4097 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4098                                 SelectionDAG &DAG) {
4099   SDLoc DL(N);
4100
4101   // This function is only supposed to be called for i64 type destination.
4102   assert(N->getValueType(0) == MVT::i64
4103           && "ExpandREAD_REGISTER called for non-i64 type result.");
4104
4105   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4106                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4107                              N->getOperand(0),
4108                              N->getOperand(1));
4109
4110   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4111                     Read.getValue(1)));
4112   Results.push_back(Read.getOperand(0));
4113 }
4114
4115 /// ExpandBITCAST - If the target supports VFP, this function is called to
4116 /// expand a bit convert where either the source or destination type is i64 to
4117 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4118 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4119 /// vectors), since the legalizer won't know what to do with that.
4120 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4121   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4122   SDLoc dl(N);
4123   SDValue Op = N->getOperand(0);
4124
4125   // This function is only supposed to be called for i64 types, either as the
4126   // source or destination of the bit convert.
4127   EVT SrcVT = Op.getValueType();
4128   EVT DstVT = N->getValueType(0);
4129   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4130          "ExpandBITCAST called for non-i64 type");
4131
4132   // Turn i64->f64 into VMOVDRR.
4133   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4134     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4135                              DAG.getConstant(0, dl, MVT::i32));
4136     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4137                              DAG.getConstant(1, dl, MVT::i32));
4138     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4139                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4140   }
4141
4142   // Turn f64->i64 into VMOVRRD.
4143   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4144     SDValue Cvt;
4145     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4146         SrcVT.getVectorNumElements() > 1)
4147       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4148                         DAG.getVTList(MVT::i32, MVT::i32),
4149                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4150     else
4151       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4152                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4153     // Merge the pieces into a single i64 value.
4154     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4155   }
4156
4157   return SDValue();
4158 }
4159
4160 /// getZeroVector - Returns a vector of specified type with all zero elements.
4161 /// Zero vectors are used to represent vector negation and in those cases
4162 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4163 /// not support i64 elements, so sometimes the zero vectors will need to be
4164 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4165 /// zero vector.
4166 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4167   assert(VT.isVector() && "Expected a vector type");
4168   // The canonical modified immediate encoding of a zero vector is....0!
4169   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4170   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4171   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4172   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4173 }
4174
4175 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4176 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4177 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4178                                                 SelectionDAG &DAG) const {
4179   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4180   EVT VT = Op.getValueType();
4181   unsigned VTBits = VT.getSizeInBits();
4182   SDLoc dl(Op);
4183   SDValue ShOpLo = Op.getOperand(0);
4184   SDValue ShOpHi = Op.getOperand(1);
4185   SDValue ShAmt  = Op.getOperand(2);
4186   SDValue ARMcc;
4187   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4188
4189   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4190
4191   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4192                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4193   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4194   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4195                                    DAG.getConstant(VTBits, dl, MVT::i32));
4196   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4197   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4198   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4199
4200   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4201   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4202                           ISD::SETGE, ARMcc, DAG, dl);
4203   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4204   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4205                            CCR, Cmp);
4206
4207   SDValue Ops[2] = { Lo, Hi };
4208   return DAG.getMergeValues(Ops, dl);
4209 }
4210
4211 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4212 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4213 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4214                                                SelectionDAG &DAG) const {
4215   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4216   EVT VT = Op.getValueType();
4217   unsigned VTBits = VT.getSizeInBits();
4218   SDLoc dl(Op);
4219   SDValue ShOpLo = Op.getOperand(0);
4220   SDValue ShOpHi = Op.getOperand(1);
4221   SDValue ShAmt  = Op.getOperand(2);
4222   SDValue ARMcc;
4223
4224   assert(Op.getOpcode() == ISD::SHL_PARTS);
4225   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4226                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4227   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4228   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4229                                    DAG.getConstant(VTBits, dl, MVT::i32));
4230   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4231   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4232
4233   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4234   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4235   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4236                           ISD::SETGE, ARMcc, DAG, dl);
4237   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4238   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4239                            CCR, Cmp);
4240
4241   SDValue Ops[2] = { Lo, Hi };
4242   return DAG.getMergeValues(Ops, dl);
4243 }
4244
4245 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4246                                             SelectionDAG &DAG) const {
4247   // The rounding mode is in bits 23:22 of the FPSCR.
4248   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4249   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4250   // so that the shift + and get folded into a bitfield extract.
4251   SDLoc dl(Op);
4252   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4253                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4254                                               MVT::i32));
4255   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4256                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4257   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4258                               DAG.getConstant(22, dl, MVT::i32));
4259   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4260                      DAG.getConstant(3, dl, MVT::i32));
4261 }
4262
4263 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4264                          const ARMSubtarget *ST) {
4265   SDLoc dl(N);
4266   EVT VT = N->getValueType(0);
4267   if (VT.isVector()) {
4268     assert(ST->hasNEON());
4269
4270     // Compute the least significant set bit: LSB = X & -X
4271     SDValue X = N->getOperand(0);
4272     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4273     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4274
4275     EVT ElemTy = VT.getVectorElementType();
4276
4277     if (ElemTy == MVT::i8) {
4278       // Compute with: cttz(x) = ctpop(lsb - 1)
4279       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4280                                 DAG.getTargetConstant(1, dl, ElemTy));
4281       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4282       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4283     }
4284
4285     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4286         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4287       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4288       unsigned NumBits = ElemTy.getSizeInBits();
4289       SDValue WidthMinus1 =
4290           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4291                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4292       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4293       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4294     }
4295
4296     // Compute with: cttz(x) = ctpop(lsb - 1)
4297
4298     // Since we can only compute the number of bits in a byte with vcnt.8, we
4299     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4300     // and i64.
4301
4302     // Compute LSB - 1.
4303     SDValue Bits;
4304     if (ElemTy == MVT::i64) {
4305       // Load constant 0xffff'ffff'ffff'ffff to register.
4306       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4307                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4308       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4309     } else {
4310       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4311                                 DAG.getTargetConstant(1, dl, ElemTy));
4312       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4313     }
4314
4315     // Count #bits with vcnt.8.
4316     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4317     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4318     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4319
4320     // Gather the #bits with vpaddl (pairwise add.)
4321     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4322     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4323         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4324         Cnt8);
4325     if (ElemTy == MVT::i16)
4326       return Cnt16;
4327
4328     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4329     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4330         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4331         Cnt16);
4332     if (ElemTy == MVT::i32)
4333       return Cnt32;
4334
4335     assert(ElemTy == MVT::i64);
4336     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4337         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4338         Cnt32);
4339     return Cnt64;
4340   }
4341
4342   if (!ST->hasV6T2Ops())
4343     return SDValue();
4344
4345   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4346   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4347 }
4348
4349 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4350 /// for each 16-bit element from operand, repeated.  The basic idea is to
4351 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4352 ///
4353 /// Trace for v4i16:
4354 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4355 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4356 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4357 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4358 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4359 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4360 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4361 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4362 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4363   EVT VT = N->getValueType(0);
4364   SDLoc DL(N);
4365
4366   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4367   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4368   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4369   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4370   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4371   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4372 }
4373
4374 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4375 /// bit-count for each 16-bit element from the operand.  We need slightly
4376 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4377 /// 64/128-bit registers.
4378 ///
4379 /// Trace for v4i16:
4380 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4381 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4382 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4383 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4384 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4385   EVT VT = N->getValueType(0);
4386   SDLoc DL(N);
4387
4388   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4389   if (VT.is64BitVector()) {
4390     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4391     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4392                        DAG.getIntPtrConstant(0, DL));
4393   } else {
4394     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4395                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4396     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4397   }
4398 }
4399
4400 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4401 /// bit-count for each 32-bit element from the operand.  The idea here is
4402 /// to split the vector into 16-bit elements, leverage the 16-bit count
4403 /// routine, and then combine the results.
4404 ///
4405 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4406 /// input    = [v0    v1    ] (vi: 32-bit elements)
4407 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4408 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4409 /// vrev: N0 = [k1 k0 k3 k2 ]
4410 ///            [k0 k1 k2 k3 ]
4411 ///       N1 =+[k1 k0 k3 k2 ]
4412 ///            [k0 k2 k1 k3 ]
4413 ///       N2 =+[k1 k3 k0 k2 ]
4414 ///            [k0    k2    k1    k3    ]
4415 /// Extended =+[k1    k3    k0    k2    ]
4416 ///            [k0    k2    ]
4417 /// Extracted=+[k1    k3    ]
4418 ///
4419 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4420   EVT VT = N->getValueType(0);
4421   SDLoc DL(N);
4422
4423   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4424
4425   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4426   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4427   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4428   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4429   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4430
4431   if (VT.is64BitVector()) {
4432     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4433     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4434                        DAG.getIntPtrConstant(0, DL));
4435   } else {
4436     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4437                                     DAG.getIntPtrConstant(0, DL));
4438     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4439   }
4440 }
4441
4442 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4443                           const ARMSubtarget *ST) {
4444   EVT VT = N->getValueType(0);
4445
4446   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4447   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4448           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4449          "Unexpected type for custom ctpop lowering");
4450
4451   if (VT.getVectorElementType() == MVT::i32)
4452     return lowerCTPOP32BitElements(N, DAG);
4453   else
4454     return lowerCTPOP16BitElements(N, DAG);
4455 }
4456
4457 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4458                           const ARMSubtarget *ST) {
4459   EVT VT = N->getValueType(0);
4460   SDLoc dl(N);
4461
4462   if (!VT.isVector())
4463     return SDValue();
4464
4465   // Lower vector shifts on NEON to use VSHL.
4466   assert(ST->hasNEON() && "unexpected vector shift");
4467
4468   // Left shifts translate directly to the vshiftu intrinsic.
4469   if (N->getOpcode() == ISD::SHL)
4470     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4471                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4472                                        MVT::i32),
4473                        N->getOperand(0), N->getOperand(1));
4474
4475   assert((N->getOpcode() == ISD::SRA ||
4476           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4477
4478   // NEON uses the same intrinsics for both left and right shifts.  For
4479   // right shifts, the shift amounts are negative, so negate the vector of
4480   // shift amounts.
4481   EVT ShiftVT = N->getOperand(1).getValueType();
4482   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4483                                      getZeroVector(ShiftVT, DAG, dl),
4484                                      N->getOperand(1));
4485   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4486                              Intrinsic::arm_neon_vshifts :
4487                              Intrinsic::arm_neon_vshiftu);
4488   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4489                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4490                      N->getOperand(0), NegatedCount);
4491 }
4492
4493 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4494                                 const ARMSubtarget *ST) {
4495   EVT VT = N->getValueType(0);
4496   SDLoc dl(N);
4497
4498   // We can get here for a node like i32 = ISD::SHL i32, i64
4499   if (VT != MVT::i64)
4500     return SDValue();
4501
4502   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4503          "Unknown shift to lower!");
4504
4505   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4506   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4507       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4508     return SDValue();
4509
4510   // If we are in thumb mode, we don't have RRX.
4511   if (ST->isThumb1Only()) return SDValue();
4512
4513   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4514   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4515                            DAG.getConstant(0, dl, MVT::i32));
4516   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4517                            DAG.getConstant(1, dl, MVT::i32));
4518
4519   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4520   // captures the result into a carry flag.
4521   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4522   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4523
4524   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4525   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4526
4527   // Merge the pieces into a single i64 value.
4528  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4529 }
4530
4531 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4532   SDValue TmpOp0, TmpOp1;
4533   bool Invert = false;
4534   bool Swap = false;
4535   unsigned Opc = 0;
4536
4537   SDValue Op0 = Op.getOperand(0);
4538   SDValue Op1 = Op.getOperand(1);
4539   SDValue CC = Op.getOperand(2);
4540   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4541   EVT VT = Op.getValueType();
4542   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4543   SDLoc dl(Op);
4544
4545   if (Op1.getValueType().isFloatingPoint()) {
4546     switch (SetCCOpcode) {
4547     default: llvm_unreachable("Illegal FP comparison");
4548     case ISD::SETUNE:
4549     case ISD::SETNE:  Invert = true; // Fallthrough
4550     case ISD::SETOEQ:
4551     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4552     case ISD::SETOLT:
4553     case ISD::SETLT: Swap = true; // Fallthrough
4554     case ISD::SETOGT:
4555     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4556     case ISD::SETOLE:
4557     case ISD::SETLE:  Swap = true; // Fallthrough
4558     case ISD::SETOGE:
4559     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4560     case ISD::SETUGE: Swap = true; // Fallthrough
4561     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4562     case ISD::SETUGT: Swap = true; // Fallthrough
4563     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4564     case ISD::SETUEQ: Invert = true; // Fallthrough
4565     case ISD::SETONE:
4566       // Expand this to (OLT | OGT).
4567       TmpOp0 = Op0;
4568       TmpOp1 = Op1;
4569       Opc = ISD::OR;
4570       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4571       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4572       break;
4573     case ISD::SETUO: Invert = true; // Fallthrough
4574     case ISD::SETO:
4575       // Expand this to (OLT | OGE).
4576       TmpOp0 = Op0;
4577       TmpOp1 = Op1;
4578       Opc = ISD::OR;
4579       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4580       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4581       break;
4582     }
4583   } else {
4584     // Integer comparisons.
4585     switch (SetCCOpcode) {
4586     default: llvm_unreachable("Illegal integer comparison");
4587     case ISD::SETNE:  Invert = true;
4588     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4589     case ISD::SETLT:  Swap = true;
4590     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4591     case ISD::SETLE:  Swap = true;
4592     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4593     case ISD::SETULT: Swap = true;
4594     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4595     case ISD::SETULE: Swap = true;
4596     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4597     }
4598
4599     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4600     if (Opc == ARMISD::VCEQ) {
4601
4602       SDValue AndOp;
4603       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4604         AndOp = Op0;
4605       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4606         AndOp = Op1;
4607
4608       // Ignore bitconvert.
4609       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4610         AndOp = AndOp.getOperand(0);
4611
4612       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4613         Opc = ARMISD::VTST;
4614         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4615         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4616         Invert = !Invert;
4617       }
4618     }
4619   }
4620
4621   if (Swap)
4622     std::swap(Op0, Op1);
4623
4624   // If one of the operands is a constant vector zero, attempt to fold the
4625   // comparison to a specialized compare-against-zero form.
4626   SDValue SingleOp;
4627   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4628     SingleOp = Op0;
4629   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4630     if (Opc == ARMISD::VCGE)
4631       Opc = ARMISD::VCLEZ;
4632     else if (Opc == ARMISD::VCGT)
4633       Opc = ARMISD::VCLTZ;
4634     SingleOp = Op1;
4635   }
4636
4637   SDValue Result;
4638   if (SingleOp.getNode()) {
4639     switch (Opc) {
4640     case ARMISD::VCEQ:
4641       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4642     case ARMISD::VCGE:
4643       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4644     case ARMISD::VCLEZ:
4645       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4646     case ARMISD::VCGT:
4647       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4648     case ARMISD::VCLTZ:
4649       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4650     default:
4651       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4652     }
4653   } else {
4654      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4655   }
4656
4657   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4658
4659   if (Invert)
4660     Result = DAG.getNOT(dl, Result, VT);
4661
4662   return Result;
4663 }
4664
4665 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4666 /// valid vector constant for a NEON instruction with a "modified immediate"
4667 /// operand (e.g., VMOV).  If so, return the encoded value.
4668 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4669                                  unsigned SplatBitSize, SelectionDAG &DAG,
4670                                  SDLoc dl, EVT &VT, bool is128Bits,
4671                                  NEONModImmType type) {
4672   unsigned OpCmode, Imm;
4673
4674   // SplatBitSize is set to the smallest size that splats the vector, so a
4675   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4676   // immediate instructions others than VMOV do not support the 8-bit encoding
4677   // of a zero vector, and the default encoding of zero is supposed to be the
4678   // 32-bit version.
4679   if (SplatBits == 0)
4680     SplatBitSize = 32;
4681
4682   switch (SplatBitSize) {
4683   case 8:
4684     if (type != VMOVModImm)
4685       return SDValue();
4686     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4687     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4688     OpCmode = 0xe;
4689     Imm = SplatBits;
4690     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4691     break;
4692
4693   case 16:
4694     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4695     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4696     if ((SplatBits & ~0xff) == 0) {
4697       // Value = 0x00nn: Op=x, Cmode=100x.
4698       OpCmode = 0x8;
4699       Imm = SplatBits;
4700       break;
4701     }
4702     if ((SplatBits & ~0xff00) == 0) {
4703       // Value = 0xnn00: Op=x, Cmode=101x.
4704       OpCmode = 0xa;
4705       Imm = SplatBits >> 8;
4706       break;
4707     }
4708     return SDValue();
4709
4710   case 32:
4711     // NEON's 32-bit VMOV supports splat values where:
4712     // * only one byte is nonzero, or
4713     // * the least significant byte is 0xff and the second byte is nonzero, or
4714     // * the least significant 2 bytes are 0xff and the third is nonzero.
4715     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4716     if ((SplatBits & ~0xff) == 0) {
4717       // Value = 0x000000nn: Op=x, Cmode=000x.
4718       OpCmode = 0;
4719       Imm = SplatBits;
4720       break;
4721     }
4722     if ((SplatBits & ~0xff00) == 0) {
4723       // Value = 0x0000nn00: Op=x, Cmode=001x.
4724       OpCmode = 0x2;
4725       Imm = SplatBits >> 8;
4726       break;
4727     }
4728     if ((SplatBits & ~0xff0000) == 0) {
4729       // Value = 0x00nn0000: Op=x, Cmode=010x.
4730       OpCmode = 0x4;
4731       Imm = SplatBits >> 16;
4732       break;
4733     }
4734     if ((SplatBits & ~0xff000000) == 0) {
4735       // Value = 0xnn000000: Op=x, Cmode=011x.
4736       OpCmode = 0x6;
4737       Imm = SplatBits >> 24;
4738       break;
4739     }
4740
4741     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4742     if (type == OtherModImm) return SDValue();
4743
4744     if ((SplatBits & ~0xffff) == 0 &&
4745         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4746       // Value = 0x0000nnff: Op=x, Cmode=1100.
4747       OpCmode = 0xc;
4748       Imm = SplatBits >> 8;
4749       break;
4750     }
4751
4752     if ((SplatBits & ~0xffffff) == 0 &&
4753         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4754       // Value = 0x00nnffff: Op=x, Cmode=1101.
4755       OpCmode = 0xd;
4756       Imm = SplatBits >> 16;
4757       break;
4758     }
4759
4760     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4761     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4762     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4763     // and fall through here to test for a valid 64-bit splat.  But, then the
4764     // caller would also need to check and handle the change in size.
4765     return SDValue();
4766
4767   case 64: {
4768     if (type != VMOVModImm)
4769       return SDValue();
4770     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4771     uint64_t BitMask = 0xff;
4772     uint64_t Val = 0;
4773     unsigned ImmMask = 1;
4774     Imm = 0;
4775     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4776       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4777         Val |= BitMask;
4778         Imm |= ImmMask;
4779       } else if ((SplatBits & BitMask) != 0) {
4780         return SDValue();
4781       }
4782       BitMask <<= 8;
4783       ImmMask <<= 1;
4784     }
4785
4786     if (DAG.getDataLayout().isBigEndian())
4787       // swap higher and lower 32 bit word
4788       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4789
4790     // Op=1, Cmode=1110.
4791     OpCmode = 0x1e;
4792     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4793     break;
4794   }
4795
4796   default:
4797     llvm_unreachable("unexpected size for isNEONModifiedImm");
4798   }
4799
4800   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4801   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4802 }
4803
4804 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4805                                            const ARMSubtarget *ST) const {
4806   if (!ST->hasVFP3())
4807     return SDValue();
4808
4809   bool IsDouble = Op.getValueType() == MVT::f64;
4810   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4811
4812   // Use the default (constant pool) lowering for double constants when we have
4813   // an SP-only FPU
4814   if (IsDouble && Subtarget->isFPOnlySP())
4815     return SDValue();
4816
4817   // Try splatting with a VMOV.f32...
4818   APFloat FPVal = CFP->getValueAPF();
4819   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4820
4821   if (ImmVal != -1) {
4822     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4823       // We have code in place to select a valid ConstantFP already, no need to
4824       // do any mangling.
4825       return Op;
4826     }
4827
4828     // It's a float and we are trying to use NEON operations where
4829     // possible. Lower it to a splat followed by an extract.
4830     SDLoc DL(Op);
4831     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4832     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4833                                       NewVal);
4834     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4835                        DAG.getConstant(0, DL, MVT::i32));
4836   }
4837
4838   // The rest of our options are NEON only, make sure that's allowed before
4839   // proceeding..
4840   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4841     return SDValue();
4842
4843   EVT VMovVT;
4844   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4845
4846   // It wouldn't really be worth bothering for doubles except for one very
4847   // important value, which does happen to match: 0.0. So make sure we don't do
4848   // anything stupid.
4849   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4850     return SDValue();
4851
4852   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4853   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4854                                      VMovVT, false, VMOVModImm);
4855   if (NewVal != SDValue()) {
4856     SDLoc DL(Op);
4857     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4858                                       NewVal);
4859     if (IsDouble)
4860       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4861
4862     // It's a float: cast and extract a vector element.
4863     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4864                                        VecConstant);
4865     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4866                        DAG.getConstant(0, DL, MVT::i32));
4867   }
4868
4869   // Finally, try a VMVN.i32
4870   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4871                              false, VMVNModImm);
4872   if (NewVal != SDValue()) {
4873     SDLoc DL(Op);
4874     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4875
4876     if (IsDouble)
4877       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4878
4879     // It's a float: cast and extract a vector element.
4880     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4881                                        VecConstant);
4882     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4883                        DAG.getConstant(0, DL, MVT::i32));
4884   }
4885
4886   return SDValue();
4887 }
4888
4889 // check if an VEXT instruction can handle the shuffle mask when the
4890 // vector sources of the shuffle are the same.
4891 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4892   unsigned NumElts = VT.getVectorNumElements();
4893
4894   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4895   if (M[0] < 0)
4896     return false;
4897
4898   Imm = M[0];
4899
4900   // If this is a VEXT shuffle, the immediate value is the index of the first
4901   // element.  The other shuffle indices must be the successive elements after
4902   // the first one.
4903   unsigned ExpectedElt = Imm;
4904   for (unsigned i = 1; i < NumElts; ++i) {
4905     // Increment the expected index.  If it wraps around, just follow it
4906     // back to index zero and keep going.
4907     ++ExpectedElt;
4908     if (ExpectedElt == NumElts)
4909       ExpectedElt = 0;
4910
4911     if (M[i] < 0) continue; // ignore UNDEF indices
4912     if (ExpectedElt != static_cast<unsigned>(M[i]))
4913       return false;
4914   }
4915
4916   return true;
4917 }
4918
4919
4920 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4921                        bool &ReverseVEXT, unsigned &Imm) {
4922   unsigned NumElts = VT.getVectorNumElements();
4923   ReverseVEXT = false;
4924
4925   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4926   if (M[0] < 0)
4927     return false;
4928
4929   Imm = M[0];
4930
4931   // If this is a VEXT shuffle, the immediate value is the index of the first
4932   // element.  The other shuffle indices must be the successive elements after
4933   // the first one.
4934   unsigned ExpectedElt = Imm;
4935   for (unsigned i = 1; i < NumElts; ++i) {
4936     // Increment the expected index.  If it wraps around, it may still be
4937     // a VEXT but the source vectors must be swapped.
4938     ExpectedElt += 1;
4939     if (ExpectedElt == NumElts * 2) {
4940       ExpectedElt = 0;
4941       ReverseVEXT = true;
4942     }
4943
4944     if (M[i] < 0) continue; // ignore UNDEF indices
4945     if (ExpectedElt != static_cast<unsigned>(M[i]))
4946       return false;
4947   }
4948
4949   // Adjust the index value if the source operands will be swapped.
4950   if (ReverseVEXT)
4951     Imm -= NumElts;
4952
4953   return true;
4954 }
4955
4956 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4957 /// instruction with the specified blocksize.  (The order of the elements
4958 /// within each block of the vector is reversed.)
4959 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4960   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4961          "Only possible block sizes for VREV are: 16, 32, 64");
4962
4963   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4964   if (EltSz == 64)
4965     return false;
4966
4967   unsigned NumElts = VT.getVectorNumElements();
4968   unsigned BlockElts = M[0] + 1;
4969   // If the first shuffle index is UNDEF, be optimistic.
4970   if (M[0] < 0)
4971     BlockElts = BlockSize / EltSz;
4972
4973   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4974     return false;
4975
4976   for (unsigned i = 0; i < NumElts; ++i) {
4977     if (M[i] < 0) continue; // ignore UNDEF indices
4978     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4979       return false;
4980   }
4981
4982   return true;
4983 }
4984
4985 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4986   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4987   // range, then 0 is placed into the resulting vector. So pretty much any mask
4988   // of 8 elements can work here.
4989   return VT == MVT::v8i8 && M.size() == 8;
4990 }
4991
4992 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
4993 // checking that pairs of elements in the shuffle mask represent the same index
4994 // in each vector, incrementing the expected index by 2 at each step.
4995 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
4996 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
4997 //  v2={e,f,g,h}
4998 // WhichResult gives the offset for each element in the mask based on which
4999 // of the two results it belongs to.
5000 //
5001 // The transpose can be represented either as:
5002 // result1 = shufflevector v1, v2, result1_shuffle_mask
5003 // result2 = shufflevector v1, v2, result2_shuffle_mask
5004 // where v1/v2 and the shuffle masks have the same number of elements
5005 // (here WhichResult (see below) indicates which result is being checked)
5006 //
5007 // or as:
5008 // results = shufflevector v1, v2, shuffle_mask
5009 // where both results are returned in one vector and the shuffle mask has twice
5010 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5011 // want to check the low half and high half of the shuffle mask as if it were
5012 // the other case
5013 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5014   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5015   if (EltSz == 64)
5016     return false;
5017
5018   unsigned NumElts = VT.getVectorNumElements();
5019   if (M.size() != NumElts && M.size() != NumElts*2)
5020     return false;
5021
5022   // If the mask is twice as long as the result then we need to check the upper
5023   // and lower parts of the mask
5024   for (unsigned i = 0; i < M.size(); i += NumElts) {
5025     WhichResult = M[i] == 0 ? 0 : 1;
5026     for (unsigned j = 0; j < NumElts; j += 2) {
5027       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5028           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5029         return false;
5030     }
5031   }
5032
5033   if (M.size() == NumElts*2)
5034     WhichResult = 0;
5035
5036   return true;
5037 }
5038
5039 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5040 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5041 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5042 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5043   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5044   if (EltSz == 64)
5045     return false;
5046
5047   unsigned NumElts = VT.getVectorNumElements();
5048   if (M.size() != NumElts && M.size() != NumElts*2)
5049     return false;
5050
5051   for (unsigned i = 0; i < M.size(); i += NumElts) {
5052     WhichResult = M[i] == 0 ? 0 : 1;
5053     for (unsigned j = 0; j < NumElts; j += 2) {
5054       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5055           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5056         return false;
5057     }
5058   }
5059
5060   if (M.size() == NumElts*2)
5061     WhichResult = 0;
5062
5063   return true;
5064 }
5065
5066 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5067 // that the mask elements are either all even and in steps of size 2 or all odd
5068 // and in steps of size 2.
5069 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5070 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5071 //  v2={e,f,g,h}
5072 // Requires similar checks to that of isVTRNMask with
5073 // respect the how results are returned.
5074 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5075   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5076   if (EltSz == 64)
5077     return false;
5078
5079   unsigned NumElts = VT.getVectorNumElements();
5080   if (M.size() != NumElts && M.size() != NumElts*2)
5081     return false;
5082
5083   for (unsigned i = 0; i < M.size(); i += NumElts) {
5084     WhichResult = M[i] == 0 ? 0 : 1;
5085     for (unsigned j = 0; j < NumElts; ++j) {
5086       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5087         return false;
5088     }
5089   }
5090
5091   if (M.size() == NumElts*2)
5092     WhichResult = 0;
5093
5094   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5095   if (VT.is64BitVector() && EltSz == 32)
5096     return false;
5097
5098   return true;
5099 }
5100
5101 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5102 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5103 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5104 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5105   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5106   if (EltSz == 64)
5107     return false;
5108
5109   unsigned NumElts = VT.getVectorNumElements();
5110   if (M.size() != NumElts && M.size() != NumElts*2)
5111     return false;
5112
5113   unsigned Half = NumElts / 2;
5114   for (unsigned i = 0; i < M.size(); i += NumElts) {
5115     WhichResult = M[i] == 0 ? 0 : 1;
5116     for (unsigned j = 0; j < NumElts; j += Half) {
5117       unsigned Idx = WhichResult;
5118       for (unsigned k = 0; k < Half; ++k) {
5119         int MIdx = M[i + j + k];
5120         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5121           return false;
5122         Idx += 2;
5123       }
5124     }
5125   }
5126
5127   if (M.size() == NumElts*2)
5128     WhichResult = 0;
5129
5130   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5131   if (VT.is64BitVector() && EltSz == 32)
5132     return false;
5133
5134   return true;
5135 }
5136
5137 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5138 // that pairs of elements of the shufflemask represent the same index in each
5139 // vector incrementing sequentially through the vectors.
5140 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5141 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5142 //  v2={e,f,g,h}
5143 // Requires similar checks to that of isVTRNMask with respect the how results
5144 // are returned.
5145 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5146   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5147   if (EltSz == 64)
5148     return false;
5149
5150   unsigned NumElts = VT.getVectorNumElements();
5151   if (M.size() != NumElts && M.size() != NumElts*2)
5152     return false;
5153
5154   for (unsigned i = 0; i < M.size(); i += NumElts) {
5155     WhichResult = M[i] == 0 ? 0 : 1;
5156     unsigned Idx = WhichResult * NumElts / 2;
5157     for (unsigned j = 0; j < NumElts; j += 2) {
5158       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5159           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5160         return false;
5161       Idx += 1;
5162     }
5163   }
5164
5165   if (M.size() == NumElts*2)
5166     WhichResult = 0;
5167
5168   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5169   if (VT.is64BitVector() && EltSz == 32)
5170     return false;
5171
5172   return true;
5173 }
5174
5175 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5176 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5177 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5178 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5179   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5180   if (EltSz == 64)
5181     return false;
5182
5183   unsigned NumElts = VT.getVectorNumElements();
5184   if (M.size() != NumElts && M.size() != NumElts*2)
5185     return false;
5186
5187   for (unsigned i = 0; i < M.size(); i += NumElts) {
5188     WhichResult = M[i] == 0 ? 0 : 1;
5189     unsigned Idx = WhichResult * NumElts / 2;
5190     for (unsigned j = 0; j < NumElts; j += 2) {
5191       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5192           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5193         return false;
5194       Idx += 1;
5195     }
5196   }
5197
5198   if (M.size() == NumElts*2)
5199     WhichResult = 0;
5200
5201   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5202   if (VT.is64BitVector() && EltSz == 32)
5203     return false;
5204
5205   return true;
5206 }
5207
5208 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5209 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5210 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5211                                            unsigned &WhichResult,
5212                                            bool &isV_UNDEF) {
5213   isV_UNDEF = false;
5214   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5215     return ARMISD::VTRN;
5216   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5217     return ARMISD::VUZP;
5218   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5219     return ARMISD::VZIP;
5220
5221   isV_UNDEF = true;
5222   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5223     return ARMISD::VTRN;
5224   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5225     return ARMISD::VUZP;
5226   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5227     return ARMISD::VZIP;
5228
5229   return 0;
5230 }
5231
5232 /// \return true if this is a reverse operation on an vector.
5233 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5234   unsigned NumElts = VT.getVectorNumElements();
5235   // Make sure the mask has the right size.
5236   if (NumElts != M.size())
5237       return false;
5238
5239   // Look for <15, ..., 3, -1, 1, 0>.
5240   for (unsigned i = 0; i != NumElts; ++i)
5241     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5242       return false;
5243
5244   return true;
5245 }
5246
5247 // If N is an integer constant that can be moved into a register in one
5248 // instruction, return an SDValue of such a constant (will become a MOV
5249 // instruction).  Otherwise return null.
5250 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5251                                      const ARMSubtarget *ST, SDLoc dl) {
5252   uint64_t Val;
5253   if (!isa<ConstantSDNode>(N))
5254     return SDValue();
5255   Val = cast<ConstantSDNode>(N)->getZExtValue();
5256
5257   if (ST->isThumb1Only()) {
5258     if (Val <= 255 || ~Val <= 255)
5259       return DAG.getConstant(Val, dl, MVT::i32);
5260   } else {
5261     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5262       return DAG.getConstant(Val, dl, MVT::i32);
5263   }
5264   return SDValue();
5265 }
5266
5267 // If this is a case we can't handle, return null and let the default
5268 // expansion code take care of it.
5269 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5270                                              const ARMSubtarget *ST) const {
5271   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5272   SDLoc dl(Op);
5273   EVT VT = Op.getValueType();
5274
5275   APInt SplatBits, SplatUndef;
5276   unsigned SplatBitSize;
5277   bool HasAnyUndefs;
5278   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5279     if (SplatBitSize <= 64) {
5280       // Check if an immediate VMOV works.
5281       EVT VmovVT;
5282       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5283                                       SplatUndef.getZExtValue(), SplatBitSize,
5284                                       DAG, dl, VmovVT, VT.is128BitVector(),
5285                                       VMOVModImm);
5286       if (Val.getNode()) {
5287         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5288         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5289       }
5290
5291       // Try an immediate VMVN.
5292       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5293       Val = isNEONModifiedImm(NegatedImm,
5294                                       SplatUndef.getZExtValue(), SplatBitSize,
5295                                       DAG, dl, VmovVT, VT.is128BitVector(),
5296                                       VMVNModImm);
5297       if (Val.getNode()) {
5298         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5299         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5300       }
5301
5302       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5303       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5304         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5305         if (ImmVal != -1) {
5306           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5307           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5308         }
5309       }
5310     }
5311   }
5312
5313   // Scan through the operands to see if only one value is used.
5314   //
5315   // As an optimisation, even if more than one value is used it may be more
5316   // profitable to splat with one value then change some lanes.
5317   //
5318   // Heuristically we decide to do this if the vector has a "dominant" value,
5319   // defined as splatted to more than half of the lanes.
5320   unsigned NumElts = VT.getVectorNumElements();
5321   bool isOnlyLowElement = true;
5322   bool usesOnlyOneValue = true;
5323   bool hasDominantValue = false;
5324   bool isConstant = true;
5325
5326   // Map of the number of times a particular SDValue appears in the
5327   // element list.
5328   DenseMap<SDValue, unsigned> ValueCounts;
5329   SDValue Value;
5330   for (unsigned i = 0; i < NumElts; ++i) {
5331     SDValue V = Op.getOperand(i);
5332     if (V.getOpcode() == ISD::UNDEF)
5333       continue;
5334     if (i > 0)
5335       isOnlyLowElement = false;
5336     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5337       isConstant = false;
5338
5339     ValueCounts.insert(std::make_pair(V, 0));
5340     unsigned &Count = ValueCounts[V];
5341
5342     // Is this value dominant? (takes up more than half of the lanes)
5343     if (++Count > (NumElts / 2)) {
5344       hasDominantValue = true;
5345       Value = V;
5346     }
5347   }
5348   if (ValueCounts.size() != 1)
5349     usesOnlyOneValue = false;
5350   if (!Value.getNode() && ValueCounts.size() > 0)
5351     Value = ValueCounts.begin()->first;
5352
5353   if (ValueCounts.size() == 0)
5354     return DAG.getUNDEF(VT);
5355
5356   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5357   // Keep going if we are hitting this case.
5358   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5359     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5360
5361   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5362
5363   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5364   // i32 and try again.
5365   if (hasDominantValue && EltSize <= 32) {
5366     if (!isConstant) {
5367       SDValue N;
5368
5369       // If we are VDUPing a value that comes directly from a vector, that will
5370       // cause an unnecessary move to and from a GPR, where instead we could
5371       // just use VDUPLANE. We can only do this if the lane being extracted
5372       // is at a constant index, as the VDUP from lane instructions only have
5373       // constant-index forms.
5374       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5375           isa<ConstantSDNode>(Value->getOperand(1))) {
5376         // We need to create a new undef vector to use for the VDUPLANE if the
5377         // size of the vector from which we get the value is different than the
5378         // size of the vector that we need to create. We will insert the element
5379         // such that the register coalescer will remove unnecessary copies.
5380         if (VT != Value->getOperand(0).getValueType()) {
5381           ConstantSDNode *constIndex;
5382           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5383           assert(constIndex && "The index is not a constant!");
5384           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5385                              VT.getVectorNumElements();
5386           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5387                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5388                         Value, DAG.getConstant(index, dl, MVT::i32)),
5389                            DAG.getConstant(index, dl, MVT::i32));
5390         } else
5391           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5392                         Value->getOperand(0), Value->getOperand(1));
5393       } else
5394         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5395
5396       if (!usesOnlyOneValue) {
5397         // The dominant value was splatted as 'N', but we now have to insert
5398         // all differing elements.
5399         for (unsigned I = 0; I < NumElts; ++I) {
5400           if (Op.getOperand(I) == Value)
5401             continue;
5402           SmallVector<SDValue, 3> Ops;
5403           Ops.push_back(N);
5404           Ops.push_back(Op.getOperand(I));
5405           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5406           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5407         }
5408       }
5409       return N;
5410     }
5411     if (VT.getVectorElementType().isFloatingPoint()) {
5412       SmallVector<SDValue, 8> Ops;
5413       for (unsigned i = 0; i < NumElts; ++i)
5414         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5415                                   Op.getOperand(i)));
5416       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5417       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5418       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5419       if (Val.getNode())
5420         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5421     }
5422     if (usesOnlyOneValue) {
5423       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5424       if (isConstant && Val.getNode())
5425         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5426     }
5427   }
5428
5429   // If all elements are constants and the case above didn't get hit, fall back
5430   // to the default expansion, which will generate a load from the constant
5431   // pool.
5432   if (isConstant)
5433     return SDValue();
5434
5435   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5436   if (NumElts >= 4) {
5437     SDValue shuffle = ReconstructShuffle(Op, DAG);
5438     if (shuffle != SDValue())
5439       return shuffle;
5440   }
5441
5442   // Vectors with 32- or 64-bit elements can be built by directly assigning
5443   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5444   // will be legalized.
5445   if (EltSize >= 32) {
5446     // Do the expansion with floating-point types, since that is what the VFP
5447     // registers are defined to use, and since i64 is not legal.
5448     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5449     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5450     SmallVector<SDValue, 8> Ops;
5451     for (unsigned i = 0; i < NumElts; ++i)
5452       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5453     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5454     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5455   }
5456
5457   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5458   // know the default expansion would otherwise fall back on something even
5459   // worse. For a vector with one or two non-undef values, that's
5460   // scalar_to_vector for the elements followed by a shuffle (provided the
5461   // shuffle is valid for the target) and materialization element by element
5462   // on the stack followed by a load for everything else.
5463   if (!isConstant && !usesOnlyOneValue) {
5464     SDValue Vec = DAG.getUNDEF(VT);
5465     for (unsigned i = 0 ; i < NumElts; ++i) {
5466       SDValue V = Op.getOperand(i);
5467       if (V.getOpcode() == ISD::UNDEF)
5468         continue;
5469       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5470       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5471     }
5472     return Vec;
5473   }
5474
5475   return SDValue();
5476 }
5477
5478 /// getExtFactor - Determine the adjustment factor for the position when
5479 /// generating an "extract from vector registers" instruction.
5480 static unsigned getExtFactor(SDValue &V) {
5481   EVT EltType = V.getValueType().getVectorElementType();
5482   return EltType.getSizeInBits() / 8;
5483 }
5484
5485 // Gather data to see if the operation can be modelled as a
5486 // shuffle in combination with VEXTs.
5487 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5488                                               SelectionDAG &DAG) const {
5489   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5490   SDLoc dl(Op);
5491   EVT VT = Op.getValueType();
5492   unsigned NumElts = VT.getVectorNumElements();
5493
5494   struct ShuffleSourceInfo {
5495     SDValue Vec;
5496     unsigned MinElt;
5497     unsigned MaxElt;
5498
5499     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5500     // be compatible with the shuffle we intend to construct. As a result
5501     // ShuffleVec will be some sliding window into the original Vec.
5502     SDValue ShuffleVec;
5503
5504     // Code should guarantee that element i in Vec starts at element "WindowBase
5505     // + i * WindowScale in ShuffleVec".
5506     int WindowBase;
5507     int WindowScale;
5508
5509     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5510     ShuffleSourceInfo(SDValue Vec)
5511         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5512           WindowScale(1) {}
5513   };
5514
5515   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5516   // node.
5517   SmallVector<ShuffleSourceInfo, 2> Sources;
5518   for (unsigned i = 0; i < NumElts; ++i) {
5519     SDValue V = Op.getOperand(i);
5520     if (V.getOpcode() == ISD::UNDEF)
5521       continue;
5522     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5523       // A shuffle can only come from building a vector from various
5524       // elements of other vectors.
5525       return SDValue();
5526     }
5527
5528     // Add this element source to the list if it's not already there.
5529     SDValue SourceVec = V.getOperand(0);
5530     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5531     if (Source == Sources.end())
5532       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5533
5534     // Update the minimum and maximum lane number seen.
5535     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5536     Source->MinElt = std::min(Source->MinElt, EltNo);
5537     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5538   }
5539
5540   // Currently only do something sane when at most two source vectors
5541   // are involved.
5542   if (Sources.size() > 2)
5543     return SDValue();
5544
5545   // Find out the smallest element size among result and two sources, and use
5546   // it as element size to build the shuffle_vector.
5547   EVT SmallestEltTy = VT.getVectorElementType();
5548   for (auto &Source : Sources) {
5549     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5550     if (SrcEltTy.bitsLT(SmallestEltTy))
5551       SmallestEltTy = SrcEltTy;
5552   }
5553   unsigned ResMultiplier =
5554       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5555   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5556   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5557
5558   // If the source vector is too wide or too narrow, we may nevertheless be able
5559   // to construct a compatible shuffle either by concatenating it with UNDEF or
5560   // extracting a suitable range of elements.
5561   for (auto &Src : Sources) {
5562     EVT SrcVT = Src.ShuffleVec.getValueType();
5563
5564     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5565       continue;
5566
5567     // This stage of the search produces a source with the same element type as
5568     // the original, but with a total width matching the BUILD_VECTOR output.
5569     EVT EltVT = SrcVT.getVectorElementType();
5570     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5571     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5572
5573     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5574       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5575         return SDValue();
5576       // We can pad out the smaller vector for free, so if it's part of a
5577       // shuffle...
5578       Src.ShuffleVec =
5579           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5580                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5581       continue;
5582     }
5583
5584     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5585       return SDValue();
5586
5587     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5588       // Span too large for a VEXT to cope
5589       return SDValue();
5590     }
5591
5592     if (Src.MinElt >= NumSrcElts) {
5593       // The extraction can just take the second half
5594       Src.ShuffleVec =
5595           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5596                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5597       Src.WindowBase = -NumSrcElts;
5598     } else if (Src.MaxElt < NumSrcElts) {
5599       // The extraction can just take the first half
5600       Src.ShuffleVec =
5601           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5602                       DAG.getConstant(0, dl, MVT::i32));
5603     } else {
5604       // An actual VEXT is needed
5605       SDValue VEXTSrc1 =
5606           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5607                       DAG.getConstant(0, dl, MVT::i32));
5608       SDValue VEXTSrc2 =
5609           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5610                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5611       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5612
5613       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5614                                    VEXTSrc2,
5615                                    DAG.getConstant(Imm, dl, MVT::i32));
5616       Src.WindowBase = -Src.MinElt;
5617     }
5618   }
5619
5620   // Another possible incompatibility occurs from the vector element types. We
5621   // can fix this by bitcasting the source vectors to the same type we intend
5622   // for the shuffle.
5623   for (auto &Src : Sources) {
5624     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5625     if (SrcEltTy == SmallestEltTy)
5626       continue;
5627     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5628     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5629     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5630     Src.WindowBase *= Src.WindowScale;
5631   }
5632
5633   // Final sanity check before we try to actually produce a shuffle.
5634   DEBUG(
5635     for (auto Src : Sources)
5636       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5637   );
5638
5639   // The stars all align, our next step is to produce the mask for the shuffle.
5640   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5641   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5642   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5643     SDValue Entry = Op.getOperand(i);
5644     if (Entry.getOpcode() == ISD::UNDEF)
5645       continue;
5646
5647     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5648     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5649
5650     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5651     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5652     // segment.
5653     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5654     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5655                                VT.getVectorElementType().getSizeInBits());
5656     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5657
5658     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5659     // starting at the appropriate offset.
5660     int *LaneMask = &Mask[i * ResMultiplier];
5661
5662     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5663     ExtractBase += NumElts * (Src - Sources.begin());
5664     for (int j = 0; j < LanesDefined; ++j)
5665       LaneMask[j] = ExtractBase + j;
5666   }
5667
5668   // Final check before we try to produce nonsense...
5669   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5670     return SDValue();
5671
5672   // We can't handle more than two sources. This should have already
5673   // been checked before this point.
5674   assert(Sources.size() <= 2 && "Too many sources!");
5675
5676   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5677   for (unsigned i = 0; i < Sources.size(); ++i)
5678     ShuffleOps[i] = Sources[i].ShuffleVec;
5679
5680   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5681                                          ShuffleOps[1], &Mask[0]);
5682   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5683 }
5684
5685 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5686 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5687 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5688 /// are assumed to be legal.
5689 bool
5690 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5691                                       EVT VT) const {
5692   if (VT.getVectorNumElements() == 4 &&
5693       (VT.is128BitVector() || VT.is64BitVector())) {
5694     unsigned PFIndexes[4];
5695     for (unsigned i = 0; i != 4; ++i) {
5696       if (M[i] < 0)
5697         PFIndexes[i] = 8;
5698       else
5699         PFIndexes[i] = M[i];
5700     }
5701
5702     // Compute the index in the perfect shuffle table.
5703     unsigned PFTableIndex =
5704       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5705     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5706     unsigned Cost = (PFEntry >> 30);
5707
5708     if (Cost <= 4)
5709       return true;
5710   }
5711
5712   bool ReverseVEXT, isV_UNDEF;
5713   unsigned Imm, WhichResult;
5714
5715   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5716   return (EltSize >= 32 ||
5717           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5718           isVREVMask(M, VT, 64) ||
5719           isVREVMask(M, VT, 32) ||
5720           isVREVMask(M, VT, 16) ||
5721           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5722           isVTBLMask(M, VT) ||
5723           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5724           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5725 }
5726
5727 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5728 /// the specified operations to build the shuffle.
5729 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5730                                       SDValue RHS, SelectionDAG &DAG,
5731                                       SDLoc dl) {
5732   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5733   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5734   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5735
5736   enum {
5737     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5738     OP_VREV,
5739     OP_VDUP0,
5740     OP_VDUP1,
5741     OP_VDUP2,
5742     OP_VDUP3,
5743     OP_VEXT1,
5744     OP_VEXT2,
5745     OP_VEXT3,
5746     OP_VUZPL, // VUZP, left result
5747     OP_VUZPR, // VUZP, right result
5748     OP_VZIPL, // VZIP, left result
5749     OP_VZIPR, // VZIP, right result
5750     OP_VTRNL, // VTRN, left result
5751     OP_VTRNR  // VTRN, right result
5752   };
5753
5754   if (OpNum == OP_COPY) {
5755     if (LHSID == (1*9+2)*9+3) return LHS;
5756     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5757     return RHS;
5758   }
5759
5760   SDValue OpLHS, OpRHS;
5761   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5762   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5763   EVT VT = OpLHS.getValueType();
5764
5765   switch (OpNum) {
5766   default: llvm_unreachable("Unknown shuffle opcode!");
5767   case OP_VREV:
5768     // VREV divides the vector in half and swaps within the half.
5769     if (VT.getVectorElementType() == MVT::i32 ||
5770         VT.getVectorElementType() == MVT::f32)
5771       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5772     // vrev <4 x i16> -> VREV32
5773     if (VT.getVectorElementType() == MVT::i16)
5774       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5775     // vrev <4 x i8> -> VREV16
5776     assert(VT.getVectorElementType() == MVT::i8);
5777     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5778   case OP_VDUP0:
5779   case OP_VDUP1:
5780   case OP_VDUP2:
5781   case OP_VDUP3:
5782     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5783                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5784   case OP_VEXT1:
5785   case OP_VEXT2:
5786   case OP_VEXT3:
5787     return DAG.getNode(ARMISD::VEXT, dl, VT,
5788                        OpLHS, OpRHS,
5789                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5790   case OP_VUZPL:
5791   case OP_VUZPR:
5792     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5793                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5794   case OP_VZIPL:
5795   case OP_VZIPR:
5796     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5797                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5798   case OP_VTRNL:
5799   case OP_VTRNR:
5800     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5801                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5802   }
5803 }
5804
5805 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5806                                        ArrayRef<int> ShuffleMask,
5807                                        SelectionDAG &DAG) {
5808   // Check to see if we can use the VTBL instruction.
5809   SDValue V1 = Op.getOperand(0);
5810   SDValue V2 = Op.getOperand(1);
5811   SDLoc DL(Op);
5812
5813   SmallVector<SDValue, 8> VTBLMask;
5814   for (ArrayRef<int>::iterator
5815          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5816     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5817
5818   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5819     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5820                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5821
5822   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5823                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5824 }
5825
5826 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5827                                                       SelectionDAG &DAG) {
5828   SDLoc DL(Op);
5829   SDValue OpLHS = Op.getOperand(0);
5830   EVT VT = OpLHS.getValueType();
5831
5832   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5833          "Expect an v8i16/v16i8 type");
5834   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5835   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5836   // extract the first 8 bytes into the top double word and the last 8 bytes
5837   // into the bottom double word. The v8i16 case is similar.
5838   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5839   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5840                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5841 }
5842
5843 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5844   SDValue V1 = Op.getOperand(0);
5845   SDValue V2 = Op.getOperand(1);
5846   SDLoc dl(Op);
5847   EVT VT = Op.getValueType();
5848   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5849
5850   // Convert shuffles that are directly supported on NEON to target-specific
5851   // DAG nodes, instead of keeping them as shuffles and matching them again
5852   // during code selection.  This is more efficient and avoids the possibility
5853   // of inconsistencies between legalization and selection.
5854   // FIXME: floating-point vectors should be canonicalized to integer vectors
5855   // of the same time so that they get CSEd properly.
5856   ArrayRef<int> ShuffleMask = SVN->getMask();
5857
5858   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5859   if (EltSize <= 32) {
5860     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5861       int Lane = SVN->getSplatIndex();
5862       // If this is undef splat, generate it via "just" vdup, if possible.
5863       if (Lane == -1) Lane = 0;
5864
5865       // Test if V1 is a SCALAR_TO_VECTOR.
5866       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5867         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5868       }
5869       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5870       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5871       // reaches it).
5872       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5873           !isa<ConstantSDNode>(V1.getOperand(0))) {
5874         bool IsScalarToVector = true;
5875         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5876           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5877             IsScalarToVector = false;
5878             break;
5879           }
5880         if (IsScalarToVector)
5881           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5882       }
5883       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5884                          DAG.getConstant(Lane, dl, MVT::i32));
5885     }
5886
5887     bool ReverseVEXT;
5888     unsigned Imm;
5889     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5890       if (ReverseVEXT)
5891         std::swap(V1, V2);
5892       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5893                          DAG.getConstant(Imm, dl, MVT::i32));
5894     }
5895
5896     if (isVREVMask(ShuffleMask, VT, 64))
5897       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5898     if (isVREVMask(ShuffleMask, VT, 32))
5899       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5900     if (isVREVMask(ShuffleMask, VT, 16))
5901       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5902
5903     if (V2->getOpcode() == ISD::UNDEF &&
5904         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5905       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5906                          DAG.getConstant(Imm, dl, MVT::i32));
5907     }
5908
5909     // Check for Neon shuffles that modify both input vectors in place.
5910     // If both results are used, i.e., if there are two shuffles with the same
5911     // source operands and with masks corresponding to both results of one of
5912     // these operations, DAG memoization will ensure that a single node is
5913     // used for both shuffles.
5914     unsigned WhichResult;
5915     bool isV_UNDEF;
5916     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5917             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5918       if (isV_UNDEF)
5919         V2 = V1;
5920       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5921           .getValue(WhichResult);
5922     }
5923
5924     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5925     // shuffles that produce a result larger than their operands with:
5926     //   shuffle(concat(v1, undef), concat(v2, undef))
5927     // ->
5928     //   shuffle(concat(v1, v2), undef)
5929     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5930     //
5931     // This is useful in the general case, but there are special cases where
5932     // native shuffles produce larger results: the two-result ops.
5933     //
5934     // Look through the concat when lowering them:
5935     //   shuffle(concat(v1, v2), undef)
5936     // ->
5937     //   concat(VZIP(v1, v2):0, :1)
5938     //
5939     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5940         V2->getOpcode() == ISD::UNDEF) {
5941       SDValue SubV1 = V1->getOperand(0);
5942       SDValue SubV2 = V1->getOperand(1);
5943       EVT SubVT = SubV1.getValueType();
5944
5945       // We expect these to have been canonicalized to -1.
5946       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5947         return i < (int)VT.getVectorNumElements();
5948       }) && "Unexpected shuffle index into UNDEF operand!");
5949
5950       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5951               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5952         if (isV_UNDEF)
5953           SubV2 = SubV1;
5954         assert((WhichResult == 0) &&
5955                "In-place shuffle of concat can only have one result!");
5956         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5957                                   SubV1, SubV2);
5958         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5959                            Res.getValue(1));
5960       }
5961     }
5962   }
5963
5964   // If the shuffle is not directly supported and it has 4 elements, use
5965   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5966   unsigned NumElts = VT.getVectorNumElements();
5967   if (NumElts == 4) {
5968     unsigned PFIndexes[4];
5969     for (unsigned i = 0; i != 4; ++i) {
5970       if (ShuffleMask[i] < 0)
5971         PFIndexes[i] = 8;
5972       else
5973         PFIndexes[i] = ShuffleMask[i];
5974     }
5975
5976     // Compute the index in the perfect shuffle table.
5977     unsigned PFTableIndex =
5978       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5979     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5980     unsigned Cost = (PFEntry >> 30);
5981
5982     if (Cost <= 4)
5983       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5984   }
5985
5986   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5987   if (EltSize >= 32) {
5988     // Do the expansion with floating-point types, since that is what the VFP
5989     // registers are defined to use, and since i64 is not legal.
5990     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5991     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5992     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5993     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5994     SmallVector<SDValue, 8> Ops;
5995     for (unsigned i = 0; i < NumElts; ++i) {
5996       if (ShuffleMask[i] < 0)
5997         Ops.push_back(DAG.getUNDEF(EltVT));
5998       else
5999         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6000                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6001                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6002                                                   dl, MVT::i32)));
6003     }
6004     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6005     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6006   }
6007
6008   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6009     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6010
6011   if (VT == MVT::v8i8) {
6012     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6013     if (NewOp.getNode())
6014       return NewOp;
6015   }
6016
6017   return SDValue();
6018 }
6019
6020 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6021   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6022   SDValue Lane = Op.getOperand(2);
6023   if (!isa<ConstantSDNode>(Lane))
6024     return SDValue();
6025
6026   return Op;
6027 }
6028
6029 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6030   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6031   SDValue Lane = Op.getOperand(1);
6032   if (!isa<ConstantSDNode>(Lane))
6033     return SDValue();
6034
6035   SDValue Vec = Op.getOperand(0);
6036   if (Op.getValueType() == MVT::i32 &&
6037       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6038     SDLoc dl(Op);
6039     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6040   }
6041
6042   return Op;
6043 }
6044
6045 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6046   // The only time a CONCAT_VECTORS operation can have legal types is when
6047   // two 64-bit vectors are concatenated to a 128-bit vector.
6048   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6049          "unexpected CONCAT_VECTORS");
6050   SDLoc dl(Op);
6051   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6052   SDValue Op0 = Op.getOperand(0);
6053   SDValue Op1 = Op.getOperand(1);
6054   if (Op0.getOpcode() != ISD::UNDEF)
6055     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6056                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6057                       DAG.getIntPtrConstant(0, dl));
6058   if (Op1.getOpcode() != ISD::UNDEF)
6059     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6060                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6061                       DAG.getIntPtrConstant(1, dl));
6062   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6063 }
6064
6065 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6066 /// element has been zero/sign-extended, depending on the isSigned parameter,
6067 /// from an integer type half its size.
6068 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6069                                    bool isSigned) {
6070   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6071   EVT VT = N->getValueType(0);
6072   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6073     SDNode *BVN = N->getOperand(0).getNode();
6074     if (BVN->getValueType(0) != MVT::v4i32 ||
6075         BVN->getOpcode() != ISD::BUILD_VECTOR)
6076       return false;
6077     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6078     unsigned HiElt = 1 - LoElt;
6079     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6080     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6081     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6082     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6083     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6084       return false;
6085     if (isSigned) {
6086       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6087           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6088         return true;
6089     } else {
6090       if (Hi0->isNullValue() && Hi1->isNullValue())
6091         return true;
6092     }
6093     return false;
6094   }
6095
6096   if (N->getOpcode() != ISD::BUILD_VECTOR)
6097     return false;
6098
6099   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6100     SDNode *Elt = N->getOperand(i).getNode();
6101     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6102       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6103       unsigned HalfSize = EltSize / 2;
6104       if (isSigned) {
6105         if (!isIntN(HalfSize, C->getSExtValue()))
6106           return false;
6107       } else {
6108         if (!isUIntN(HalfSize, C->getZExtValue()))
6109           return false;
6110       }
6111       continue;
6112     }
6113     return false;
6114   }
6115
6116   return true;
6117 }
6118
6119 /// isSignExtended - Check if a node is a vector value that is sign-extended
6120 /// or a constant BUILD_VECTOR with sign-extended elements.
6121 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6122   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6123     return true;
6124   if (isExtendedBUILD_VECTOR(N, DAG, true))
6125     return true;
6126   return false;
6127 }
6128
6129 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6130 /// or a constant BUILD_VECTOR with zero-extended elements.
6131 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6132   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6133     return true;
6134   if (isExtendedBUILD_VECTOR(N, DAG, false))
6135     return true;
6136   return false;
6137 }
6138
6139 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6140   if (OrigVT.getSizeInBits() >= 64)
6141     return OrigVT;
6142
6143   assert(OrigVT.isSimple() && "Expecting a simple value type");
6144
6145   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6146   switch (OrigSimpleTy) {
6147   default: llvm_unreachable("Unexpected Vector Type");
6148   case MVT::v2i8:
6149   case MVT::v2i16:
6150      return MVT::v2i32;
6151   case MVT::v4i8:
6152     return  MVT::v4i16;
6153   }
6154 }
6155
6156 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6157 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6158 /// We insert the required extension here to get the vector to fill a D register.
6159 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6160                                             const EVT &OrigTy,
6161                                             const EVT &ExtTy,
6162                                             unsigned ExtOpcode) {
6163   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6164   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6165   // 64-bits we need to insert a new extension so that it will be 64-bits.
6166   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6167   if (OrigTy.getSizeInBits() >= 64)
6168     return N;
6169
6170   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6171   EVT NewVT = getExtensionTo64Bits(OrigTy);
6172
6173   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6174 }
6175
6176 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6177 /// does not do any sign/zero extension. If the original vector is less
6178 /// than 64 bits, an appropriate extension will be added after the load to
6179 /// reach a total size of 64 bits. We have to add the extension separately
6180 /// because ARM does not have a sign/zero extending load for vectors.
6181 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6182   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6183
6184   // The load already has the right type.
6185   if (ExtendedTy == LD->getMemoryVT())
6186     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6187                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6188                 LD->isNonTemporal(), LD->isInvariant(),
6189                 LD->getAlignment());
6190
6191   // We need to create a zextload/sextload. We cannot just create a load
6192   // followed by a zext/zext node because LowerMUL is also run during normal
6193   // operation legalization where we can't create illegal types.
6194   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6195                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6196                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6197                         LD->isNonTemporal(), LD->getAlignment());
6198 }
6199
6200 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6201 /// extending load, or BUILD_VECTOR with extended elements, return the
6202 /// unextended value. The unextended vector should be 64 bits so that it can
6203 /// be used as an operand to a VMULL instruction. If the original vector size
6204 /// before extension is less than 64 bits we add a an extension to resize
6205 /// the vector to 64 bits.
6206 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6207   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6208     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6209                                         N->getOperand(0)->getValueType(0),
6210                                         N->getValueType(0),
6211                                         N->getOpcode());
6212
6213   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6214     return SkipLoadExtensionForVMULL(LD, DAG);
6215
6216   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6217   // have been legalized as a BITCAST from v4i32.
6218   if (N->getOpcode() == ISD::BITCAST) {
6219     SDNode *BVN = N->getOperand(0).getNode();
6220     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6221            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6222     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6223     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6224                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6225   }
6226   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6227   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6228   EVT VT = N->getValueType(0);
6229   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6230   unsigned NumElts = VT.getVectorNumElements();
6231   MVT TruncVT = MVT::getIntegerVT(EltSize);
6232   SmallVector<SDValue, 8> Ops;
6233   SDLoc dl(N);
6234   for (unsigned i = 0; i != NumElts; ++i) {
6235     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6236     const APInt &CInt = C->getAPIntValue();
6237     // Element types smaller than 32 bits are not legal, so use i32 elements.
6238     // The values are implicitly truncated so sext vs. zext doesn't matter.
6239     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6240   }
6241   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6242                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6243 }
6244
6245 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6246   unsigned Opcode = N->getOpcode();
6247   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6248     SDNode *N0 = N->getOperand(0).getNode();
6249     SDNode *N1 = N->getOperand(1).getNode();
6250     return N0->hasOneUse() && N1->hasOneUse() &&
6251       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6252   }
6253   return false;
6254 }
6255
6256 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6257   unsigned Opcode = N->getOpcode();
6258   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6259     SDNode *N0 = N->getOperand(0).getNode();
6260     SDNode *N1 = N->getOperand(1).getNode();
6261     return N0->hasOneUse() && N1->hasOneUse() &&
6262       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6263   }
6264   return false;
6265 }
6266
6267 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6268   // Multiplications are only custom-lowered for 128-bit vectors so that
6269   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6270   EVT VT = Op.getValueType();
6271   assert(VT.is128BitVector() && VT.isInteger() &&
6272          "unexpected type for custom-lowering ISD::MUL");
6273   SDNode *N0 = Op.getOperand(0).getNode();
6274   SDNode *N1 = Op.getOperand(1).getNode();
6275   unsigned NewOpc = 0;
6276   bool isMLA = false;
6277   bool isN0SExt = isSignExtended(N0, DAG);
6278   bool isN1SExt = isSignExtended(N1, DAG);
6279   if (isN0SExt && isN1SExt)
6280     NewOpc = ARMISD::VMULLs;
6281   else {
6282     bool isN0ZExt = isZeroExtended(N0, DAG);
6283     bool isN1ZExt = isZeroExtended(N1, DAG);
6284     if (isN0ZExt && isN1ZExt)
6285       NewOpc = ARMISD::VMULLu;
6286     else if (isN1SExt || isN1ZExt) {
6287       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6288       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6289       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6290         NewOpc = ARMISD::VMULLs;
6291         isMLA = true;
6292       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6293         NewOpc = ARMISD::VMULLu;
6294         isMLA = true;
6295       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6296         std::swap(N0, N1);
6297         NewOpc = ARMISD::VMULLu;
6298         isMLA = true;
6299       }
6300     }
6301
6302     if (!NewOpc) {
6303       if (VT == MVT::v2i64)
6304         // Fall through to expand this.  It is not legal.
6305         return SDValue();
6306       else
6307         // Other vector multiplications are legal.
6308         return Op;
6309     }
6310   }
6311
6312   // Legalize to a VMULL instruction.
6313   SDLoc DL(Op);
6314   SDValue Op0;
6315   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6316   if (!isMLA) {
6317     Op0 = SkipExtensionForVMULL(N0, DAG);
6318     assert(Op0.getValueType().is64BitVector() &&
6319            Op1.getValueType().is64BitVector() &&
6320            "unexpected types for extended operands to VMULL");
6321     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6322   }
6323
6324   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6325   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6326   //   vmull q0, d4, d6
6327   //   vmlal q0, d5, d6
6328   // is faster than
6329   //   vaddl q0, d4, d5
6330   //   vmovl q1, d6
6331   //   vmul  q0, q0, q1
6332   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6333   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6334   EVT Op1VT = Op1.getValueType();
6335   return DAG.getNode(N0->getOpcode(), DL, VT,
6336                      DAG.getNode(NewOpc, DL, VT,
6337                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6338                      DAG.getNode(NewOpc, DL, VT,
6339                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6340 }
6341
6342 static SDValue
6343 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6344   // Convert to float
6345   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6346   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6347   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6348   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6349   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6350   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6351   // Get reciprocal estimate.
6352   // float4 recip = vrecpeq_f32(yf);
6353   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6354                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6355                    Y);
6356   // Because char has a smaller range than uchar, we can actually get away
6357   // without any newton steps.  This requires that we use a weird bias
6358   // of 0xb000, however (again, this has been exhaustively tested).
6359   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6360   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6361   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6362   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6363   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6364   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6365   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6366   // Convert back to short.
6367   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6368   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6369   return X;
6370 }
6371
6372 static SDValue
6373 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6374   SDValue N2;
6375   // Convert to float.
6376   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6377   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6378   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6379   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6380   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6381   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6382
6383   // Use reciprocal estimate and one refinement step.
6384   // float4 recip = vrecpeq_f32(yf);
6385   // recip *= vrecpsq_f32(yf, recip);
6386   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6387                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6388                    N1);
6389   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6390                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6391                    N1, N2);
6392   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6393   // Because short has a smaller range than ushort, we can actually get away
6394   // with only a single newton step.  This requires that we use a weird bias
6395   // of 89, however (again, this has been exhaustively tested).
6396   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6397   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6398   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6399   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6400   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6401   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6402   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6403   // Convert back to integer and return.
6404   // return vmovn_s32(vcvt_s32_f32(result));
6405   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6406   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6407   return N0;
6408 }
6409
6410 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6411   EVT VT = Op.getValueType();
6412   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6413          "unexpected type for custom-lowering ISD::SDIV");
6414
6415   SDLoc dl(Op);
6416   SDValue N0 = Op.getOperand(0);
6417   SDValue N1 = Op.getOperand(1);
6418   SDValue N2, N3;
6419
6420   if (VT == MVT::v8i8) {
6421     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6422     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6423
6424     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6425                      DAG.getIntPtrConstant(4, dl));
6426     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6427                      DAG.getIntPtrConstant(4, dl));
6428     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6429                      DAG.getIntPtrConstant(0, dl));
6430     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6431                      DAG.getIntPtrConstant(0, dl));
6432
6433     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6434     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6435
6436     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6437     N0 = LowerCONCAT_VECTORS(N0, DAG);
6438
6439     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6440     return N0;
6441   }
6442   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6443 }
6444
6445 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6446   EVT VT = Op.getValueType();
6447   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6448          "unexpected type for custom-lowering ISD::UDIV");
6449
6450   SDLoc dl(Op);
6451   SDValue N0 = Op.getOperand(0);
6452   SDValue N1 = Op.getOperand(1);
6453   SDValue N2, N3;
6454
6455   if (VT == MVT::v8i8) {
6456     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6457     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6458
6459     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6460                      DAG.getIntPtrConstant(4, dl));
6461     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6462                      DAG.getIntPtrConstant(4, dl));
6463     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6464                      DAG.getIntPtrConstant(0, dl));
6465     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6466                      DAG.getIntPtrConstant(0, dl));
6467
6468     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6469     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6470
6471     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6472     N0 = LowerCONCAT_VECTORS(N0, DAG);
6473
6474     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6475                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6476                                      MVT::i32),
6477                      N0);
6478     return N0;
6479   }
6480
6481   // v4i16 sdiv ... Convert to float.
6482   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6483   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6484   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6485   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6486   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6487   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6488
6489   // Use reciprocal estimate and two refinement steps.
6490   // float4 recip = vrecpeq_f32(yf);
6491   // recip *= vrecpsq_f32(yf, recip);
6492   // recip *= vrecpsq_f32(yf, recip);
6493   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6494                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6495                    BN1);
6496   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6497                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6498                    BN1, N2);
6499   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6500   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6501                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6502                    BN1, N2);
6503   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6504   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6505   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6506   // and that it will never cause us to return an answer too large).
6507   // float4 result = as_float4(as_int4(xf*recip) + 2);
6508   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6509   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6510   N1 = DAG.getConstant(2, dl, MVT::i32);
6511   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6512   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6513   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6514   // Convert back to integer and return.
6515   // return vmovn_u32(vcvt_s32_f32(result));
6516   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6517   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6518   return N0;
6519 }
6520
6521 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6522   EVT VT = Op.getNode()->getValueType(0);
6523   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6524
6525   unsigned Opc;
6526   bool ExtraOp = false;
6527   switch (Op.getOpcode()) {
6528   default: llvm_unreachable("Invalid code");
6529   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6530   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6531   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6532   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6533   }
6534
6535   if (!ExtraOp)
6536     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6537                        Op.getOperand(1));
6538   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6539                      Op.getOperand(1), Op.getOperand(2));
6540 }
6541
6542 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6543   assert(Subtarget->isTargetDarwin());
6544
6545   // For iOS, we want to call an alternative entry point: __sincos_stret,
6546   // return values are passed via sret.
6547   SDLoc dl(Op);
6548   SDValue Arg = Op.getOperand(0);
6549   EVT ArgVT = Arg.getValueType();
6550   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6551   auto PtrVT = getPointerTy(DAG.getDataLayout());
6552
6553   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6554
6555   // Pair of floats / doubles used to pass the result.
6556   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6557
6558   // Create stack object for sret.
6559   auto &DL = DAG.getDataLayout();
6560   const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6561   const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6562   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6563   SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6564
6565   ArgListTy Args;
6566   ArgListEntry Entry;
6567
6568   Entry.Node = SRet;
6569   Entry.Ty = RetTy->getPointerTo();
6570   Entry.isSExt = false;
6571   Entry.isZExt = false;
6572   Entry.isSRet = true;
6573   Args.push_back(Entry);
6574
6575   Entry.Node = Arg;
6576   Entry.Ty = ArgTy;
6577   Entry.isSExt = false;
6578   Entry.isZExt = false;
6579   Args.push_back(Entry);
6580
6581   const char *LibcallName  = (ArgVT == MVT::f64)
6582   ? "__sincos_stret" : "__sincosf_stret";
6583   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6584
6585   TargetLowering::CallLoweringInfo CLI(DAG);
6586   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6587     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6588                std::move(Args), 0)
6589     .setDiscardResult();
6590
6591   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6592
6593   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6594                                 MachinePointerInfo(), false, false, false, 0);
6595
6596   // Address of cos field.
6597   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6598                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6599   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6600                                 MachinePointerInfo(), false, false, false, 0);
6601
6602   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6603   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6604                      LoadSin.getValue(0), LoadCos.getValue(0));
6605 }
6606
6607 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6608   // Monotonic load/store is legal for all targets
6609   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6610     return Op;
6611
6612   // Acquire/Release load/store is not legal for targets without a
6613   // dmb or equivalent available.
6614   return SDValue();
6615 }
6616
6617 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6618                                     SmallVectorImpl<SDValue> &Results,
6619                                     SelectionDAG &DAG,
6620                                     const ARMSubtarget *Subtarget) {
6621   SDLoc DL(N);
6622   SDValue Cycles32, OutChain;
6623
6624   if (Subtarget->hasPerfMon()) {
6625     // Under Power Management extensions, the cycle-count is:
6626     //    mrc p15, #0, <Rt>, c9, c13, #0
6627     SDValue Ops[] = { N->getOperand(0), // Chain
6628                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6629                       DAG.getConstant(15, DL, MVT::i32),
6630                       DAG.getConstant(0, DL, MVT::i32),
6631                       DAG.getConstant(9, DL, MVT::i32),
6632                       DAG.getConstant(13, DL, MVT::i32),
6633                       DAG.getConstant(0, DL, MVT::i32)
6634     };
6635
6636     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6637                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6638     OutChain = Cycles32.getValue(1);
6639   } else {
6640     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6641     // there are older ARM CPUs that have implementation-specific ways of
6642     // obtaining this information (FIXME!).
6643     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6644     OutChain = DAG.getEntryNode();
6645   }
6646
6647
6648   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6649                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6650   Results.push_back(Cycles64);
6651   Results.push_back(OutChain);
6652 }
6653
6654 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6655   switch (Op.getOpcode()) {
6656   default: llvm_unreachable("Don't know how to custom lower this!");
6657   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6658   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6659   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6660   case ISD::GlobalAddress:
6661     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6662     default: llvm_unreachable("unknown object format");
6663     case Triple::COFF:
6664       return LowerGlobalAddressWindows(Op, DAG);
6665     case Triple::ELF:
6666       return LowerGlobalAddressELF(Op, DAG);
6667     case Triple::MachO:
6668       return LowerGlobalAddressDarwin(Op, DAG);
6669     }
6670   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6671   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6672   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6673   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6674   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6675   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6676   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6677   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6678   case ISD::SINT_TO_FP:
6679   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6680   case ISD::FP_TO_SINT:
6681   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6682   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6683   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6684   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6685   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6686   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6687   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6688   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6689   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6690                                                                Subtarget);
6691   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6692   case ISD::SHL:
6693   case ISD::SRL:
6694   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6695   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6696   case ISD::SRL_PARTS:
6697   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6698   case ISD::CTTZ:
6699   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6700   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6701   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6702   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6703   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6704   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6705   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6706   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6707   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6708   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6709   case ISD::MUL:           return LowerMUL(Op, DAG);
6710   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6711   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6712   case ISD::ADDC:
6713   case ISD::ADDE:
6714   case ISD::SUBC:
6715   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6716   case ISD::SADDO:
6717   case ISD::UADDO:
6718   case ISD::SSUBO:
6719   case ISD::USUBO:
6720     return LowerXALUO(Op, DAG);
6721   case ISD::ATOMIC_LOAD:
6722   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6723   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6724   case ISD::SDIVREM:
6725   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6726   case ISD::DYNAMIC_STACKALLOC:
6727     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6728       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6729     llvm_unreachable("Don't know how to custom lower this!");
6730   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6731   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6732   }
6733 }
6734
6735 /// ReplaceNodeResults - Replace the results of node with an illegal result
6736 /// type with new values built out of custom code.
6737 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6738                                            SmallVectorImpl<SDValue>&Results,
6739                                            SelectionDAG &DAG) const {
6740   SDValue Res;
6741   switch (N->getOpcode()) {
6742   default:
6743     llvm_unreachable("Don't know how to custom expand this!");
6744   case ISD::READ_REGISTER:
6745     ExpandREAD_REGISTER(N, Results, DAG);
6746     break;
6747   case ISD::BITCAST:
6748     Res = ExpandBITCAST(N, DAG);
6749     break;
6750   case ISD::SRL:
6751   case ISD::SRA:
6752     Res = Expand64BitShift(N, DAG, Subtarget);
6753     break;
6754   case ISD::READCYCLECOUNTER:
6755     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6756     return;
6757   }
6758   if (Res.getNode())
6759     Results.push_back(Res);
6760 }
6761
6762 //===----------------------------------------------------------------------===//
6763 //                           ARM Scheduler Hooks
6764 //===----------------------------------------------------------------------===//
6765
6766 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6767 /// registers the function context.
6768 void ARMTargetLowering::
6769 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6770                        MachineBasicBlock *DispatchBB, int FI) const {
6771   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6772   DebugLoc dl = MI->getDebugLoc();
6773   MachineFunction *MF = MBB->getParent();
6774   MachineRegisterInfo *MRI = &MF->getRegInfo();
6775   MachineConstantPool *MCP = MF->getConstantPool();
6776   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6777   const Function *F = MF->getFunction();
6778
6779   bool isThumb = Subtarget->isThumb();
6780   bool isThumb2 = Subtarget->isThumb2();
6781
6782   unsigned PCLabelId = AFI->createPICLabelUId();
6783   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6784   ARMConstantPoolValue *CPV =
6785     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6786   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6787
6788   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6789                                            : &ARM::GPRRegClass;
6790
6791   // Grab constant pool and fixed stack memory operands.
6792   MachineMemOperand *CPMMO =
6793       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6794                                MachineMemOperand::MOLoad, 4, 4);
6795
6796   MachineMemOperand *FIMMOSt =
6797       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6798                                MachineMemOperand::MOStore, 4, 4);
6799
6800   // Load the address of the dispatch MBB into the jump buffer.
6801   if (isThumb2) {
6802     // Incoming value: jbuf
6803     //   ldr.n  r5, LCPI1_1
6804     //   orr    r5, r5, #1
6805     //   add    r5, pc
6806     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6807     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6808     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6809                    .addConstantPoolIndex(CPI)
6810                    .addMemOperand(CPMMO));
6811     // Set the low bit because of thumb mode.
6812     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6813     AddDefaultCC(
6814       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6815                      .addReg(NewVReg1, RegState::Kill)
6816                      .addImm(0x01)));
6817     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6818     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6819       .addReg(NewVReg2, RegState::Kill)
6820       .addImm(PCLabelId);
6821     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6822                    .addReg(NewVReg3, RegState::Kill)
6823                    .addFrameIndex(FI)
6824                    .addImm(36)  // &jbuf[1] :: pc
6825                    .addMemOperand(FIMMOSt));
6826   } else if (isThumb) {
6827     // Incoming value: jbuf
6828     //   ldr.n  r1, LCPI1_4
6829     //   add    r1, pc
6830     //   mov    r2, #1
6831     //   orrs   r1, r2
6832     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6833     //   str    r1, [r2]
6834     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6835     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6836                    .addConstantPoolIndex(CPI)
6837                    .addMemOperand(CPMMO));
6838     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6839     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6840       .addReg(NewVReg1, RegState::Kill)
6841       .addImm(PCLabelId);
6842     // Set the low bit because of thumb mode.
6843     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6844     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6845                    .addReg(ARM::CPSR, RegState::Define)
6846                    .addImm(1));
6847     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6848     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6849                    .addReg(ARM::CPSR, RegState::Define)
6850                    .addReg(NewVReg2, RegState::Kill)
6851                    .addReg(NewVReg3, RegState::Kill));
6852     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6853     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6854             .addFrameIndex(FI)
6855             .addImm(36); // &jbuf[1] :: pc
6856     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6857                    .addReg(NewVReg4, RegState::Kill)
6858                    .addReg(NewVReg5, RegState::Kill)
6859                    .addImm(0)
6860                    .addMemOperand(FIMMOSt));
6861   } else {
6862     // Incoming value: jbuf
6863     //   ldr  r1, LCPI1_1
6864     //   add  r1, pc, r1
6865     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6866     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6867     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6868                    .addConstantPoolIndex(CPI)
6869                    .addImm(0)
6870                    .addMemOperand(CPMMO));
6871     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6872     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6873                    .addReg(NewVReg1, RegState::Kill)
6874                    .addImm(PCLabelId));
6875     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6876                    .addReg(NewVReg2, RegState::Kill)
6877                    .addFrameIndex(FI)
6878                    .addImm(36)  // &jbuf[1] :: pc
6879                    .addMemOperand(FIMMOSt));
6880   }
6881 }
6882
6883 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6884                                               MachineBasicBlock *MBB) const {
6885   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6886   DebugLoc dl = MI->getDebugLoc();
6887   MachineFunction *MF = MBB->getParent();
6888   MachineRegisterInfo *MRI = &MF->getRegInfo();
6889   MachineFrameInfo *MFI = MF->getFrameInfo();
6890   int FI = MFI->getFunctionContextIndex();
6891
6892   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6893                                                         : &ARM::GPRnopcRegClass;
6894
6895   // Get a mapping of the call site numbers to all of the landing pads they're
6896   // associated with.
6897   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6898   unsigned MaxCSNum = 0;
6899   MachineModuleInfo &MMI = MF->getMMI();
6900   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6901        ++BB) {
6902     if (!BB->isLandingPad()) continue;
6903
6904     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6905     // pad.
6906     for (MachineBasicBlock::iterator
6907            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6908       if (!II->isEHLabel()) continue;
6909
6910       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6911       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6912
6913       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6914       for (SmallVectorImpl<unsigned>::iterator
6915              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6916            CSI != CSE; ++CSI) {
6917         CallSiteNumToLPad[*CSI].push_back(BB);
6918         MaxCSNum = std::max(MaxCSNum, *CSI);
6919       }
6920       break;
6921     }
6922   }
6923
6924   // Get an ordered list of the machine basic blocks for the jump table.
6925   std::vector<MachineBasicBlock*> LPadList;
6926   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6927   LPadList.reserve(CallSiteNumToLPad.size());
6928   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6929     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6930     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6931            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6932       LPadList.push_back(*II);
6933       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6934     }
6935   }
6936
6937   assert(!LPadList.empty() &&
6938          "No landing pad destinations for the dispatch jump table!");
6939
6940   // Create the jump table and associated information.
6941   MachineJumpTableInfo *JTI =
6942     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6943   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6944   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6945
6946   // Create the MBBs for the dispatch code.
6947
6948   // Shove the dispatch's address into the return slot in the function context.
6949   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6950   DispatchBB->setIsLandingPad();
6951
6952   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6953   unsigned trap_opcode;
6954   if (Subtarget->isThumb())
6955     trap_opcode = ARM::tTRAP;
6956   else
6957     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6958
6959   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6960   DispatchBB->addSuccessor(TrapBB);
6961
6962   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6963   DispatchBB->addSuccessor(DispContBB);
6964
6965   // Insert and MBBs.
6966   MF->insert(MF->end(), DispatchBB);
6967   MF->insert(MF->end(), DispContBB);
6968   MF->insert(MF->end(), TrapBB);
6969
6970   // Insert code into the entry block that creates and registers the function
6971   // context.
6972   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6973
6974   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
6975       MachinePointerInfo::getFixedStack(*MF, FI),
6976       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
6977
6978   MachineInstrBuilder MIB;
6979   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6980
6981   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6982   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6983
6984   // Add a register mask with no preserved registers.  This results in all
6985   // registers being marked as clobbered.
6986   MIB.addRegMask(RI.getNoPreservedMask());
6987
6988   unsigned NumLPads = LPadList.size();
6989   if (Subtarget->isThumb2()) {
6990     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6991     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6992                    .addFrameIndex(FI)
6993                    .addImm(4)
6994                    .addMemOperand(FIMMOLd));
6995
6996     if (NumLPads < 256) {
6997       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6998                      .addReg(NewVReg1)
6999                      .addImm(LPadList.size()));
7000     } else {
7001       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7002       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7003                      .addImm(NumLPads & 0xFFFF));
7004
7005       unsigned VReg2 = VReg1;
7006       if ((NumLPads & 0xFFFF0000) != 0) {
7007         VReg2 = MRI->createVirtualRegister(TRC);
7008         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7009                        .addReg(VReg1)
7010                        .addImm(NumLPads >> 16));
7011       }
7012
7013       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7014                      .addReg(NewVReg1)
7015                      .addReg(VReg2));
7016     }
7017
7018     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7019       .addMBB(TrapBB)
7020       .addImm(ARMCC::HI)
7021       .addReg(ARM::CPSR);
7022
7023     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7024     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7025                    .addJumpTableIndex(MJTI));
7026
7027     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7028     AddDefaultCC(
7029       AddDefaultPred(
7030         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7031         .addReg(NewVReg3, RegState::Kill)
7032         .addReg(NewVReg1)
7033         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7034
7035     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7036       .addReg(NewVReg4, RegState::Kill)
7037       .addReg(NewVReg1)
7038       .addJumpTableIndex(MJTI);
7039   } else if (Subtarget->isThumb()) {
7040     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7041     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7042                    .addFrameIndex(FI)
7043                    .addImm(1)
7044                    .addMemOperand(FIMMOLd));
7045
7046     if (NumLPads < 256) {
7047       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7048                      .addReg(NewVReg1)
7049                      .addImm(NumLPads));
7050     } else {
7051       MachineConstantPool *ConstantPool = MF->getConstantPool();
7052       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7053       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7054
7055       // MachineConstantPool wants an explicit alignment.
7056       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7057       if (Align == 0)
7058         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7059       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7060
7061       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7062       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7063                      .addReg(VReg1, RegState::Define)
7064                      .addConstantPoolIndex(Idx));
7065       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7066                      .addReg(NewVReg1)
7067                      .addReg(VReg1));
7068     }
7069
7070     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7071       .addMBB(TrapBB)
7072       .addImm(ARMCC::HI)
7073       .addReg(ARM::CPSR);
7074
7075     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7076     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7077                    .addReg(ARM::CPSR, RegState::Define)
7078                    .addReg(NewVReg1)
7079                    .addImm(2));
7080
7081     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7082     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7083                    .addJumpTableIndex(MJTI));
7084
7085     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7086     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7087                    .addReg(ARM::CPSR, RegState::Define)
7088                    .addReg(NewVReg2, RegState::Kill)
7089                    .addReg(NewVReg3));
7090
7091     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7092         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7093
7094     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7095     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7096                    .addReg(NewVReg4, RegState::Kill)
7097                    .addImm(0)
7098                    .addMemOperand(JTMMOLd));
7099
7100     unsigned NewVReg6 = NewVReg5;
7101     if (RelocM == Reloc::PIC_) {
7102       NewVReg6 = MRI->createVirtualRegister(TRC);
7103       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7104                      .addReg(ARM::CPSR, RegState::Define)
7105                      .addReg(NewVReg5, RegState::Kill)
7106                      .addReg(NewVReg3));
7107     }
7108
7109     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7110       .addReg(NewVReg6, RegState::Kill)
7111       .addJumpTableIndex(MJTI);
7112   } else {
7113     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7114     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7115                    .addFrameIndex(FI)
7116                    .addImm(4)
7117                    .addMemOperand(FIMMOLd));
7118
7119     if (NumLPads < 256) {
7120       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7121                      .addReg(NewVReg1)
7122                      .addImm(NumLPads));
7123     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7124       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7125       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7126                      .addImm(NumLPads & 0xFFFF));
7127
7128       unsigned VReg2 = VReg1;
7129       if ((NumLPads & 0xFFFF0000) != 0) {
7130         VReg2 = MRI->createVirtualRegister(TRC);
7131         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7132                        .addReg(VReg1)
7133                        .addImm(NumLPads >> 16));
7134       }
7135
7136       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7137                      .addReg(NewVReg1)
7138                      .addReg(VReg2));
7139     } else {
7140       MachineConstantPool *ConstantPool = MF->getConstantPool();
7141       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7142       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7143
7144       // MachineConstantPool wants an explicit alignment.
7145       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7146       if (Align == 0)
7147         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7148       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7149
7150       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7151       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7152                      .addReg(VReg1, RegState::Define)
7153                      .addConstantPoolIndex(Idx)
7154                      .addImm(0));
7155       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7156                      .addReg(NewVReg1)
7157                      .addReg(VReg1, RegState::Kill));
7158     }
7159
7160     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7161       .addMBB(TrapBB)
7162       .addImm(ARMCC::HI)
7163       .addReg(ARM::CPSR);
7164
7165     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7166     AddDefaultCC(
7167       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7168                      .addReg(NewVReg1)
7169                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7170     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7171     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7172                    .addJumpTableIndex(MJTI));
7173
7174     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7175         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7176     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7177     AddDefaultPred(
7178       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7179       .addReg(NewVReg3, RegState::Kill)
7180       .addReg(NewVReg4)
7181       .addImm(0)
7182       .addMemOperand(JTMMOLd));
7183
7184     if (RelocM == Reloc::PIC_) {
7185       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7186         .addReg(NewVReg5, RegState::Kill)
7187         .addReg(NewVReg4)
7188         .addJumpTableIndex(MJTI);
7189     } else {
7190       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7191         .addReg(NewVReg5, RegState::Kill)
7192         .addJumpTableIndex(MJTI);
7193     }
7194   }
7195
7196   // Add the jump table entries as successors to the MBB.
7197   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7198   for (std::vector<MachineBasicBlock*>::iterator
7199          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7200     MachineBasicBlock *CurMBB = *I;
7201     if (SeenMBBs.insert(CurMBB).second)
7202       DispContBB->addSuccessor(CurMBB);
7203   }
7204
7205   // N.B. the order the invoke BBs are processed in doesn't matter here.
7206   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7207   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7208   for (MachineBasicBlock *BB : InvokeBBs) {
7209
7210     // Remove the landing pad successor from the invoke block and replace it
7211     // with the new dispatch block.
7212     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7213                                                   BB->succ_end());
7214     while (!Successors.empty()) {
7215       MachineBasicBlock *SMBB = Successors.pop_back_val();
7216       if (SMBB->isLandingPad()) {
7217         BB->removeSuccessor(SMBB);
7218         MBBLPads.push_back(SMBB);
7219       }
7220     }
7221
7222     BB->addSuccessor(DispatchBB);
7223
7224     // Find the invoke call and mark all of the callee-saved registers as
7225     // 'implicit defined' so that they're spilled. This prevents code from
7226     // moving instructions to before the EH block, where they will never be
7227     // executed.
7228     for (MachineBasicBlock::reverse_iterator
7229            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7230       if (!II->isCall()) continue;
7231
7232       DenseMap<unsigned, bool> DefRegs;
7233       for (MachineInstr::mop_iterator
7234              OI = II->operands_begin(), OE = II->operands_end();
7235            OI != OE; ++OI) {
7236         if (!OI->isReg()) continue;
7237         DefRegs[OI->getReg()] = true;
7238       }
7239
7240       MachineInstrBuilder MIB(*MF, &*II);
7241
7242       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7243         unsigned Reg = SavedRegs[i];
7244         if (Subtarget->isThumb2() &&
7245             !ARM::tGPRRegClass.contains(Reg) &&
7246             !ARM::hGPRRegClass.contains(Reg))
7247           continue;
7248         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7249           continue;
7250         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7251           continue;
7252         if (!DefRegs[Reg])
7253           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7254       }
7255
7256       break;
7257     }
7258   }
7259
7260   // Mark all former landing pads as non-landing pads. The dispatch is the only
7261   // landing pad now.
7262   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7263          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7264     (*I)->setIsLandingPad(false);
7265
7266   // The instruction is gone now.
7267   MI->eraseFromParent();
7268 }
7269
7270 static
7271 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7272   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7273        E = MBB->succ_end(); I != E; ++I)
7274     if (*I != Succ)
7275       return *I;
7276   llvm_unreachable("Expecting a BB with two successors!");
7277 }
7278
7279 /// Return the load opcode for a given load size. If load size >= 8,
7280 /// neon opcode will be returned.
7281 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7282   if (LdSize >= 8)
7283     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7284                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7285   if (IsThumb1)
7286     return LdSize == 4 ? ARM::tLDRi
7287                        : LdSize == 2 ? ARM::tLDRHi
7288                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7289   if (IsThumb2)
7290     return LdSize == 4 ? ARM::t2LDR_POST
7291                        : LdSize == 2 ? ARM::t2LDRH_POST
7292                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7293   return LdSize == 4 ? ARM::LDR_POST_IMM
7294                      : LdSize == 2 ? ARM::LDRH_POST
7295                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7296 }
7297
7298 /// Return the store opcode for a given store size. If store size >= 8,
7299 /// neon opcode will be returned.
7300 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7301   if (StSize >= 8)
7302     return StSize == 16 ? ARM::VST1q32wb_fixed
7303                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7304   if (IsThumb1)
7305     return StSize == 4 ? ARM::tSTRi
7306                        : StSize == 2 ? ARM::tSTRHi
7307                                      : StSize == 1 ? ARM::tSTRBi : 0;
7308   if (IsThumb2)
7309     return StSize == 4 ? ARM::t2STR_POST
7310                        : StSize == 2 ? ARM::t2STRH_POST
7311                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7312   return StSize == 4 ? ARM::STR_POST_IMM
7313                      : StSize == 2 ? ARM::STRH_POST
7314                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7315 }
7316
7317 /// Emit a post-increment load operation with given size. The instructions
7318 /// will be added to BB at Pos.
7319 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7320                        const TargetInstrInfo *TII, DebugLoc dl,
7321                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7322                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7323   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7324   assert(LdOpc != 0 && "Should have a load opcode");
7325   if (LdSize >= 8) {
7326     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7327                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7328                        .addImm(0));
7329   } else if (IsThumb1) {
7330     // load + update AddrIn
7331     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7332                        .addReg(AddrIn).addImm(0));
7333     MachineInstrBuilder MIB =
7334         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7335     MIB = AddDefaultT1CC(MIB);
7336     MIB.addReg(AddrIn).addImm(LdSize);
7337     AddDefaultPred(MIB);
7338   } else if (IsThumb2) {
7339     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7340                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7341                        .addImm(LdSize));
7342   } else { // arm
7343     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7344                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7345                        .addReg(0).addImm(LdSize));
7346   }
7347 }
7348
7349 /// Emit a post-increment store operation with given size. The instructions
7350 /// will be added to BB at Pos.
7351 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7352                        const TargetInstrInfo *TII, DebugLoc dl,
7353                        unsigned StSize, unsigned Data, unsigned AddrIn,
7354                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7355   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7356   assert(StOpc != 0 && "Should have a store opcode");
7357   if (StSize >= 8) {
7358     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7359                        .addReg(AddrIn).addImm(0).addReg(Data));
7360   } else if (IsThumb1) {
7361     // store + update AddrIn
7362     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7363                        .addReg(AddrIn).addImm(0));
7364     MachineInstrBuilder MIB =
7365         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7366     MIB = AddDefaultT1CC(MIB);
7367     MIB.addReg(AddrIn).addImm(StSize);
7368     AddDefaultPred(MIB);
7369   } else if (IsThumb2) {
7370     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7371                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7372   } else { // arm
7373     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7374                        .addReg(Data).addReg(AddrIn).addReg(0)
7375                        .addImm(StSize));
7376   }
7377 }
7378
7379 MachineBasicBlock *
7380 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7381                                    MachineBasicBlock *BB) const {
7382   // This pseudo instruction has 3 operands: dst, src, size
7383   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7384   // Otherwise, we will generate unrolled scalar copies.
7385   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7386   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7387   MachineFunction::iterator It = BB;
7388   ++It;
7389
7390   unsigned dest = MI->getOperand(0).getReg();
7391   unsigned src = MI->getOperand(1).getReg();
7392   unsigned SizeVal = MI->getOperand(2).getImm();
7393   unsigned Align = MI->getOperand(3).getImm();
7394   DebugLoc dl = MI->getDebugLoc();
7395
7396   MachineFunction *MF = BB->getParent();
7397   MachineRegisterInfo &MRI = MF->getRegInfo();
7398   unsigned UnitSize = 0;
7399   const TargetRegisterClass *TRC = nullptr;
7400   const TargetRegisterClass *VecTRC = nullptr;
7401
7402   bool IsThumb1 = Subtarget->isThumb1Only();
7403   bool IsThumb2 = Subtarget->isThumb2();
7404
7405   if (Align & 1) {
7406     UnitSize = 1;
7407   } else if (Align & 2) {
7408     UnitSize = 2;
7409   } else {
7410     // Check whether we can use NEON instructions.
7411     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7412         Subtarget->hasNEON()) {
7413       if ((Align % 16 == 0) && SizeVal >= 16)
7414         UnitSize = 16;
7415       else if ((Align % 8 == 0) && SizeVal >= 8)
7416         UnitSize = 8;
7417     }
7418     // Can't use NEON instructions.
7419     if (UnitSize == 0)
7420       UnitSize = 4;
7421   }
7422
7423   // Select the correct opcode and register class for unit size load/store
7424   bool IsNeon = UnitSize >= 8;
7425   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7426   if (IsNeon)
7427     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7428                             : UnitSize == 8 ? &ARM::DPRRegClass
7429                                             : nullptr;
7430
7431   unsigned BytesLeft = SizeVal % UnitSize;
7432   unsigned LoopSize = SizeVal - BytesLeft;
7433
7434   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7435     // Use LDR and STR to copy.
7436     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7437     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7438     unsigned srcIn = src;
7439     unsigned destIn = dest;
7440     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7441       unsigned srcOut = MRI.createVirtualRegister(TRC);
7442       unsigned destOut = MRI.createVirtualRegister(TRC);
7443       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7444       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7445                  IsThumb1, IsThumb2);
7446       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7447                  IsThumb1, IsThumb2);
7448       srcIn = srcOut;
7449       destIn = destOut;
7450     }
7451
7452     // Handle the leftover bytes with LDRB and STRB.
7453     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7454     // [destOut] = STRB_POST(scratch, destIn, 1)
7455     for (unsigned i = 0; i < BytesLeft; i++) {
7456       unsigned srcOut = MRI.createVirtualRegister(TRC);
7457       unsigned destOut = MRI.createVirtualRegister(TRC);
7458       unsigned scratch = MRI.createVirtualRegister(TRC);
7459       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7460                  IsThumb1, IsThumb2);
7461       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7462                  IsThumb1, IsThumb2);
7463       srcIn = srcOut;
7464       destIn = destOut;
7465     }
7466     MI->eraseFromParent();   // The instruction is gone now.
7467     return BB;
7468   }
7469
7470   // Expand the pseudo op to a loop.
7471   // thisMBB:
7472   //   ...
7473   //   movw varEnd, # --> with thumb2
7474   //   movt varEnd, #
7475   //   ldrcp varEnd, idx --> without thumb2
7476   //   fallthrough --> loopMBB
7477   // loopMBB:
7478   //   PHI varPhi, varEnd, varLoop
7479   //   PHI srcPhi, src, srcLoop
7480   //   PHI destPhi, dst, destLoop
7481   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7482   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7483   //   subs varLoop, varPhi, #UnitSize
7484   //   bne loopMBB
7485   //   fallthrough --> exitMBB
7486   // exitMBB:
7487   //   epilogue to handle left-over bytes
7488   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7489   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7490   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7491   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7492   MF->insert(It, loopMBB);
7493   MF->insert(It, exitMBB);
7494
7495   // Transfer the remainder of BB and its successor edges to exitMBB.
7496   exitMBB->splice(exitMBB->begin(), BB,
7497                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7498   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7499
7500   // Load an immediate to varEnd.
7501   unsigned varEnd = MRI.createVirtualRegister(TRC);
7502   if (Subtarget->useMovt(*MF)) {
7503     unsigned Vtmp = varEnd;
7504     if ((LoopSize & 0xFFFF0000) != 0)
7505       Vtmp = MRI.createVirtualRegister(TRC);
7506     AddDefaultPred(BuildMI(BB, dl,
7507                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7508                            Vtmp).addImm(LoopSize & 0xFFFF));
7509
7510     if ((LoopSize & 0xFFFF0000) != 0)
7511       AddDefaultPred(BuildMI(BB, dl,
7512                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7513                              varEnd)
7514                          .addReg(Vtmp)
7515                          .addImm(LoopSize >> 16));
7516   } else {
7517     MachineConstantPool *ConstantPool = MF->getConstantPool();
7518     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7519     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7520
7521     // MachineConstantPool wants an explicit alignment.
7522     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7523     if (Align == 0)
7524       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7525     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7526
7527     if (IsThumb1)
7528       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7529           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7530     else
7531       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7532           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7533   }
7534   BB->addSuccessor(loopMBB);
7535
7536   // Generate the loop body:
7537   //   varPhi = PHI(varLoop, varEnd)
7538   //   srcPhi = PHI(srcLoop, src)
7539   //   destPhi = PHI(destLoop, dst)
7540   MachineBasicBlock *entryBB = BB;
7541   BB = loopMBB;
7542   unsigned varLoop = MRI.createVirtualRegister(TRC);
7543   unsigned varPhi = MRI.createVirtualRegister(TRC);
7544   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7545   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7546   unsigned destLoop = MRI.createVirtualRegister(TRC);
7547   unsigned destPhi = MRI.createVirtualRegister(TRC);
7548
7549   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7550     .addReg(varLoop).addMBB(loopMBB)
7551     .addReg(varEnd).addMBB(entryBB);
7552   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7553     .addReg(srcLoop).addMBB(loopMBB)
7554     .addReg(src).addMBB(entryBB);
7555   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7556     .addReg(destLoop).addMBB(loopMBB)
7557     .addReg(dest).addMBB(entryBB);
7558
7559   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7560   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7561   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7562   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7563              IsThumb1, IsThumb2);
7564   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7565              IsThumb1, IsThumb2);
7566
7567   // Decrement loop variable by UnitSize.
7568   if (IsThumb1) {
7569     MachineInstrBuilder MIB =
7570         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7571     MIB = AddDefaultT1CC(MIB);
7572     MIB.addReg(varPhi).addImm(UnitSize);
7573     AddDefaultPred(MIB);
7574   } else {
7575     MachineInstrBuilder MIB =
7576         BuildMI(*BB, BB->end(), dl,
7577                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7578     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7579     MIB->getOperand(5).setReg(ARM::CPSR);
7580     MIB->getOperand(5).setIsDef(true);
7581   }
7582   BuildMI(*BB, BB->end(), dl,
7583           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7584       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7585
7586   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7587   BB->addSuccessor(loopMBB);
7588   BB->addSuccessor(exitMBB);
7589
7590   // Add epilogue to handle BytesLeft.
7591   BB = exitMBB;
7592   MachineInstr *StartOfExit = exitMBB->begin();
7593
7594   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7595   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7596   unsigned srcIn = srcLoop;
7597   unsigned destIn = destLoop;
7598   for (unsigned i = 0; i < BytesLeft; i++) {
7599     unsigned srcOut = MRI.createVirtualRegister(TRC);
7600     unsigned destOut = MRI.createVirtualRegister(TRC);
7601     unsigned scratch = MRI.createVirtualRegister(TRC);
7602     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7603                IsThumb1, IsThumb2);
7604     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7605                IsThumb1, IsThumb2);
7606     srcIn = srcOut;
7607     destIn = destOut;
7608   }
7609
7610   MI->eraseFromParent();   // The instruction is gone now.
7611   return BB;
7612 }
7613
7614 MachineBasicBlock *
7615 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7616                                        MachineBasicBlock *MBB) const {
7617   const TargetMachine &TM = getTargetMachine();
7618   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7619   DebugLoc DL = MI->getDebugLoc();
7620
7621   assert(Subtarget->isTargetWindows() &&
7622          "__chkstk is only supported on Windows");
7623   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7624
7625   // __chkstk takes the number of words to allocate on the stack in R4, and
7626   // returns the stack adjustment in number of bytes in R4.  This will not
7627   // clober any other registers (other than the obvious lr).
7628   //
7629   // Although, technically, IP should be considered a register which may be
7630   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7631   // thumb-2 environment, so there is no interworking required.  As a result, we
7632   // do not expect a veneer to be emitted by the linker, clobbering IP.
7633   //
7634   // Each module receives its own copy of __chkstk, so no import thunk is
7635   // required, again, ensuring that IP is not clobbered.
7636   //
7637   // Finally, although some linkers may theoretically provide a trampoline for
7638   // out of range calls (which is quite common due to a 32M range limitation of
7639   // branches for Thumb), we can generate the long-call version via
7640   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7641   // IP.
7642
7643   switch (TM.getCodeModel()) {
7644   case CodeModel::Small:
7645   case CodeModel::Medium:
7646   case CodeModel::Default:
7647   case CodeModel::Kernel:
7648     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7649       .addImm((unsigned)ARMCC::AL).addReg(0)
7650       .addExternalSymbol("__chkstk")
7651       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7652       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7653       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7654     break;
7655   case CodeModel::Large:
7656   case CodeModel::JITDefault: {
7657     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7658     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7659
7660     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7661       .addExternalSymbol("__chkstk");
7662     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7663       .addImm((unsigned)ARMCC::AL).addReg(0)
7664       .addReg(Reg, RegState::Kill)
7665       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7666       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7667       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7668     break;
7669   }
7670   }
7671
7672   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7673                                       ARM::SP)
7674                               .addReg(ARM::SP).addReg(ARM::R4)));
7675
7676   MI->eraseFromParent();
7677   return MBB;
7678 }
7679
7680 MachineBasicBlock *
7681 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7682                                                MachineBasicBlock *BB) const {
7683   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7684   DebugLoc dl = MI->getDebugLoc();
7685   bool isThumb2 = Subtarget->isThumb2();
7686   switch (MI->getOpcode()) {
7687   default: {
7688     MI->dump();
7689     llvm_unreachable("Unexpected instr type to insert");
7690   }
7691   // The Thumb2 pre-indexed stores have the same MI operands, they just
7692   // define them differently in the .td files from the isel patterns, so
7693   // they need pseudos.
7694   case ARM::t2STR_preidx:
7695     MI->setDesc(TII->get(ARM::t2STR_PRE));
7696     return BB;
7697   case ARM::t2STRB_preidx:
7698     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7699     return BB;
7700   case ARM::t2STRH_preidx:
7701     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7702     return BB;
7703
7704   case ARM::STRi_preidx:
7705   case ARM::STRBi_preidx: {
7706     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7707       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7708     // Decode the offset.
7709     unsigned Offset = MI->getOperand(4).getImm();
7710     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7711     Offset = ARM_AM::getAM2Offset(Offset);
7712     if (isSub)
7713       Offset = -Offset;
7714
7715     MachineMemOperand *MMO = *MI->memoperands_begin();
7716     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7717       .addOperand(MI->getOperand(0))  // Rn_wb
7718       .addOperand(MI->getOperand(1))  // Rt
7719       .addOperand(MI->getOperand(2))  // Rn
7720       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7721       .addOperand(MI->getOperand(5))  // pred
7722       .addOperand(MI->getOperand(6))
7723       .addMemOperand(MMO);
7724     MI->eraseFromParent();
7725     return BB;
7726   }
7727   case ARM::STRr_preidx:
7728   case ARM::STRBr_preidx:
7729   case ARM::STRH_preidx: {
7730     unsigned NewOpc;
7731     switch (MI->getOpcode()) {
7732     default: llvm_unreachable("unexpected opcode!");
7733     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7734     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7735     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7736     }
7737     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7738     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7739       MIB.addOperand(MI->getOperand(i));
7740     MI->eraseFromParent();
7741     return BB;
7742   }
7743
7744   case ARM::tMOVCCr_pseudo: {
7745     // To "insert" a SELECT_CC instruction, we actually have to insert the
7746     // diamond control-flow pattern.  The incoming instruction knows the
7747     // destination vreg to set, the condition code register to branch on, the
7748     // true/false values to select between, and a branch opcode to use.
7749     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7750     MachineFunction::iterator It = BB;
7751     ++It;
7752
7753     //  thisMBB:
7754     //  ...
7755     //   TrueVal = ...
7756     //   cmpTY ccX, r1, r2
7757     //   bCC copy1MBB
7758     //   fallthrough --> copy0MBB
7759     MachineBasicBlock *thisMBB  = BB;
7760     MachineFunction *F = BB->getParent();
7761     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7762     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7763     F->insert(It, copy0MBB);
7764     F->insert(It, sinkMBB);
7765
7766     // Transfer the remainder of BB and its successor edges to sinkMBB.
7767     sinkMBB->splice(sinkMBB->begin(), BB,
7768                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7769     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7770
7771     BB->addSuccessor(copy0MBB);
7772     BB->addSuccessor(sinkMBB);
7773
7774     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7775       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7776
7777     //  copy0MBB:
7778     //   %FalseValue = ...
7779     //   # fallthrough to sinkMBB
7780     BB = copy0MBB;
7781
7782     // Update machine-CFG edges
7783     BB->addSuccessor(sinkMBB);
7784
7785     //  sinkMBB:
7786     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7787     //  ...
7788     BB = sinkMBB;
7789     BuildMI(*BB, BB->begin(), dl,
7790             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7791       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7792       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7793
7794     MI->eraseFromParent();   // The pseudo instruction is gone now.
7795     return BB;
7796   }
7797
7798   case ARM::BCCi64:
7799   case ARM::BCCZi64: {
7800     // If there is an unconditional branch to the other successor, remove it.
7801     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7802
7803     // Compare both parts that make up the double comparison separately for
7804     // equality.
7805     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7806
7807     unsigned LHS1 = MI->getOperand(1).getReg();
7808     unsigned LHS2 = MI->getOperand(2).getReg();
7809     if (RHSisZero) {
7810       AddDefaultPred(BuildMI(BB, dl,
7811                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7812                      .addReg(LHS1).addImm(0));
7813       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7814         .addReg(LHS2).addImm(0)
7815         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7816     } else {
7817       unsigned RHS1 = MI->getOperand(3).getReg();
7818       unsigned RHS2 = MI->getOperand(4).getReg();
7819       AddDefaultPred(BuildMI(BB, dl,
7820                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7821                      .addReg(LHS1).addReg(RHS1));
7822       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7823         .addReg(LHS2).addReg(RHS2)
7824         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7825     }
7826
7827     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7828     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7829     if (MI->getOperand(0).getImm() == ARMCC::NE)
7830       std::swap(destMBB, exitMBB);
7831
7832     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7833       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7834     if (isThumb2)
7835       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7836     else
7837       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7838
7839     MI->eraseFromParent();   // The pseudo instruction is gone now.
7840     return BB;
7841   }
7842
7843   case ARM::Int_eh_sjlj_setjmp:
7844   case ARM::Int_eh_sjlj_setjmp_nofp:
7845   case ARM::tInt_eh_sjlj_setjmp:
7846   case ARM::t2Int_eh_sjlj_setjmp:
7847   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7848     return BB;
7849
7850   case ARM::Int_eh_sjlj_setup_dispatch:
7851     EmitSjLjDispatchBlock(MI, BB);
7852     return BB;
7853
7854   case ARM::ABS:
7855   case ARM::t2ABS: {
7856     // To insert an ABS instruction, we have to insert the
7857     // diamond control-flow pattern.  The incoming instruction knows the
7858     // source vreg to test against 0, the destination vreg to set,
7859     // the condition code register to branch on, the
7860     // true/false values to select between, and a branch opcode to use.
7861     // It transforms
7862     //     V1 = ABS V0
7863     // into
7864     //     V2 = MOVS V0
7865     //     BCC                      (branch to SinkBB if V0 >= 0)
7866     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7867     //     SinkBB: V1 = PHI(V2, V3)
7868     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7869     MachineFunction::iterator BBI = BB;
7870     ++BBI;
7871     MachineFunction *Fn = BB->getParent();
7872     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7873     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7874     Fn->insert(BBI, RSBBB);
7875     Fn->insert(BBI, SinkBB);
7876
7877     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7878     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7879     bool ABSSrcKIll = MI->getOperand(1).isKill();
7880     bool isThumb2 = Subtarget->isThumb2();
7881     MachineRegisterInfo &MRI = Fn->getRegInfo();
7882     // In Thumb mode S must not be specified if source register is the SP or
7883     // PC and if destination register is the SP, so restrict register class
7884     unsigned NewRsbDstReg =
7885       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7886
7887     // Transfer the remainder of BB and its successor edges to sinkMBB.
7888     SinkBB->splice(SinkBB->begin(), BB,
7889                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7890     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7891
7892     BB->addSuccessor(RSBBB);
7893     BB->addSuccessor(SinkBB);
7894
7895     // fall through to SinkMBB
7896     RSBBB->addSuccessor(SinkBB);
7897
7898     // insert a cmp at the end of BB
7899     AddDefaultPred(BuildMI(BB, dl,
7900                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7901                    .addReg(ABSSrcReg).addImm(0));
7902
7903     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7904     BuildMI(BB, dl,
7905       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7906       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7907
7908     // insert rsbri in RSBBB
7909     // Note: BCC and rsbri will be converted into predicated rsbmi
7910     // by if-conversion pass
7911     BuildMI(*RSBBB, RSBBB->begin(), dl,
7912       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7913       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7914       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7915
7916     // insert PHI in SinkBB,
7917     // reuse ABSDstReg to not change uses of ABS instruction
7918     BuildMI(*SinkBB, SinkBB->begin(), dl,
7919       TII->get(ARM::PHI), ABSDstReg)
7920       .addReg(NewRsbDstReg).addMBB(RSBBB)
7921       .addReg(ABSSrcReg).addMBB(BB);
7922
7923     // remove ABS instruction
7924     MI->eraseFromParent();
7925
7926     // return last added BB
7927     return SinkBB;
7928   }
7929   case ARM::COPY_STRUCT_BYVAL_I32:
7930     ++NumLoopByVals;
7931     return EmitStructByval(MI, BB);
7932   case ARM::WIN__CHKSTK:
7933     return EmitLowered__chkstk(MI, BB);
7934   }
7935 }
7936
7937 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7938                                                       SDNode *Node) const {
7939   const MCInstrDesc *MCID = &MI->getDesc();
7940   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7941   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7942   // operand is still set to noreg. If needed, set the optional operand's
7943   // register to CPSR, and remove the redundant implicit def.
7944   //
7945   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7946
7947   // Rename pseudo opcodes.
7948   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7949   if (NewOpc) {
7950     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7951     MCID = &TII->get(NewOpc);
7952
7953     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7954            "converted opcode should be the same except for cc_out");
7955
7956     MI->setDesc(*MCID);
7957
7958     // Add the optional cc_out operand
7959     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7960   }
7961   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7962
7963   // Any ARM instruction that sets the 's' bit should specify an optional
7964   // "cc_out" operand in the last operand position.
7965   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7966     assert(!NewOpc && "Optional cc_out operand required");
7967     return;
7968   }
7969   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7970   // since we already have an optional CPSR def.
7971   bool definesCPSR = false;
7972   bool deadCPSR = false;
7973   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7974        i != e; ++i) {
7975     const MachineOperand &MO = MI->getOperand(i);
7976     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7977       definesCPSR = true;
7978       if (MO.isDead())
7979         deadCPSR = true;
7980       MI->RemoveOperand(i);
7981       break;
7982     }
7983   }
7984   if (!definesCPSR) {
7985     assert(!NewOpc && "Optional cc_out operand required");
7986     return;
7987   }
7988   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7989   if (deadCPSR) {
7990     assert(!MI->getOperand(ccOutIdx).getReg() &&
7991            "expect uninitialized optional cc_out operand");
7992     return;
7993   }
7994
7995   // If this instruction was defined with an optional CPSR def and its dag node
7996   // had a live implicit CPSR def, then activate the optional CPSR def.
7997   MachineOperand &MO = MI->getOperand(ccOutIdx);
7998   MO.setReg(ARM::CPSR);
7999   MO.setIsDef(true);
8000 }
8001
8002 //===----------------------------------------------------------------------===//
8003 //                           ARM Optimization Hooks
8004 //===----------------------------------------------------------------------===//
8005
8006 // Helper function that checks if N is a null or all ones constant.
8007 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8008   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8009   if (!C)
8010     return false;
8011   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8012 }
8013
8014 // Return true if N is conditionally 0 or all ones.
8015 // Detects these expressions where cc is an i1 value:
8016 //
8017 //   (select cc 0, y)   [AllOnes=0]
8018 //   (select cc y, 0)   [AllOnes=0]
8019 //   (zext cc)          [AllOnes=0]
8020 //   (sext cc)          [AllOnes=0/1]
8021 //   (select cc -1, y)  [AllOnes=1]
8022 //   (select cc y, -1)  [AllOnes=1]
8023 //
8024 // Invert is set when N is the null/all ones constant when CC is false.
8025 // OtherOp is set to the alternative value of N.
8026 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8027                                        SDValue &CC, bool &Invert,
8028                                        SDValue &OtherOp,
8029                                        SelectionDAG &DAG) {
8030   switch (N->getOpcode()) {
8031   default: return false;
8032   case ISD::SELECT: {
8033     CC = N->getOperand(0);
8034     SDValue N1 = N->getOperand(1);
8035     SDValue N2 = N->getOperand(2);
8036     if (isZeroOrAllOnes(N1, AllOnes)) {
8037       Invert = false;
8038       OtherOp = N2;
8039       return true;
8040     }
8041     if (isZeroOrAllOnes(N2, AllOnes)) {
8042       Invert = true;
8043       OtherOp = N1;
8044       return true;
8045     }
8046     return false;
8047   }
8048   case ISD::ZERO_EXTEND:
8049     // (zext cc) can never be the all ones value.
8050     if (AllOnes)
8051       return false;
8052     // Fall through.
8053   case ISD::SIGN_EXTEND: {
8054     SDLoc dl(N);
8055     EVT VT = N->getValueType(0);
8056     CC = N->getOperand(0);
8057     if (CC.getValueType() != MVT::i1)
8058       return false;
8059     Invert = !AllOnes;
8060     if (AllOnes)
8061       // When looking for an AllOnes constant, N is an sext, and the 'other'
8062       // value is 0.
8063       OtherOp = DAG.getConstant(0, dl, VT);
8064     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8065       // When looking for a 0 constant, N can be zext or sext.
8066       OtherOp = DAG.getConstant(1, dl, VT);
8067     else
8068       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8069                                 VT);
8070     return true;
8071   }
8072   }
8073 }
8074
8075 // Combine a constant select operand into its use:
8076 //
8077 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8078 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8079 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8080 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8081 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8082 //
8083 // The transform is rejected if the select doesn't have a constant operand that
8084 // is null, or all ones when AllOnes is set.
8085 //
8086 // Also recognize sext/zext from i1:
8087 //
8088 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8089 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8090 //
8091 // These transformations eventually create predicated instructions.
8092 //
8093 // @param N       The node to transform.
8094 // @param Slct    The N operand that is a select.
8095 // @param OtherOp The other N operand (x above).
8096 // @param DCI     Context.
8097 // @param AllOnes Require the select constant to be all ones instead of null.
8098 // @returns The new node, or SDValue() on failure.
8099 static
8100 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8101                             TargetLowering::DAGCombinerInfo &DCI,
8102                             bool AllOnes = false) {
8103   SelectionDAG &DAG = DCI.DAG;
8104   EVT VT = N->getValueType(0);
8105   SDValue NonConstantVal;
8106   SDValue CCOp;
8107   bool SwapSelectOps;
8108   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8109                                   NonConstantVal, DAG))
8110     return SDValue();
8111
8112   // Slct is now know to be the desired identity constant when CC is true.
8113   SDValue TrueVal = OtherOp;
8114   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8115                                  OtherOp, NonConstantVal);
8116   // Unless SwapSelectOps says CC should be false.
8117   if (SwapSelectOps)
8118     std::swap(TrueVal, FalseVal);
8119
8120   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8121                      CCOp, TrueVal, FalseVal);
8122 }
8123
8124 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8125 static
8126 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8127                                        TargetLowering::DAGCombinerInfo &DCI) {
8128   SDValue N0 = N->getOperand(0);
8129   SDValue N1 = N->getOperand(1);
8130   if (N0.getNode()->hasOneUse()) {
8131     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8132     if (Result.getNode())
8133       return Result;
8134   }
8135   if (N1.getNode()->hasOneUse()) {
8136     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8137     if (Result.getNode())
8138       return Result;
8139   }
8140   return SDValue();
8141 }
8142
8143 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8144 // (only after legalization).
8145 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8146                                  TargetLowering::DAGCombinerInfo &DCI,
8147                                  const ARMSubtarget *Subtarget) {
8148
8149   // Only perform optimization if after legalize, and if NEON is available. We
8150   // also expected both operands to be BUILD_VECTORs.
8151   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8152       || N0.getOpcode() != ISD::BUILD_VECTOR
8153       || N1.getOpcode() != ISD::BUILD_VECTOR)
8154     return SDValue();
8155
8156   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8157   EVT VT = N->getValueType(0);
8158   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8159     return SDValue();
8160
8161   // Check that the vector operands are of the right form.
8162   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8163   // operands, where N is the size of the formed vector.
8164   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8165   // index such that we have a pair wise add pattern.
8166
8167   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8168   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8169     return SDValue();
8170   SDValue Vec = N0->getOperand(0)->getOperand(0);
8171   SDNode *V = Vec.getNode();
8172   unsigned nextIndex = 0;
8173
8174   // For each operands to the ADD which are BUILD_VECTORs,
8175   // check to see if each of their operands are an EXTRACT_VECTOR with
8176   // the same vector and appropriate index.
8177   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8178     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8179         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8180
8181       SDValue ExtVec0 = N0->getOperand(i);
8182       SDValue ExtVec1 = N1->getOperand(i);
8183
8184       // First operand is the vector, verify its the same.
8185       if (V != ExtVec0->getOperand(0).getNode() ||
8186           V != ExtVec1->getOperand(0).getNode())
8187         return SDValue();
8188
8189       // Second is the constant, verify its correct.
8190       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8191       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8192
8193       // For the constant, we want to see all the even or all the odd.
8194       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8195           || C1->getZExtValue() != nextIndex+1)
8196         return SDValue();
8197
8198       // Increment index.
8199       nextIndex+=2;
8200     } else
8201       return SDValue();
8202   }
8203
8204   // Create VPADDL node.
8205   SelectionDAG &DAG = DCI.DAG;
8206   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8207
8208   SDLoc dl(N);
8209
8210   // Build operand list.
8211   SmallVector<SDValue, 8> Ops;
8212   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8213                                 TLI.getPointerTy(DAG.getDataLayout())));
8214
8215   // Input is the vector.
8216   Ops.push_back(Vec);
8217
8218   // Get widened type and narrowed type.
8219   MVT widenType;
8220   unsigned numElem = VT.getVectorNumElements();
8221   
8222   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8223   switch (inputLaneType.getSimpleVT().SimpleTy) {
8224     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8225     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8226     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8227     default:
8228       llvm_unreachable("Invalid vector element type for padd optimization.");
8229   }
8230
8231   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8232   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8233   return DAG.getNode(ExtOp, dl, VT, tmp);
8234 }
8235
8236 static SDValue findMUL_LOHI(SDValue V) {
8237   if (V->getOpcode() == ISD::UMUL_LOHI ||
8238       V->getOpcode() == ISD::SMUL_LOHI)
8239     return V;
8240   return SDValue();
8241 }
8242
8243 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8244                                      TargetLowering::DAGCombinerInfo &DCI,
8245                                      const ARMSubtarget *Subtarget) {
8246
8247   if (Subtarget->isThumb1Only()) return SDValue();
8248
8249   // Only perform the checks after legalize when the pattern is available.
8250   if (DCI.isBeforeLegalize()) return SDValue();
8251
8252   // Look for multiply add opportunities.
8253   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8254   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8255   // a glue link from the first add to the second add.
8256   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8257   // a S/UMLAL instruction.
8258   //                  UMUL_LOHI
8259   //                 / :lo    \ :hi
8260   //                /          \          [no multiline comment]
8261   //    loAdd ->  ADDE         |
8262   //                 \ :glue  /
8263   //                  \      /
8264   //                    ADDC   <- hiAdd
8265   //
8266   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8267   SDValue AddcOp0 = AddcNode->getOperand(0);
8268   SDValue AddcOp1 = AddcNode->getOperand(1);
8269
8270   // Check if the two operands are from the same mul_lohi node.
8271   if (AddcOp0.getNode() == AddcOp1.getNode())
8272     return SDValue();
8273
8274   assert(AddcNode->getNumValues() == 2 &&
8275          AddcNode->getValueType(0) == MVT::i32 &&
8276          "Expect ADDC with two result values. First: i32");
8277
8278   // Check that we have a glued ADDC node.
8279   if (AddcNode->getValueType(1) != MVT::Glue)
8280     return SDValue();
8281
8282   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8283   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8284       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8285       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8286       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8287     return SDValue();
8288
8289   // Look for the glued ADDE.
8290   SDNode* AddeNode = AddcNode->getGluedUser();
8291   if (!AddeNode)
8292     return SDValue();
8293
8294   // Make sure it is really an ADDE.
8295   if (AddeNode->getOpcode() != ISD::ADDE)
8296     return SDValue();
8297
8298   assert(AddeNode->getNumOperands() == 3 &&
8299          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8300          "ADDE node has the wrong inputs");
8301
8302   // Check for the triangle shape.
8303   SDValue AddeOp0 = AddeNode->getOperand(0);
8304   SDValue AddeOp1 = AddeNode->getOperand(1);
8305
8306   // Make sure that the ADDE operands are not coming from the same node.
8307   if (AddeOp0.getNode() == AddeOp1.getNode())
8308     return SDValue();
8309
8310   // Find the MUL_LOHI node walking up ADDE's operands.
8311   bool IsLeftOperandMUL = false;
8312   SDValue MULOp = findMUL_LOHI(AddeOp0);
8313   if (MULOp == SDValue())
8314    MULOp = findMUL_LOHI(AddeOp1);
8315   else
8316     IsLeftOperandMUL = true;
8317   if (MULOp == SDValue())
8318     return SDValue();
8319
8320   // Figure out the right opcode.
8321   unsigned Opc = MULOp->getOpcode();
8322   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8323
8324   // Figure out the high and low input values to the MLAL node.
8325   SDValue* HiAdd = nullptr;
8326   SDValue* LoMul = nullptr;
8327   SDValue* LowAdd = nullptr;
8328
8329   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8330   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8331     return SDValue();
8332
8333   if (IsLeftOperandMUL)
8334     HiAdd = &AddeOp1;
8335   else
8336     HiAdd = &AddeOp0;
8337
8338
8339   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8340   // whose low result is fed to the ADDC we are checking.
8341
8342   if (AddcOp0 == MULOp.getValue(0)) {
8343     LoMul = &AddcOp0;
8344     LowAdd = &AddcOp1;
8345   }
8346   if (AddcOp1 == MULOp.getValue(0)) {
8347     LoMul = &AddcOp1;
8348     LowAdd = &AddcOp0;
8349   }
8350
8351   if (!LoMul)
8352     return SDValue();
8353
8354   // Create the merged node.
8355   SelectionDAG &DAG = DCI.DAG;
8356
8357   // Build operand list.
8358   SmallVector<SDValue, 8> Ops;
8359   Ops.push_back(LoMul->getOperand(0));
8360   Ops.push_back(LoMul->getOperand(1));
8361   Ops.push_back(*LowAdd);
8362   Ops.push_back(*HiAdd);
8363
8364   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8365                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8366
8367   // Replace the ADDs' nodes uses by the MLA node's values.
8368   SDValue HiMLALResult(MLALNode.getNode(), 1);
8369   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8370
8371   SDValue LoMLALResult(MLALNode.getNode(), 0);
8372   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8373
8374   // Return original node to notify the driver to stop replacing.
8375   SDValue resNode(AddcNode, 0);
8376   return resNode;
8377 }
8378
8379 /// PerformADDCCombine - Target-specific dag combine transform from
8380 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8381 static SDValue PerformADDCCombine(SDNode *N,
8382                                  TargetLowering::DAGCombinerInfo &DCI,
8383                                  const ARMSubtarget *Subtarget) {
8384
8385   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8386
8387 }
8388
8389 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8390 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8391 /// called with the default operands, and if that fails, with commuted
8392 /// operands.
8393 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8394                                           TargetLowering::DAGCombinerInfo &DCI,
8395                                           const ARMSubtarget *Subtarget){
8396
8397   // Attempt to create vpaddl for this add.
8398   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8399   if (Result.getNode())
8400     return Result;
8401
8402   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8403   if (N0.getNode()->hasOneUse()) {
8404     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8405     if (Result.getNode()) return Result;
8406   }
8407   return SDValue();
8408 }
8409
8410 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8411 ///
8412 static SDValue PerformADDCombine(SDNode *N,
8413                                  TargetLowering::DAGCombinerInfo &DCI,
8414                                  const ARMSubtarget *Subtarget) {
8415   SDValue N0 = N->getOperand(0);
8416   SDValue N1 = N->getOperand(1);
8417
8418   // First try with the default operand order.
8419   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8420   if (Result.getNode())
8421     return Result;
8422
8423   // If that didn't work, try again with the operands commuted.
8424   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8425 }
8426
8427 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8428 ///
8429 static SDValue PerformSUBCombine(SDNode *N,
8430                                  TargetLowering::DAGCombinerInfo &DCI) {
8431   SDValue N0 = N->getOperand(0);
8432   SDValue N1 = N->getOperand(1);
8433
8434   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8435   if (N1.getNode()->hasOneUse()) {
8436     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8437     if (Result.getNode()) return Result;
8438   }
8439
8440   return SDValue();
8441 }
8442
8443 /// PerformVMULCombine
8444 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8445 /// special multiplier accumulator forwarding.
8446 ///   vmul d3, d0, d2
8447 ///   vmla d3, d1, d2
8448 /// is faster than
8449 ///   vadd d3, d0, d1
8450 ///   vmul d3, d3, d2
8451 //  However, for (A + B) * (A + B),
8452 //    vadd d2, d0, d1
8453 //    vmul d3, d0, d2
8454 //    vmla d3, d1, d2
8455 //  is slower than
8456 //    vadd d2, d0, d1
8457 //    vmul d3, d2, d2
8458 static SDValue PerformVMULCombine(SDNode *N,
8459                                   TargetLowering::DAGCombinerInfo &DCI,
8460                                   const ARMSubtarget *Subtarget) {
8461   if (!Subtarget->hasVMLxForwarding())
8462     return SDValue();
8463
8464   SelectionDAG &DAG = DCI.DAG;
8465   SDValue N0 = N->getOperand(0);
8466   SDValue N1 = N->getOperand(1);
8467   unsigned Opcode = N0.getOpcode();
8468   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8469       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8470     Opcode = N1.getOpcode();
8471     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8472         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8473       return SDValue();
8474     std::swap(N0, N1);
8475   }
8476
8477   if (N0 == N1)
8478     return SDValue();
8479
8480   EVT VT = N->getValueType(0);
8481   SDLoc DL(N);
8482   SDValue N00 = N0->getOperand(0);
8483   SDValue N01 = N0->getOperand(1);
8484   return DAG.getNode(Opcode, DL, VT,
8485                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8486                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8487 }
8488
8489 static SDValue PerformMULCombine(SDNode *N,
8490                                  TargetLowering::DAGCombinerInfo &DCI,
8491                                  const ARMSubtarget *Subtarget) {
8492   SelectionDAG &DAG = DCI.DAG;
8493
8494   if (Subtarget->isThumb1Only())
8495     return SDValue();
8496
8497   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8498     return SDValue();
8499
8500   EVT VT = N->getValueType(0);
8501   if (VT.is64BitVector() || VT.is128BitVector())
8502     return PerformVMULCombine(N, DCI, Subtarget);
8503   if (VT != MVT::i32)
8504     return SDValue();
8505
8506   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8507   if (!C)
8508     return SDValue();
8509
8510   int64_t MulAmt = C->getSExtValue();
8511   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8512
8513   ShiftAmt = ShiftAmt & (32 - 1);
8514   SDValue V = N->getOperand(0);
8515   SDLoc DL(N);
8516
8517   SDValue Res;
8518   MulAmt >>= ShiftAmt;
8519
8520   if (MulAmt >= 0) {
8521     if (isPowerOf2_32(MulAmt - 1)) {
8522       // (mul x, 2^N + 1) => (add (shl x, N), x)
8523       Res = DAG.getNode(ISD::ADD, DL, VT,
8524                         V,
8525                         DAG.getNode(ISD::SHL, DL, VT,
8526                                     V,
8527                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8528                                                     MVT::i32)));
8529     } else if (isPowerOf2_32(MulAmt + 1)) {
8530       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8531       Res = DAG.getNode(ISD::SUB, DL, VT,
8532                         DAG.getNode(ISD::SHL, DL, VT,
8533                                     V,
8534                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8535                                                     MVT::i32)),
8536                         V);
8537     } else
8538       return SDValue();
8539   } else {
8540     uint64_t MulAmtAbs = -MulAmt;
8541     if (isPowerOf2_32(MulAmtAbs + 1)) {
8542       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8543       Res = DAG.getNode(ISD::SUB, DL, VT,
8544                         V,
8545                         DAG.getNode(ISD::SHL, DL, VT,
8546                                     V,
8547                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8548                                                     MVT::i32)));
8549     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8550       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8551       Res = DAG.getNode(ISD::ADD, DL, VT,
8552                         V,
8553                         DAG.getNode(ISD::SHL, DL, VT,
8554                                     V,
8555                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8556                                                     MVT::i32)));
8557       Res = DAG.getNode(ISD::SUB, DL, VT,
8558                         DAG.getConstant(0, DL, MVT::i32), Res);
8559
8560     } else
8561       return SDValue();
8562   }
8563
8564   if (ShiftAmt != 0)
8565     Res = DAG.getNode(ISD::SHL, DL, VT,
8566                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8567
8568   // Do not add new nodes to DAG combiner worklist.
8569   DCI.CombineTo(N, Res, false);
8570   return SDValue();
8571 }
8572
8573 static SDValue PerformANDCombine(SDNode *N,
8574                                  TargetLowering::DAGCombinerInfo &DCI,
8575                                  const ARMSubtarget *Subtarget) {
8576
8577   // Attempt to use immediate-form VBIC
8578   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8579   SDLoc dl(N);
8580   EVT VT = N->getValueType(0);
8581   SelectionDAG &DAG = DCI.DAG;
8582
8583   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8584     return SDValue();
8585
8586   APInt SplatBits, SplatUndef;
8587   unsigned SplatBitSize;
8588   bool HasAnyUndefs;
8589   if (BVN &&
8590       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8591     if (SplatBitSize <= 64) {
8592       EVT VbicVT;
8593       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8594                                       SplatUndef.getZExtValue(), SplatBitSize,
8595                                       DAG, dl, VbicVT, VT.is128BitVector(),
8596                                       OtherModImm);
8597       if (Val.getNode()) {
8598         SDValue Input =
8599           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8600         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8601         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8602       }
8603     }
8604   }
8605
8606   if (!Subtarget->isThumb1Only()) {
8607     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8608     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8609     if (Result.getNode())
8610       return Result;
8611   }
8612
8613   return SDValue();
8614 }
8615
8616 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8617 static SDValue PerformORCombine(SDNode *N,
8618                                 TargetLowering::DAGCombinerInfo &DCI,
8619                                 const ARMSubtarget *Subtarget) {
8620   // Attempt to use immediate-form VORR
8621   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8622   SDLoc dl(N);
8623   EVT VT = N->getValueType(0);
8624   SelectionDAG &DAG = DCI.DAG;
8625
8626   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8627     return SDValue();
8628
8629   APInt SplatBits, SplatUndef;
8630   unsigned SplatBitSize;
8631   bool HasAnyUndefs;
8632   if (BVN && Subtarget->hasNEON() &&
8633       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8634     if (SplatBitSize <= 64) {
8635       EVT VorrVT;
8636       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8637                                       SplatUndef.getZExtValue(), SplatBitSize,
8638                                       DAG, dl, VorrVT, VT.is128BitVector(),
8639                                       OtherModImm);
8640       if (Val.getNode()) {
8641         SDValue Input =
8642           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8643         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8644         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8645       }
8646     }
8647   }
8648
8649   if (!Subtarget->isThumb1Only()) {
8650     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8651     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8652     if (Result.getNode())
8653       return Result;
8654   }
8655
8656   // The code below optimizes (or (and X, Y), Z).
8657   // The AND operand needs to have a single user to make these optimizations
8658   // profitable.
8659   SDValue N0 = N->getOperand(0);
8660   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8661     return SDValue();
8662   SDValue N1 = N->getOperand(1);
8663
8664   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8665   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8666       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8667     APInt SplatUndef;
8668     unsigned SplatBitSize;
8669     bool HasAnyUndefs;
8670
8671     APInt SplatBits0, SplatBits1;
8672     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8673     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8674     // Ensure that the second operand of both ands are constants
8675     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8676                                       HasAnyUndefs) && !HasAnyUndefs) {
8677         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8678                                           HasAnyUndefs) && !HasAnyUndefs) {
8679             // Ensure that the bit width of the constants are the same and that
8680             // the splat arguments are logical inverses as per the pattern we
8681             // are trying to simplify.
8682             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8683                 SplatBits0 == ~SplatBits1) {
8684                 // Canonicalize the vector type to make instruction selection
8685                 // simpler.
8686                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8687                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8688                                              N0->getOperand(1),
8689                                              N0->getOperand(0),
8690                                              N1->getOperand(0));
8691                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8692             }
8693         }
8694     }
8695   }
8696
8697   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8698   // reasonable.
8699
8700   // BFI is only available on V6T2+
8701   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8702     return SDValue();
8703
8704   SDLoc DL(N);
8705   // 1) or (and A, mask), val => ARMbfi A, val, mask
8706   //      iff (val & mask) == val
8707   //
8708   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8709   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8710   //          && mask == ~mask2
8711   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8712   //          && ~mask == mask2
8713   //  (i.e., copy a bitfield value into another bitfield of the same width)
8714
8715   if (VT != MVT::i32)
8716     return SDValue();
8717
8718   SDValue N00 = N0.getOperand(0);
8719
8720   // The value and the mask need to be constants so we can verify this is
8721   // actually a bitfield set. If the mask is 0xffff, we can do better
8722   // via a movt instruction, so don't use BFI in that case.
8723   SDValue MaskOp = N0.getOperand(1);
8724   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8725   if (!MaskC)
8726     return SDValue();
8727   unsigned Mask = MaskC->getZExtValue();
8728   if (Mask == 0xffff)
8729     return SDValue();
8730   SDValue Res;
8731   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8732   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8733   if (N1C) {
8734     unsigned Val = N1C->getZExtValue();
8735     if ((Val & ~Mask) != Val)
8736       return SDValue();
8737
8738     if (ARM::isBitFieldInvertedMask(Mask)) {
8739       Val >>= countTrailingZeros(~Mask);
8740
8741       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8742                         DAG.getConstant(Val, DL, MVT::i32),
8743                         DAG.getConstant(Mask, DL, MVT::i32));
8744
8745       // Do not add new nodes to DAG combiner worklist.
8746       DCI.CombineTo(N, Res, false);
8747       return SDValue();
8748     }
8749   } else if (N1.getOpcode() == ISD::AND) {
8750     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8751     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8752     if (!N11C)
8753       return SDValue();
8754     unsigned Mask2 = N11C->getZExtValue();
8755
8756     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8757     // as is to match.
8758     if (ARM::isBitFieldInvertedMask(Mask) &&
8759         (Mask == ~Mask2)) {
8760       // The pack halfword instruction works better for masks that fit it,
8761       // so use that when it's available.
8762       if (Subtarget->hasT2ExtractPack() &&
8763           (Mask == 0xffff || Mask == 0xffff0000))
8764         return SDValue();
8765       // 2a
8766       unsigned amt = countTrailingZeros(Mask2);
8767       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8768                         DAG.getConstant(amt, DL, MVT::i32));
8769       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8770                         DAG.getConstant(Mask, DL, MVT::i32));
8771       // Do not add new nodes to DAG combiner worklist.
8772       DCI.CombineTo(N, Res, false);
8773       return SDValue();
8774     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8775                (~Mask == Mask2)) {
8776       // The pack halfword instruction works better for masks that fit it,
8777       // so use that when it's available.
8778       if (Subtarget->hasT2ExtractPack() &&
8779           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8780         return SDValue();
8781       // 2b
8782       unsigned lsb = countTrailingZeros(Mask);
8783       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8784                         DAG.getConstant(lsb, DL, MVT::i32));
8785       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8786                         DAG.getConstant(Mask2, DL, MVT::i32));
8787       // Do not add new nodes to DAG combiner worklist.
8788       DCI.CombineTo(N, Res, false);
8789       return SDValue();
8790     }
8791   }
8792
8793   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8794       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8795       ARM::isBitFieldInvertedMask(~Mask)) {
8796     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8797     // where lsb(mask) == #shamt and masked bits of B are known zero.
8798     SDValue ShAmt = N00.getOperand(1);
8799     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8800     unsigned LSB = countTrailingZeros(Mask);
8801     if (ShAmtC != LSB)
8802       return SDValue();
8803
8804     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8805                       DAG.getConstant(~Mask, DL, MVT::i32));
8806
8807     // Do not add new nodes to DAG combiner worklist.
8808     DCI.CombineTo(N, Res, false);
8809   }
8810
8811   return SDValue();
8812 }
8813
8814 static SDValue PerformXORCombine(SDNode *N,
8815                                  TargetLowering::DAGCombinerInfo &DCI,
8816                                  const ARMSubtarget *Subtarget) {
8817   EVT VT = N->getValueType(0);
8818   SelectionDAG &DAG = DCI.DAG;
8819
8820   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8821     return SDValue();
8822
8823   if (!Subtarget->isThumb1Only()) {
8824     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8825     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8826     if (Result.getNode())
8827       return Result;
8828   }
8829
8830   return SDValue();
8831 }
8832
8833 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8834 /// the bits being cleared by the AND are not demanded by the BFI.
8835 static SDValue PerformBFICombine(SDNode *N,
8836                                  TargetLowering::DAGCombinerInfo &DCI) {
8837   SDValue N1 = N->getOperand(1);
8838   if (N1.getOpcode() == ISD::AND) {
8839     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8840     if (!N11C)
8841       return SDValue();
8842     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8843     unsigned LSB = countTrailingZeros(~InvMask);
8844     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8845     assert(Width <
8846                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8847            "undefined behavior");
8848     unsigned Mask = (1u << Width) - 1;
8849     unsigned Mask2 = N11C->getZExtValue();
8850     if ((Mask & (~Mask2)) == 0)
8851       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8852                              N->getOperand(0), N1.getOperand(0),
8853                              N->getOperand(2));
8854   }
8855   return SDValue();
8856 }
8857
8858 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8859 /// ARMISD::VMOVRRD.
8860 static SDValue PerformVMOVRRDCombine(SDNode *N,
8861                                      TargetLowering::DAGCombinerInfo &DCI,
8862                                      const ARMSubtarget *Subtarget) {
8863   // vmovrrd(vmovdrr x, y) -> x,y
8864   SDValue InDouble = N->getOperand(0);
8865   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8866     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8867
8868   // vmovrrd(load f64) -> (load i32), (load i32)
8869   SDNode *InNode = InDouble.getNode();
8870   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8871       InNode->getValueType(0) == MVT::f64 &&
8872       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8873       !cast<LoadSDNode>(InNode)->isVolatile()) {
8874     // TODO: Should this be done for non-FrameIndex operands?
8875     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8876
8877     SelectionDAG &DAG = DCI.DAG;
8878     SDLoc DL(LD);
8879     SDValue BasePtr = LD->getBasePtr();
8880     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8881                                  LD->getPointerInfo(), LD->isVolatile(),
8882                                  LD->isNonTemporal(), LD->isInvariant(),
8883                                  LD->getAlignment());
8884
8885     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8886                                     DAG.getConstant(4, DL, MVT::i32));
8887     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8888                                  LD->getPointerInfo(), LD->isVolatile(),
8889                                  LD->isNonTemporal(), LD->isInvariant(),
8890                                  std::min(4U, LD->getAlignment() / 2));
8891
8892     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8893     if (DCI.DAG.getDataLayout().isBigEndian())
8894       std::swap (NewLD1, NewLD2);
8895     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8896     return Result;
8897   }
8898
8899   return SDValue();
8900 }
8901
8902 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8903 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8904 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8905   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8906   SDValue Op0 = N->getOperand(0);
8907   SDValue Op1 = N->getOperand(1);
8908   if (Op0.getOpcode() == ISD::BITCAST)
8909     Op0 = Op0.getOperand(0);
8910   if (Op1.getOpcode() == ISD::BITCAST)
8911     Op1 = Op1.getOperand(0);
8912   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8913       Op0.getNode() == Op1.getNode() &&
8914       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8915     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8916                        N->getValueType(0), Op0.getOperand(0));
8917   return SDValue();
8918 }
8919
8920 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8921 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8922 /// i64 vector to have f64 elements, since the value can then be loaded
8923 /// directly into a VFP register.
8924 static bool hasNormalLoadOperand(SDNode *N) {
8925   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8926   for (unsigned i = 0; i < NumElts; ++i) {
8927     SDNode *Elt = N->getOperand(i).getNode();
8928     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8929       return true;
8930   }
8931   return false;
8932 }
8933
8934 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8935 /// ISD::BUILD_VECTOR.
8936 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8937                                           TargetLowering::DAGCombinerInfo &DCI,
8938                                           const ARMSubtarget *Subtarget) {
8939   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8940   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8941   // into a pair of GPRs, which is fine when the value is used as a scalar,
8942   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8943   SelectionDAG &DAG = DCI.DAG;
8944   if (N->getNumOperands() == 2) {
8945     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8946     if (RV.getNode())
8947       return RV;
8948   }
8949
8950   // Load i64 elements as f64 values so that type legalization does not split
8951   // them up into i32 values.
8952   EVT VT = N->getValueType(0);
8953   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8954     return SDValue();
8955   SDLoc dl(N);
8956   SmallVector<SDValue, 8> Ops;
8957   unsigned NumElts = VT.getVectorNumElements();
8958   for (unsigned i = 0; i < NumElts; ++i) {
8959     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8960     Ops.push_back(V);
8961     // Make the DAGCombiner fold the bitcast.
8962     DCI.AddToWorklist(V.getNode());
8963   }
8964   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8965   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8966   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8967 }
8968
8969 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8970 static SDValue
8971 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8972   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8973   // At that time, we may have inserted bitcasts from integer to float.
8974   // If these bitcasts have survived DAGCombine, change the lowering of this
8975   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8976   // force to use floating point types.
8977
8978   // Make sure we can change the type of the vector.
8979   // This is possible iff:
8980   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8981   //    1.1. Vector is used only once.
8982   //    1.2. Use is a bit convert to an integer type.
8983   // 2. The size of its operands are 32-bits (64-bits are not legal).
8984   EVT VT = N->getValueType(0);
8985   EVT EltVT = VT.getVectorElementType();
8986
8987   // Check 1.1. and 2.
8988   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8989     return SDValue();
8990
8991   // By construction, the input type must be float.
8992   assert(EltVT == MVT::f32 && "Unexpected type!");
8993
8994   // Check 1.2.
8995   SDNode *Use = *N->use_begin();
8996   if (Use->getOpcode() != ISD::BITCAST ||
8997       Use->getValueType(0).isFloatingPoint())
8998     return SDValue();
8999
9000   // Check profitability.
9001   // Model is, if more than half of the relevant operands are bitcast from
9002   // i32, turn the build_vector into a sequence of insert_vector_elt.
9003   // Relevant operands are everything that is not statically
9004   // (i.e., at compile time) bitcasted.
9005   unsigned NumOfBitCastedElts = 0;
9006   unsigned NumElts = VT.getVectorNumElements();
9007   unsigned NumOfRelevantElts = NumElts;
9008   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9009     SDValue Elt = N->getOperand(Idx);
9010     if (Elt->getOpcode() == ISD::BITCAST) {
9011       // Assume only bit cast to i32 will go away.
9012       if (Elt->getOperand(0).getValueType() == MVT::i32)
9013         ++NumOfBitCastedElts;
9014     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9015       // Constants are statically casted, thus do not count them as
9016       // relevant operands.
9017       --NumOfRelevantElts;
9018   }
9019
9020   // Check if more than half of the elements require a non-free bitcast.
9021   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9022     return SDValue();
9023
9024   SelectionDAG &DAG = DCI.DAG;
9025   // Create the new vector type.
9026   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9027   // Check if the type is legal.
9028   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9029   if (!TLI.isTypeLegal(VecVT))
9030     return SDValue();
9031
9032   // Combine:
9033   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9034   // => BITCAST INSERT_VECTOR_ELT
9035   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9036   //                      (BITCAST EN), N.
9037   SDValue Vec = DAG.getUNDEF(VecVT);
9038   SDLoc dl(N);
9039   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9040     SDValue V = N->getOperand(Idx);
9041     if (V.getOpcode() == ISD::UNDEF)
9042       continue;
9043     if (V.getOpcode() == ISD::BITCAST &&
9044         V->getOperand(0).getValueType() == MVT::i32)
9045       // Fold obvious case.
9046       V = V.getOperand(0);
9047     else {
9048       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9049       // Make the DAGCombiner fold the bitcasts.
9050       DCI.AddToWorklist(V.getNode());
9051     }
9052     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9053     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9054   }
9055   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9056   // Make the DAGCombiner fold the bitcasts.
9057   DCI.AddToWorklist(Vec.getNode());
9058   return Vec;
9059 }
9060
9061 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9062 /// ISD::INSERT_VECTOR_ELT.
9063 static SDValue PerformInsertEltCombine(SDNode *N,
9064                                        TargetLowering::DAGCombinerInfo &DCI) {
9065   // Bitcast an i64 load inserted into a vector to f64.
9066   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9067   EVT VT = N->getValueType(0);
9068   SDNode *Elt = N->getOperand(1).getNode();
9069   if (VT.getVectorElementType() != MVT::i64 ||
9070       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9071     return SDValue();
9072
9073   SelectionDAG &DAG = DCI.DAG;
9074   SDLoc dl(N);
9075   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9076                                  VT.getVectorNumElements());
9077   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9078   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9079   // Make the DAGCombiner fold the bitcasts.
9080   DCI.AddToWorklist(Vec.getNode());
9081   DCI.AddToWorklist(V.getNode());
9082   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9083                                Vec, V, N->getOperand(2));
9084   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9085 }
9086
9087 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9088 /// ISD::VECTOR_SHUFFLE.
9089 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9090   // The LLVM shufflevector instruction does not require the shuffle mask
9091   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9092   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9093   // operands do not match the mask length, they are extended by concatenating
9094   // them with undef vectors.  That is probably the right thing for other
9095   // targets, but for NEON it is better to concatenate two double-register
9096   // size vector operands into a single quad-register size vector.  Do that
9097   // transformation here:
9098   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9099   //   shuffle(concat(v1, v2), undef)
9100   SDValue Op0 = N->getOperand(0);
9101   SDValue Op1 = N->getOperand(1);
9102   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9103       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9104       Op0.getNumOperands() != 2 ||
9105       Op1.getNumOperands() != 2)
9106     return SDValue();
9107   SDValue Concat0Op1 = Op0.getOperand(1);
9108   SDValue Concat1Op1 = Op1.getOperand(1);
9109   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9110       Concat1Op1.getOpcode() != ISD::UNDEF)
9111     return SDValue();
9112   // Skip the transformation if any of the types are illegal.
9113   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9114   EVT VT = N->getValueType(0);
9115   if (!TLI.isTypeLegal(VT) ||
9116       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9117       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9118     return SDValue();
9119
9120   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9121                                   Op0.getOperand(0), Op1.getOperand(0));
9122   // Translate the shuffle mask.
9123   SmallVector<int, 16> NewMask;
9124   unsigned NumElts = VT.getVectorNumElements();
9125   unsigned HalfElts = NumElts/2;
9126   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9127   for (unsigned n = 0; n < NumElts; ++n) {
9128     int MaskElt = SVN->getMaskElt(n);
9129     int NewElt = -1;
9130     if (MaskElt < (int)HalfElts)
9131       NewElt = MaskElt;
9132     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9133       NewElt = HalfElts + MaskElt - NumElts;
9134     NewMask.push_back(NewElt);
9135   }
9136   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9137                               DAG.getUNDEF(VT), NewMask.data());
9138 }
9139
9140 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9141 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9142 /// base address updates.
9143 /// For generic load/stores, the memory type is assumed to be a vector.
9144 /// The caller is assumed to have checked legality.
9145 static SDValue CombineBaseUpdate(SDNode *N,
9146                                  TargetLowering::DAGCombinerInfo &DCI) {
9147   SelectionDAG &DAG = DCI.DAG;
9148   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9149                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9150   const bool isStore = N->getOpcode() == ISD::STORE;
9151   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9152   SDValue Addr = N->getOperand(AddrOpIdx);
9153   MemSDNode *MemN = cast<MemSDNode>(N);
9154   SDLoc dl(N);
9155
9156   // Search for a use of the address operand that is an increment.
9157   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9158          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9159     SDNode *User = *UI;
9160     if (User->getOpcode() != ISD::ADD ||
9161         UI.getUse().getResNo() != Addr.getResNo())
9162       continue;
9163
9164     // Check that the add is independent of the load/store.  Otherwise, folding
9165     // it would create a cycle.
9166     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9167       continue;
9168
9169     // Find the new opcode for the updating load/store.
9170     bool isLoadOp = true;
9171     bool isLaneOp = false;
9172     unsigned NewOpc = 0;
9173     unsigned NumVecs = 0;
9174     if (isIntrinsic) {
9175       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9176       switch (IntNo) {
9177       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9178       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9179         NumVecs = 1; break;
9180       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9181         NumVecs = 2; break;
9182       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9183         NumVecs = 3; break;
9184       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9185         NumVecs = 4; break;
9186       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9187         NumVecs = 2; isLaneOp = true; break;
9188       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9189         NumVecs = 3; isLaneOp = true; break;
9190       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9191         NumVecs = 4; isLaneOp = true; break;
9192       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9193         NumVecs = 1; isLoadOp = false; break;
9194       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9195         NumVecs = 2; isLoadOp = false; break;
9196       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9197         NumVecs = 3; isLoadOp = false; break;
9198       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9199         NumVecs = 4; isLoadOp = false; break;
9200       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9201         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9202       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9203         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9204       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9205         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9206       }
9207     } else {
9208       isLaneOp = true;
9209       switch (N->getOpcode()) {
9210       default: llvm_unreachable("unexpected opcode for Neon base update");
9211       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9212       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9213       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9214       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9215         NumVecs = 1; isLaneOp = false; break;
9216       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9217         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9218       }
9219     }
9220
9221     // Find the size of memory referenced by the load/store.
9222     EVT VecTy;
9223     if (isLoadOp) {
9224       VecTy = N->getValueType(0);
9225     } else if (isIntrinsic) {
9226       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9227     } else {
9228       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9229       VecTy = N->getOperand(1).getValueType();
9230     }
9231
9232     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9233     if (isLaneOp)
9234       NumBytes /= VecTy.getVectorNumElements();
9235
9236     // If the increment is a constant, it must match the memory ref size.
9237     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9238     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9239       uint64_t IncVal = CInc->getZExtValue();
9240       if (IncVal != NumBytes)
9241         continue;
9242     } else if (NumBytes >= 3 * 16) {
9243       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9244       // separate instructions that make it harder to use a non-constant update.
9245       continue;
9246     }
9247
9248     // OK, we found an ADD we can fold into the base update.
9249     // Now, create a _UPD node, taking care of not breaking alignment.
9250
9251     EVT AlignedVecTy = VecTy;
9252     unsigned Alignment = MemN->getAlignment();
9253
9254     // If this is a less-than-standard-aligned load/store, change the type to
9255     // match the standard alignment.
9256     // The alignment is overlooked when selecting _UPD variants; and it's
9257     // easier to introduce bitcasts here than fix that.
9258     // There are 3 ways to get to this base-update combine:
9259     // - intrinsics: they are assumed to be properly aligned (to the standard
9260     //   alignment of the memory type), so we don't need to do anything.
9261     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9262     //   intrinsics, so, likewise, there's nothing to do.
9263     // - generic load/store instructions: the alignment is specified as an
9264     //   explicit operand, rather than implicitly as the standard alignment
9265     //   of the memory type (like the intrisics).  We need to change the
9266     //   memory type to match the explicit alignment.  That way, we don't
9267     //   generate non-standard-aligned ARMISD::VLDx nodes.
9268     if (isa<LSBaseSDNode>(N)) {
9269       if (Alignment == 0)
9270         Alignment = 1;
9271       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9272         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9273         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9274         assert(!isLaneOp && "Unexpected generic load/store lane.");
9275         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9276         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9277       }
9278       // Don't set an explicit alignment on regular load/stores that we want
9279       // to transform to VLD/VST 1_UPD nodes.
9280       // This matches the behavior of regular load/stores, which only get an
9281       // explicit alignment if the MMO alignment is larger than the standard
9282       // alignment of the memory type.
9283       // Intrinsics, however, always get an explicit alignment, set to the
9284       // alignment of the MMO.
9285       Alignment = 1;
9286     }
9287
9288     // Create the new updating load/store node.
9289     // First, create an SDVTList for the new updating node's results.
9290     EVT Tys[6];
9291     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9292     unsigned n;
9293     for (n = 0; n < NumResultVecs; ++n)
9294       Tys[n] = AlignedVecTy;
9295     Tys[n++] = MVT::i32;
9296     Tys[n] = MVT::Other;
9297     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9298
9299     // Then, gather the new node's operands.
9300     SmallVector<SDValue, 8> Ops;
9301     Ops.push_back(N->getOperand(0)); // incoming chain
9302     Ops.push_back(N->getOperand(AddrOpIdx));
9303     Ops.push_back(Inc);
9304
9305     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9306       // Try to match the intrinsic's signature
9307       Ops.push_back(StN->getValue());
9308     } else {
9309       // Loads (and of course intrinsics) match the intrinsics' signature,
9310       // so just add all but the alignment operand.
9311       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9312         Ops.push_back(N->getOperand(i));
9313     }
9314
9315     // For all node types, the alignment operand is always the last one.
9316     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9317
9318     // If this is a non-standard-aligned STORE, the penultimate operand is the
9319     // stored value.  Bitcast it to the aligned type.
9320     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9321       SDValue &StVal = Ops[Ops.size()-2];
9322       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9323     }
9324
9325     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9326                                            Ops, AlignedVecTy,
9327                                            MemN->getMemOperand());
9328
9329     // Update the uses.
9330     SmallVector<SDValue, 5> NewResults;
9331     for (unsigned i = 0; i < NumResultVecs; ++i)
9332       NewResults.push_back(SDValue(UpdN.getNode(), i));
9333
9334     // If this is an non-standard-aligned LOAD, the first result is the loaded
9335     // value.  Bitcast it to the expected result type.
9336     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9337       SDValue &LdVal = NewResults[0];
9338       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9339     }
9340
9341     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9342     DCI.CombineTo(N, NewResults);
9343     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9344
9345     break;
9346   }
9347   return SDValue();
9348 }
9349
9350 static SDValue PerformVLDCombine(SDNode *N,
9351                                  TargetLowering::DAGCombinerInfo &DCI) {
9352   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9353     return SDValue();
9354
9355   return CombineBaseUpdate(N, DCI);
9356 }
9357
9358 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9359 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9360 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9361 /// return true.
9362 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9363   SelectionDAG &DAG = DCI.DAG;
9364   EVT VT = N->getValueType(0);
9365   // vldN-dup instructions only support 64-bit vectors for N > 1.
9366   if (!VT.is64BitVector())
9367     return false;
9368
9369   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9370   SDNode *VLD = N->getOperand(0).getNode();
9371   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9372     return false;
9373   unsigned NumVecs = 0;
9374   unsigned NewOpc = 0;
9375   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9376   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9377     NumVecs = 2;
9378     NewOpc = ARMISD::VLD2DUP;
9379   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9380     NumVecs = 3;
9381     NewOpc = ARMISD::VLD3DUP;
9382   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9383     NumVecs = 4;
9384     NewOpc = ARMISD::VLD4DUP;
9385   } else {
9386     return false;
9387   }
9388
9389   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9390   // numbers match the load.
9391   unsigned VLDLaneNo =
9392     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9393   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9394        UI != UE; ++UI) {
9395     // Ignore uses of the chain result.
9396     if (UI.getUse().getResNo() == NumVecs)
9397       continue;
9398     SDNode *User = *UI;
9399     if (User->getOpcode() != ARMISD::VDUPLANE ||
9400         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9401       return false;
9402   }
9403
9404   // Create the vldN-dup node.
9405   EVT Tys[5];
9406   unsigned n;
9407   for (n = 0; n < NumVecs; ++n)
9408     Tys[n] = VT;
9409   Tys[n] = MVT::Other;
9410   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9411   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9412   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9413   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9414                                            Ops, VLDMemInt->getMemoryVT(),
9415                                            VLDMemInt->getMemOperand());
9416
9417   // Update the uses.
9418   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9419        UI != UE; ++UI) {
9420     unsigned ResNo = UI.getUse().getResNo();
9421     // Ignore uses of the chain result.
9422     if (ResNo == NumVecs)
9423       continue;
9424     SDNode *User = *UI;
9425     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9426   }
9427
9428   // Now the vldN-lane intrinsic is dead except for its chain result.
9429   // Update uses of the chain.
9430   std::vector<SDValue> VLDDupResults;
9431   for (unsigned n = 0; n < NumVecs; ++n)
9432     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9433   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9434   DCI.CombineTo(VLD, VLDDupResults);
9435
9436   return true;
9437 }
9438
9439 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9440 /// ARMISD::VDUPLANE.
9441 static SDValue PerformVDUPLANECombine(SDNode *N,
9442                                       TargetLowering::DAGCombinerInfo &DCI) {
9443   SDValue Op = N->getOperand(0);
9444
9445   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9446   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9447   if (CombineVLDDUP(N, DCI))
9448     return SDValue(N, 0);
9449
9450   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9451   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9452   while (Op.getOpcode() == ISD::BITCAST)
9453     Op = Op.getOperand(0);
9454   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9455     return SDValue();
9456
9457   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9458   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9459   // The canonical VMOV for a zero vector uses a 32-bit element size.
9460   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9461   unsigned EltBits;
9462   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9463     EltSize = 8;
9464   EVT VT = N->getValueType(0);
9465   if (EltSize > VT.getVectorElementType().getSizeInBits())
9466     return SDValue();
9467
9468   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9469 }
9470
9471 static SDValue PerformLOADCombine(SDNode *N,
9472                                   TargetLowering::DAGCombinerInfo &DCI) {
9473   EVT VT = N->getValueType(0);
9474
9475   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9476   if (ISD::isNormalLoad(N) && VT.isVector() &&
9477       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9478     return CombineBaseUpdate(N, DCI);
9479
9480   return SDValue();
9481 }
9482
9483 /// PerformSTORECombine - Target-specific dag combine xforms for
9484 /// ISD::STORE.
9485 static SDValue PerformSTORECombine(SDNode *N,
9486                                    TargetLowering::DAGCombinerInfo &DCI) {
9487   StoreSDNode *St = cast<StoreSDNode>(N);
9488   if (St->isVolatile())
9489     return SDValue();
9490
9491   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9492   // pack all of the elements in one place.  Next, store to memory in fewer
9493   // chunks.
9494   SDValue StVal = St->getValue();
9495   EVT VT = StVal.getValueType();
9496   if (St->isTruncatingStore() && VT.isVector()) {
9497     SelectionDAG &DAG = DCI.DAG;
9498     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9499     EVT StVT = St->getMemoryVT();
9500     unsigned NumElems = VT.getVectorNumElements();
9501     assert(StVT != VT && "Cannot truncate to the same type");
9502     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9503     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9504
9505     // From, To sizes and ElemCount must be pow of two
9506     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9507
9508     // We are going to use the original vector elt for storing.
9509     // Accumulated smaller vector elements must be a multiple of the store size.
9510     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9511
9512     unsigned SizeRatio  = FromEltSz / ToEltSz;
9513     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9514
9515     // Create a type on which we perform the shuffle.
9516     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9517                                      NumElems*SizeRatio);
9518     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9519
9520     SDLoc DL(St);
9521     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9522     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9523     for (unsigned i = 0; i < NumElems; ++i)
9524       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9525                           ? (i + 1) * SizeRatio - 1
9526                           : i * SizeRatio;
9527
9528     // Can't shuffle using an illegal type.
9529     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9530
9531     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9532                                 DAG.getUNDEF(WideVec.getValueType()),
9533                                 ShuffleVec.data());
9534     // At this point all of the data is stored at the bottom of the
9535     // register. We now need to save it to mem.
9536
9537     // Find the largest store unit
9538     MVT StoreType = MVT::i8;
9539     for (MVT Tp : MVT::integer_valuetypes()) {
9540       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9541         StoreType = Tp;
9542     }
9543     // Didn't find a legal store type.
9544     if (!TLI.isTypeLegal(StoreType))
9545       return SDValue();
9546
9547     // Bitcast the original vector into a vector of store-size units
9548     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9549             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9550     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9551     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9552     SmallVector<SDValue, 8> Chains;
9553     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9554                                         TLI.getPointerTy(DAG.getDataLayout()));
9555     SDValue BasePtr = St->getBasePtr();
9556
9557     // Perform one or more big stores into memory.
9558     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9559     for (unsigned I = 0; I < E; I++) {
9560       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9561                                    StoreType, ShuffWide,
9562                                    DAG.getIntPtrConstant(I, DL));
9563       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9564                                 St->getPointerInfo(), St->isVolatile(),
9565                                 St->isNonTemporal(), St->getAlignment());
9566       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9567                             Increment);
9568       Chains.push_back(Ch);
9569     }
9570     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9571   }
9572
9573   if (!ISD::isNormalStore(St))
9574     return SDValue();
9575
9576   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9577   // ARM stores of arguments in the same cache line.
9578   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9579       StVal.getNode()->hasOneUse()) {
9580     SelectionDAG  &DAG = DCI.DAG;
9581     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9582     SDLoc DL(St);
9583     SDValue BasePtr = St->getBasePtr();
9584     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9585                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9586                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9587                                   St->isNonTemporal(), St->getAlignment());
9588
9589     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9590                                     DAG.getConstant(4, DL, MVT::i32));
9591     return DAG.getStore(NewST1.getValue(0), DL,
9592                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9593                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9594                         St->isNonTemporal(),
9595                         std::min(4U, St->getAlignment() / 2));
9596   }
9597
9598   if (StVal.getValueType() == MVT::i64 &&
9599       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9600
9601     // Bitcast an i64 store extracted from a vector to f64.
9602     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9603     SelectionDAG &DAG = DCI.DAG;
9604     SDLoc dl(StVal);
9605     SDValue IntVec = StVal.getOperand(0);
9606     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9607                                    IntVec.getValueType().getVectorNumElements());
9608     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9609     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9610                                  Vec, StVal.getOperand(1));
9611     dl = SDLoc(N);
9612     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9613     // Make the DAGCombiner fold the bitcasts.
9614     DCI.AddToWorklist(Vec.getNode());
9615     DCI.AddToWorklist(ExtElt.getNode());
9616     DCI.AddToWorklist(V.getNode());
9617     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9618                         St->getPointerInfo(), St->isVolatile(),
9619                         St->isNonTemporal(), St->getAlignment(),
9620                         St->getAAInfo());
9621   }
9622
9623   // If this is a legal vector store, try to combine it into a VST1_UPD.
9624   if (ISD::isNormalStore(N) && VT.isVector() &&
9625       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9626     return CombineBaseUpdate(N, DCI);
9627
9628   return SDValue();
9629 }
9630
9631 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9632 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9633 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9634 {
9635   integerPart cN;
9636   integerPart c0 = 0;
9637   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9638        I != E; I++) {
9639     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9640     if (!C)
9641       return false;
9642
9643     bool isExact;
9644     APFloat APF = C->getValueAPF();
9645     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9646         != APFloat::opOK || !isExact)
9647       return false;
9648
9649     c0 = (I == 0) ? cN : c0;
9650     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9651       return false;
9652   }
9653   C = c0;
9654   return true;
9655 }
9656
9657 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9658 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9659 /// when the VMUL has a constant operand that is a power of 2.
9660 ///
9661 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9662 ///  vmul.f32        d16, d17, d16
9663 ///  vcvt.s32.f32    d16, d16
9664 /// becomes:
9665 ///  vcvt.s32.f32    d16, d16, #3
9666 static SDValue PerformVCVTCombine(SDNode *N,
9667                                   TargetLowering::DAGCombinerInfo &DCI,
9668                                   const ARMSubtarget *Subtarget) {
9669   SelectionDAG &DAG = DCI.DAG;
9670   SDValue Op = N->getOperand(0);
9671
9672   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9673       Op.getOpcode() != ISD::FMUL)
9674     return SDValue();
9675
9676   uint64_t C;
9677   SDValue N0 = Op->getOperand(0);
9678   SDValue ConstVec = Op->getOperand(1);
9679   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9680
9681   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9682       !isConstVecPow2(ConstVec, isSigned, C))
9683     return SDValue();
9684
9685   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9686   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9687   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9688   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9689       NumLanes > 4) {
9690     // These instructions only exist converting from f32 to i32. We can handle
9691     // smaller integers by generating an extra truncate, but larger ones would
9692     // be lossy. We also can't handle more then 4 lanes, since these intructions
9693     // only support v2i32/v4i32 types.
9694     return SDValue();
9695   }
9696
9697   SDLoc dl(N);
9698   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9699     Intrinsic::arm_neon_vcvtfp2fxu;
9700   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9701                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9702                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9703                                  N0,
9704                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9705
9706   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9707     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9708
9709   return FixConv;
9710 }
9711
9712 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9713 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9714 /// when the VDIV has a constant operand that is a power of 2.
9715 ///
9716 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9717 ///  vcvt.f32.s32    d16, d16
9718 ///  vdiv.f32        d16, d17, d16
9719 /// becomes:
9720 ///  vcvt.f32.s32    d16, d16, #3
9721 static SDValue PerformVDIVCombine(SDNode *N,
9722                                   TargetLowering::DAGCombinerInfo &DCI,
9723                                   const ARMSubtarget *Subtarget) {
9724   SelectionDAG &DAG = DCI.DAG;
9725   SDValue Op = N->getOperand(0);
9726   unsigned OpOpcode = Op.getNode()->getOpcode();
9727
9728   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9729       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9730     return SDValue();
9731
9732   uint64_t C;
9733   SDValue ConstVec = N->getOperand(1);
9734   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9735
9736   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9737       !isConstVecPow2(ConstVec, isSigned, C))
9738     return SDValue();
9739
9740   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9741   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9742   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9743     // These instructions only exist converting from i32 to f32. We can handle
9744     // smaller integers by generating an extra extend, but larger ones would
9745     // be lossy.
9746     return SDValue();
9747   }
9748
9749   SDLoc dl(N);
9750   SDValue ConvInput = Op.getOperand(0);
9751   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9752   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9753     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9754                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9755                             ConvInput);
9756
9757   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9758     Intrinsic::arm_neon_vcvtfxu2fp;
9759   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9760                      Op.getValueType(),
9761                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9762                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9763 }
9764
9765 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9766 /// operand of a vector shift operation, where all the elements of the
9767 /// build_vector must have the same constant integer value.
9768 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9769   // Ignore bit_converts.
9770   while (Op.getOpcode() == ISD::BITCAST)
9771     Op = Op.getOperand(0);
9772   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9773   APInt SplatBits, SplatUndef;
9774   unsigned SplatBitSize;
9775   bool HasAnyUndefs;
9776   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9777                                       HasAnyUndefs, ElementBits) ||
9778       SplatBitSize > ElementBits)
9779     return false;
9780   Cnt = SplatBits.getSExtValue();
9781   return true;
9782 }
9783
9784 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9785 /// operand of a vector shift left operation.  That value must be in the range:
9786 ///   0 <= Value < ElementBits for a left shift; or
9787 ///   0 <= Value <= ElementBits for a long left shift.
9788 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9789   assert(VT.isVector() && "vector shift count is not a vector type");
9790   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9791   if (! getVShiftImm(Op, ElementBits, Cnt))
9792     return false;
9793   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9794 }
9795
9796 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9797 /// operand of a vector shift right operation.  For a shift opcode, the value
9798 /// is positive, but for an intrinsic the value count must be negative. The
9799 /// absolute value must be in the range:
9800 ///   1 <= |Value| <= ElementBits for a right shift; or
9801 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9802 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9803                          int64_t &Cnt) {
9804   assert(VT.isVector() && "vector shift count is not a vector type");
9805   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9806   if (! getVShiftImm(Op, ElementBits, Cnt))
9807     return false;
9808   if (!isIntrinsic)
9809     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9810   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9811     Cnt = -Cnt;
9812     return true;
9813   }
9814   return false;
9815 }
9816
9817 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9818 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9819   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9820   switch (IntNo) {
9821   default:
9822     // Don't do anything for most intrinsics.
9823     break;
9824
9825   case Intrinsic::arm_neon_vabds:
9826     if (!N->getValueType(0).isInteger())
9827       return SDValue();
9828     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9829                        N->getOperand(1), N->getOperand(2));
9830   case Intrinsic::arm_neon_vabdu:
9831     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9832                        N->getOperand(1), N->getOperand(2));
9833
9834   // Vector shifts: check for immediate versions and lower them.
9835   // Note: This is done during DAG combining instead of DAG legalizing because
9836   // the build_vectors for 64-bit vector element shift counts are generally
9837   // not legal, and it is hard to see their values after they get legalized to
9838   // loads from a constant pool.
9839   case Intrinsic::arm_neon_vshifts:
9840   case Intrinsic::arm_neon_vshiftu:
9841   case Intrinsic::arm_neon_vrshifts:
9842   case Intrinsic::arm_neon_vrshiftu:
9843   case Intrinsic::arm_neon_vrshiftn:
9844   case Intrinsic::arm_neon_vqshifts:
9845   case Intrinsic::arm_neon_vqshiftu:
9846   case Intrinsic::arm_neon_vqshiftsu:
9847   case Intrinsic::arm_neon_vqshiftns:
9848   case Intrinsic::arm_neon_vqshiftnu:
9849   case Intrinsic::arm_neon_vqshiftnsu:
9850   case Intrinsic::arm_neon_vqrshiftns:
9851   case Intrinsic::arm_neon_vqrshiftnu:
9852   case Intrinsic::arm_neon_vqrshiftnsu: {
9853     EVT VT = N->getOperand(1).getValueType();
9854     int64_t Cnt;
9855     unsigned VShiftOpc = 0;
9856
9857     switch (IntNo) {
9858     case Intrinsic::arm_neon_vshifts:
9859     case Intrinsic::arm_neon_vshiftu:
9860       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9861         VShiftOpc = ARMISD::VSHL;
9862         break;
9863       }
9864       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9865         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9866                      ARMISD::VSHRs : ARMISD::VSHRu);
9867         break;
9868       }
9869       return SDValue();
9870
9871     case Intrinsic::arm_neon_vrshifts:
9872     case Intrinsic::arm_neon_vrshiftu:
9873       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9874         break;
9875       return SDValue();
9876
9877     case Intrinsic::arm_neon_vqshifts:
9878     case Intrinsic::arm_neon_vqshiftu:
9879       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9880         break;
9881       return SDValue();
9882
9883     case Intrinsic::arm_neon_vqshiftsu:
9884       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9885         break;
9886       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9887
9888     case Intrinsic::arm_neon_vrshiftn:
9889     case Intrinsic::arm_neon_vqshiftns:
9890     case Intrinsic::arm_neon_vqshiftnu:
9891     case Intrinsic::arm_neon_vqshiftnsu:
9892     case Intrinsic::arm_neon_vqrshiftns:
9893     case Intrinsic::arm_neon_vqrshiftnu:
9894     case Intrinsic::arm_neon_vqrshiftnsu:
9895       // Narrowing shifts require an immediate right shift.
9896       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9897         break;
9898       llvm_unreachable("invalid shift count for narrowing vector shift "
9899                        "intrinsic");
9900
9901     default:
9902       llvm_unreachable("unhandled vector shift");
9903     }
9904
9905     switch (IntNo) {
9906     case Intrinsic::arm_neon_vshifts:
9907     case Intrinsic::arm_neon_vshiftu:
9908       // Opcode already set above.
9909       break;
9910     case Intrinsic::arm_neon_vrshifts:
9911       VShiftOpc = ARMISD::VRSHRs; break;
9912     case Intrinsic::arm_neon_vrshiftu:
9913       VShiftOpc = ARMISD::VRSHRu; break;
9914     case Intrinsic::arm_neon_vrshiftn:
9915       VShiftOpc = ARMISD::VRSHRN; break;
9916     case Intrinsic::arm_neon_vqshifts:
9917       VShiftOpc = ARMISD::VQSHLs; break;
9918     case Intrinsic::arm_neon_vqshiftu:
9919       VShiftOpc = ARMISD::VQSHLu; break;
9920     case Intrinsic::arm_neon_vqshiftsu:
9921       VShiftOpc = ARMISD::VQSHLsu; break;
9922     case Intrinsic::arm_neon_vqshiftns:
9923       VShiftOpc = ARMISD::VQSHRNs; break;
9924     case Intrinsic::arm_neon_vqshiftnu:
9925       VShiftOpc = ARMISD::VQSHRNu; break;
9926     case Intrinsic::arm_neon_vqshiftnsu:
9927       VShiftOpc = ARMISD::VQSHRNsu; break;
9928     case Intrinsic::arm_neon_vqrshiftns:
9929       VShiftOpc = ARMISD::VQRSHRNs; break;
9930     case Intrinsic::arm_neon_vqrshiftnu:
9931       VShiftOpc = ARMISD::VQRSHRNu; break;
9932     case Intrinsic::arm_neon_vqrshiftnsu:
9933       VShiftOpc = ARMISD::VQRSHRNsu; break;
9934     }
9935
9936     SDLoc dl(N);
9937     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9938                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9939   }
9940
9941   case Intrinsic::arm_neon_vshiftins: {
9942     EVT VT = N->getOperand(1).getValueType();
9943     int64_t Cnt;
9944     unsigned VShiftOpc = 0;
9945
9946     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9947       VShiftOpc = ARMISD::VSLI;
9948     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9949       VShiftOpc = ARMISD::VSRI;
9950     else {
9951       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9952     }
9953
9954     SDLoc dl(N);
9955     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9956                        N->getOperand(1), N->getOperand(2),
9957                        DAG.getConstant(Cnt, dl, MVT::i32));
9958   }
9959
9960   case Intrinsic::arm_neon_vqrshifts:
9961   case Intrinsic::arm_neon_vqrshiftu:
9962     // No immediate versions of these to check for.
9963     break;
9964   }
9965
9966   return SDValue();
9967 }
9968
9969 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9970 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9971 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9972 /// vector element shift counts are generally not legal, and it is hard to see
9973 /// their values after they get legalized to loads from a constant pool.
9974 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9975                                    const ARMSubtarget *ST) {
9976   EVT VT = N->getValueType(0);
9977   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9978     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9979     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9980     SDValue N1 = N->getOperand(1);
9981     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9982       SDValue N0 = N->getOperand(0);
9983       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9984           DAG.MaskedValueIsZero(N0.getOperand(0),
9985                                 APInt::getHighBitsSet(32, 16)))
9986         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9987     }
9988   }
9989
9990   // Nothing to be done for scalar shifts.
9991   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9992   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9993     return SDValue();
9994
9995   assert(ST->hasNEON() && "unexpected vector shift");
9996   int64_t Cnt;
9997
9998   switch (N->getOpcode()) {
9999   default: llvm_unreachable("unexpected shift opcode");
10000
10001   case ISD::SHL:
10002     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10003       SDLoc dl(N);
10004       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10005                          DAG.getConstant(Cnt, dl, MVT::i32));
10006     }
10007     break;
10008
10009   case ISD::SRA:
10010   case ISD::SRL:
10011     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10012       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10013                             ARMISD::VSHRs : ARMISD::VSHRu);
10014       SDLoc dl(N);
10015       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10016                          DAG.getConstant(Cnt, dl, MVT::i32));
10017     }
10018   }
10019   return SDValue();
10020 }
10021
10022 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10023 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10024 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10025                                     const ARMSubtarget *ST) {
10026   SDValue N0 = N->getOperand(0);
10027
10028   // Check for sign- and zero-extensions of vector extract operations of 8-
10029   // and 16-bit vector elements.  NEON supports these directly.  They are
10030   // handled during DAG combining because type legalization will promote them
10031   // to 32-bit types and it is messy to recognize the operations after that.
10032   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10033     SDValue Vec = N0.getOperand(0);
10034     SDValue Lane = N0.getOperand(1);
10035     EVT VT = N->getValueType(0);
10036     EVT EltVT = N0.getValueType();
10037     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10038
10039     if (VT == MVT::i32 &&
10040         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10041         TLI.isTypeLegal(Vec.getValueType()) &&
10042         isa<ConstantSDNode>(Lane)) {
10043
10044       unsigned Opc = 0;
10045       switch (N->getOpcode()) {
10046       default: llvm_unreachable("unexpected opcode");
10047       case ISD::SIGN_EXTEND:
10048         Opc = ARMISD::VGETLANEs;
10049         break;
10050       case ISD::ZERO_EXTEND:
10051       case ISD::ANY_EXTEND:
10052         Opc = ARMISD::VGETLANEu;
10053         break;
10054       }
10055       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10056     }
10057   }
10058
10059   return SDValue();
10060 }
10061
10062 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10063 SDValue
10064 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10065   SDValue Cmp = N->getOperand(4);
10066   if (Cmp.getOpcode() != ARMISD::CMPZ)
10067     // Only looking at EQ and NE cases.
10068     return SDValue();
10069
10070   EVT VT = N->getValueType(0);
10071   SDLoc dl(N);
10072   SDValue LHS = Cmp.getOperand(0);
10073   SDValue RHS = Cmp.getOperand(1);
10074   SDValue FalseVal = N->getOperand(0);
10075   SDValue TrueVal = N->getOperand(1);
10076   SDValue ARMcc = N->getOperand(2);
10077   ARMCC::CondCodes CC =
10078     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10079
10080   // Simplify
10081   //   mov     r1, r0
10082   //   cmp     r1, x
10083   //   mov     r0, y
10084   //   moveq   r0, x
10085   // to
10086   //   cmp     r0, x
10087   //   movne   r0, y
10088   //
10089   //   mov     r1, r0
10090   //   cmp     r1, x
10091   //   mov     r0, x
10092   //   movne   r0, y
10093   // to
10094   //   cmp     r0, x
10095   //   movne   r0, y
10096   /// FIXME: Turn this into a target neutral optimization?
10097   SDValue Res;
10098   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10099     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10100                       N->getOperand(3), Cmp);
10101   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10102     SDValue ARMcc;
10103     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10104     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10105                       N->getOperand(3), NewCmp);
10106   }
10107
10108   if (Res.getNode()) {
10109     APInt KnownZero, KnownOne;
10110     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10111     // Capture demanded bits information that would be otherwise lost.
10112     if (KnownZero == 0xfffffffe)
10113       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10114                         DAG.getValueType(MVT::i1));
10115     else if (KnownZero == 0xffffff00)
10116       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10117                         DAG.getValueType(MVT::i8));
10118     else if (KnownZero == 0xffff0000)
10119       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10120                         DAG.getValueType(MVT::i16));
10121   }
10122
10123   return Res;
10124 }
10125
10126 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10127                                              DAGCombinerInfo &DCI) const {
10128   switch (N->getOpcode()) {
10129   default: break;
10130   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10131   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10132   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10133   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10134   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10135   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10136   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10137   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10138   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10139   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10140   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10141   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10142   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10143   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10144   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10145   case ISD::FP_TO_SINT:
10146   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10147   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10148   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10149   case ISD::SHL:
10150   case ISD::SRA:
10151   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10152   case ISD::SIGN_EXTEND:
10153   case ISD::ZERO_EXTEND:
10154   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10155   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10156   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10157   case ARMISD::VLD2DUP:
10158   case ARMISD::VLD3DUP:
10159   case ARMISD::VLD4DUP:
10160     return PerformVLDCombine(N, DCI);
10161   case ARMISD::BUILD_VECTOR:
10162     return PerformARMBUILD_VECTORCombine(N, DCI);
10163   case ISD::INTRINSIC_VOID:
10164   case ISD::INTRINSIC_W_CHAIN:
10165     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10166     case Intrinsic::arm_neon_vld1:
10167     case Intrinsic::arm_neon_vld2:
10168     case Intrinsic::arm_neon_vld3:
10169     case Intrinsic::arm_neon_vld4:
10170     case Intrinsic::arm_neon_vld2lane:
10171     case Intrinsic::arm_neon_vld3lane:
10172     case Intrinsic::arm_neon_vld4lane:
10173     case Intrinsic::arm_neon_vst1:
10174     case Intrinsic::arm_neon_vst2:
10175     case Intrinsic::arm_neon_vst3:
10176     case Intrinsic::arm_neon_vst4:
10177     case Intrinsic::arm_neon_vst2lane:
10178     case Intrinsic::arm_neon_vst3lane:
10179     case Intrinsic::arm_neon_vst4lane:
10180       return PerformVLDCombine(N, DCI);
10181     default: break;
10182     }
10183     break;
10184   }
10185   return SDValue();
10186 }
10187
10188 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10189                                                           EVT VT) const {
10190   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10191 }
10192
10193 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10194                                                        unsigned,
10195                                                        unsigned,
10196                                                        bool *Fast) const {
10197   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10198   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10199
10200   switch (VT.getSimpleVT().SimpleTy) {
10201   default:
10202     return false;
10203   case MVT::i8:
10204   case MVT::i16:
10205   case MVT::i32: {
10206     // Unaligned access can use (for example) LRDB, LRDH, LDR
10207     if (AllowsUnaligned) {
10208       if (Fast)
10209         *Fast = Subtarget->hasV7Ops();
10210       return true;
10211     }
10212     return false;
10213   }
10214   case MVT::f64:
10215   case MVT::v2f64: {
10216     // For any little-endian targets with neon, we can support unaligned ld/st
10217     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10218     // A big-endian target may also explicitly support unaligned accesses
10219     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10220       if (Fast)
10221         *Fast = true;
10222       return true;
10223     }
10224     return false;
10225   }
10226   }
10227 }
10228
10229 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10230                        unsigned AlignCheck) {
10231   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10232           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10233 }
10234
10235 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10236                                            unsigned DstAlign, unsigned SrcAlign,
10237                                            bool IsMemset, bool ZeroMemset,
10238                                            bool MemcpyStrSrc,
10239                                            MachineFunction &MF) const {
10240   const Function *F = MF.getFunction();
10241
10242   // See if we can use NEON instructions for this...
10243   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10244       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10245     bool Fast;
10246     if (Size >= 16 &&
10247         (memOpAlign(SrcAlign, DstAlign, 16) ||
10248          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10249       return MVT::v2f64;
10250     } else if (Size >= 8 &&
10251                (memOpAlign(SrcAlign, DstAlign, 8) ||
10252                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10253                  Fast))) {
10254       return MVT::f64;
10255     }
10256   }
10257
10258   // Lowering to i32/i16 if the size permits.
10259   if (Size >= 4)
10260     return MVT::i32;
10261   else if (Size >= 2)
10262     return MVT::i16;
10263
10264   // Let the target-independent logic figure it out.
10265   return MVT::Other;
10266 }
10267
10268 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10269   if (Val.getOpcode() != ISD::LOAD)
10270     return false;
10271
10272   EVT VT1 = Val.getValueType();
10273   if (!VT1.isSimple() || !VT1.isInteger() ||
10274       !VT2.isSimple() || !VT2.isInteger())
10275     return false;
10276
10277   switch (VT1.getSimpleVT().SimpleTy) {
10278   default: break;
10279   case MVT::i1:
10280   case MVT::i8:
10281   case MVT::i16:
10282     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10283     return true;
10284   }
10285
10286   return false;
10287 }
10288
10289 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10290   EVT VT = ExtVal.getValueType();
10291
10292   if (!isTypeLegal(VT))
10293     return false;
10294
10295   // Don't create a loadext if we can fold the extension into a wide/long
10296   // instruction.
10297   // If there's more than one user instruction, the loadext is desirable no
10298   // matter what.  There can be two uses by the same instruction.
10299   if (ExtVal->use_empty() ||
10300       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10301     return true;
10302
10303   SDNode *U = *ExtVal->use_begin();
10304   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10305        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10306     return false;
10307
10308   return true;
10309 }
10310
10311 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10312   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10313     return false;
10314
10315   if (!isTypeLegal(EVT::getEVT(Ty1)))
10316     return false;
10317
10318   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10319
10320   // Assuming the caller doesn't have a zeroext or signext return parameter,
10321   // truncation all the way down to i1 is valid.
10322   return true;
10323 }
10324
10325
10326 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10327   if (V < 0)
10328     return false;
10329
10330   unsigned Scale = 1;
10331   switch (VT.getSimpleVT().SimpleTy) {
10332   default: return false;
10333   case MVT::i1:
10334   case MVT::i8:
10335     // Scale == 1;
10336     break;
10337   case MVT::i16:
10338     // Scale == 2;
10339     Scale = 2;
10340     break;
10341   case MVT::i32:
10342     // Scale == 4;
10343     Scale = 4;
10344     break;
10345   }
10346
10347   if ((V & (Scale - 1)) != 0)
10348     return false;
10349   V /= Scale;
10350   return V == (V & ((1LL << 5) - 1));
10351 }
10352
10353 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10354                                       const ARMSubtarget *Subtarget) {
10355   bool isNeg = false;
10356   if (V < 0) {
10357     isNeg = true;
10358     V = - V;
10359   }
10360
10361   switch (VT.getSimpleVT().SimpleTy) {
10362   default: return false;
10363   case MVT::i1:
10364   case MVT::i8:
10365   case MVT::i16:
10366   case MVT::i32:
10367     // + imm12 or - imm8
10368     if (isNeg)
10369       return V == (V & ((1LL << 8) - 1));
10370     return V == (V & ((1LL << 12) - 1));
10371   case MVT::f32:
10372   case MVT::f64:
10373     // Same as ARM mode. FIXME: NEON?
10374     if (!Subtarget->hasVFP2())
10375       return false;
10376     if ((V & 3) != 0)
10377       return false;
10378     V >>= 2;
10379     return V == (V & ((1LL << 8) - 1));
10380   }
10381 }
10382
10383 /// isLegalAddressImmediate - Return true if the integer value can be used
10384 /// as the offset of the target addressing mode for load / store of the
10385 /// given type.
10386 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10387                                     const ARMSubtarget *Subtarget) {
10388   if (V == 0)
10389     return true;
10390
10391   if (!VT.isSimple())
10392     return false;
10393
10394   if (Subtarget->isThumb1Only())
10395     return isLegalT1AddressImmediate(V, VT);
10396   else if (Subtarget->isThumb2())
10397     return isLegalT2AddressImmediate(V, VT, Subtarget);
10398
10399   // ARM mode.
10400   if (V < 0)
10401     V = - V;
10402   switch (VT.getSimpleVT().SimpleTy) {
10403   default: return false;
10404   case MVT::i1:
10405   case MVT::i8:
10406   case MVT::i32:
10407     // +- imm12
10408     return V == (V & ((1LL << 12) - 1));
10409   case MVT::i16:
10410     // +- imm8
10411     return V == (V & ((1LL << 8) - 1));
10412   case MVT::f32:
10413   case MVT::f64:
10414     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10415       return false;
10416     if ((V & 3) != 0)
10417       return false;
10418     V >>= 2;
10419     return V == (V & ((1LL << 8) - 1));
10420   }
10421 }
10422
10423 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10424                                                       EVT VT) const {
10425   int Scale = AM.Scale;
10426   if (Scale < 0)
10427     return false;
10428
10429   switch (VT.getSimpleVT().SimpleTy) {
10430   default: return false;
10431   case MVT::i1:
10432   case MVT::i8:
10433   case MVT::i16:
10434   case MVT::i32:
10435     if (Scale == 1)
10436       return true;
10437     // r + r << imm
10438     Scale = Scale & ~1;
10439     return Scale == 2 || Scale == 4 || Scale == 8;
10440   case MVT::i64:
10441     // r + r
10442     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10443       return true;
10444     return false;
10445   case MVT::isVoid:
10446     // Note, we allow "void" uses (basically, uses that aren't loads or
10447     // stores), because arm allows folding a scale into many arithmetic
10448     // operations.  This should be made more precise and revisited later.
10449
10450     // Allow r << imm, but the imm has to be a multiple of two.
10451     if (Scale & 1) return false;
10452     return isPowerOf2_32(Scale);
10453   }
10454 }
10455
10456 /// isLegalAddressingMode - Return true if the addressing mode represented
10457 /// by AM is legal for this target, for a load/store of the specified type.
10458 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10459                                               const AddrMode &AM, Type *Ty,
10460                                               unsigned AS) const {
10461   EVT VT = getValueType(DL, Ty, true);
10462   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10463     return false;
10464
10465   // Can never fold addr of global into load/store.
10466   if (AM.BaseGV)
10467     return false;
10468
10469   switch (AM.Scale) {
10470   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10471     break;
10472   case 1:
10473     if (Subtarget->isThumb1Only())
10474       return false;
10475     // FALL THROUGH.
10476   default:
10477     // ARM doesn't support any R+R*scale+imm addr modes.
10478     if (AM.BaseOffs)
10479       return false;
10480
10481     if (!VT.isSimple())
10482       return false;
10483
10484     if (Subtarget->isThumb2())
10485       return isLegalT2ScaledAddressingMode(AM, VT);
10486
10487     int Scale = AM.Scale;
10488     switch (VT.getSimpleVT().SimpleTy) {
10489     default: return false;
10490     case MVT::i1:
10491     case MVT::i8:
10492     case MVT::i32:
10493       if (Scale < 0) Scale = -Scale;
10494       if (Scale == 1)
10495         return true;
10496       // r + r << imm
10497       return isPowerOf2_32(Scale & ~1);
10498     case MVT::i16:
10499     case MVT::i64:
10500       // r + r
10501       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10502         return true;
10503       return false;
10504
10505     case MVT::isVoid:
10506       // Note, we allow "void" uses (basically, uses that aren't loads or
10507       // stores), because arm allows folding a scale into many arithmetic
10508       // operations.  This should be made more precise and revisited later.
10509
10510       // Allow r << imm, but the imm has to be a multiple of two.
10511       if (Scale & 1) return false;
10512       return isPowerOf2_32(Scale);
10513     }
10514   }
10515   return true;
10516 }
10517
10518 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10519 /// icmp immediate, that is the target has icmp instructions which can compare
10520 /// a register against the immediate without having to materialize the
10521 /// immediate into a register.
10522 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10523   // Thumb2 and ARM modes can use cmn for negative immediates.
10524   if (!Subtarget->isThumb())
10525     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10526   if (Subtarget->isThumb2())
10527     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10528   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10529   return Imm >= 0 && Imm <= 255;
10530 }
10531
10532 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10533 /// *or sub* immediate, that is the target has add or sub instructions which can
10534 /// add a register with the immediate without having to materialize the
10535 /// immediate into a register.
10536 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10537   // Same encoding for add/sub, just flip the sign.
10538   int64_t AbsImm = std::abs(Imm);
10539   if (!Subtarget->isThumb())
10540     return ARM_AM::getSOImmVal(AbsImm) != -1;
10541   if (Subtarget->isThumb2())
10542     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10543   // Thumb1 only has 8-bit unsigned immediate.
10544   return AbsImm >= 0 && AbsImm <= 255;
10545 }
10546
10547 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10548                                       bool isSEXTLoad, SDValue &Base,
10549                                       SDValue &Offset, bool &isInc,
10550                                       SelectionDAG &DAG) {
10551   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10552     return false;
10553
10554   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10555     // AddressingMode 3
10556     Base = Ptr->getOperand(0);
10557     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10558       int RHSC = (int)RHS->getZExtValue();
10559       if (RHSC < 0 && RHSC > -256) {
10560         assert(Ptr->getOpcode() == ISD::ADD);
10561         isInc = false;
10562         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10563         return true;
10564       }
10565     }
10566     isInc = (Ptr->getOpcode() == ISD::ADD);
10567     Offset = Ptr->getOperand(1);
10568     return true;
10569   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10570     // AddressingMode 2
10571     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10572       int RHSC = (int)RHS->getZExtValue();
10573       if (RHSC < 0 && RHSC > -0x1000) {
10574         assert(Ptr->getOpcode() == ISD::ADD);
10575         isInc = false;
10576         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10577         Base = Ptr->getOperand(0);
10578         return true;
10579       }
10580     }
10581
10582     if (Ptr->getOpcode() == ISD::ADD) {
10583       isInc = true;
10584       ARM_AM::ShiftOpc ShOpcVal=
10585         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10586       if (ShOpcVal != ARM_AM::no_shift) {
10587         Base = Ptr->getOperand(1);
10588         Offset = Ptr->getOperand(0);
10589       } else {
10590         Base = Ptr->getOperand(0);
10591         Offset = Ptr->getOperand(1);
10592       }
10593       return true;
10594     }
10595
10596     isInc = (Ptr->getOpcode() == ISD::ADD);
10597     Base = Ptr->getOperand(0);
10598     Offset = Ptr->getOperand(1);
10599     return true;
10600   }
10601
10602   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10603   return false;
10604 }
10605
10606 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10607                                      bool isSEXTLoad, SDValue &Base,
10608                                      SDValue &Offset, bool &isInc,
10609                                      SelectionDAG &DAG) {
10610   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10611     return false;
10612
10613   Base = Ptr->getOperand(0);
10614   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10615     int RHSC = (int)RHS->getZExtValue();
10616     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10617       assert(Ptr->getOpcode() == ISD::ADD);
10618       isInc = false;
10619       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10620       return true;
10621     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10622       isInc = Ptr->getOpcode() == ISD::ADD;
10623       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10624       return true;
10625     }
10626   }
10627
10628   return false;
10629 }
10630
10631 /// getPreIndexedAddressParts - returns true by value, base pointer and
10632 /// offset pointer and addressing mode by reference if the node's address
10633 /// can be legally represented as pre-indexed load / store address.
10634 bool
10635 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10636                                              SDValue &Offset,
10637                                              ISD::MemIndexedMode &AM,
10638                                              SelectionDAG &DAG) const {
10639   if (Subtarget->isThumb1Only())
10640     return false;
10641
10642   EVT VT;
10643   SDValue Ptr;
10644   bool isSEXTLoad = false;
10645   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10646     Ptr = LD->getBasePtr();
10647     VT  = LD->getMemoryVT();
10648     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10649   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10650     Ptr = ST->getBasePtr();
10651     VT  = ST->getMemoryVT();
10652   } else
10653     return false;
10654
10655   bool isInc;
10656   bool isLegal = false;
10657   if (Subtarget->isThumb2())
10658     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10659                                        Offset, isInc, DAG);
10660   else
10661     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10662                                         Offset, isInc, DAG);
10663   if (!isLegal)
10664     return false;
10665
10666   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10667   return true;
10668 }
10669
10670 /// getPostIndexedAddressParts - returns true by value, base pointer and
10671 /// offset pointer and addressing mode by reference if this node can be
10672 /// combined with a load / store to form a post-indexed load / store.
10673 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10674                                                    SDValue &Base,
10675                                                    SDValue &Offset,
10676                                                    ISD::MemIndexedMode &AM,
10677                                                    SelectionDAG &DAG) const {
10678   if (Subtarget->isThumb1Only())
10679     return false;
10680
10681   EVT VT;
10682   SDValue Ptr;
10683   bool isSEXTLoad = false;
10684   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10685     VT  = LD->getMemoryVT();
10686     Ptr = LD->getBasePtr();
10687     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10688   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10689     VT  = ST->getMemoryVT();
10690     Ptr = ST->getBasePtr();
10691   } else
10692     return false;
10693
10694   bool isInc;
10695   bool isLegal = false;
10696   if (Subtarget->isThumb2())
10697     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10698                                        isInc, DAG);
10699   else
10700     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10701                                         isInc, DAG);
10702   if (!isLegal)
10703     return false;
10704
10705   if (Ptr != Base) {
10706     // Swap base ptr and offset to catch more post-index load / store when
10707     // it's legal. In Thumb2 mode, offset must be an immediate.
10708     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10709         !Subtarget->isThumb2())
10710       std::swap(Base, Offset);
10711
10712     // Post-indexed load / store update the base pointer.
10713     if (Ptr != Base)
10714       return false;
10715   }
10716
10717   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10718   return true;
10719 }
10720
10721 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10722                                                       APInt &KnownZero,
10723                                                       APInt &KnownOne,
10724                                                       const SelectionDAG &DAG,
10725                                                       unsigned Depth) const {
10726   unsigned BitWidth = KnownOne.getBitWidth();
10727   KnownZero = KnownOne = APInt(BitWidth, 0);
10728   switch (Op.getOpcode()) {
10729   default: break;
10730   case ARMISD::ADDC:
10731   case ARMISD::ADDE:
10732   case ARMISD::SUBC:
10733   case ARMISD::SUBE:
10734     // These nodes' second result is a boolean
10735     if (Op.getResNo() == 0)
10736       break;
10737     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10738     break;
10739   case ARMISD::CMOV: {
10740     // Bits are known zero/one if known on the LHS and RHS.
10741     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10742     if (KnownZero == 0 && KnownOne == 0) return;
10743
10744     APInt KnownZeroRHS, KnownOneRHS;
10745     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10746     KnownZero &= KnownZeroRHS;
10747     KnownOne  &= KnownOneRHS;
10748     return;
10749   }
10750   case ISD::INTRINSIC_W_CHAIN: {
10751     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10752     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10753     switch (IntID) {
10754     default: return;
10755     case Intrinsic::arm_ldaex:
10756     case Intrinsic::arm_ldrex: {
10757       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10758       unsigned MemBits = VT.getScalarType().getSizeInBits();
10759       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10760       return;
10761     }
10762     }
10763   }
10764   }
10765 }
10766
10767 //===----------------------------------------------------------------------===//
10768 //                           ARM Inline Assembly Support
10769 //===----------------------------------------------------------------------===//
10770
10771 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10772   // Looking for "rev" which is V6+.
10773   if (!Subtarget->hasV6Ops())
10774     return false;
10775
10776   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10777   std::string AsmStr = IA->getAsmString();
10778   SmallVector<StringRef, 4> AsmPieces;
10779   SplitString(AsmStr, AsmPieces, ";\n");
10780
10781   switch (AsmPieces.size()) {
10782   default: return false;
10783   case 1:
10784     AsmStr = AsmPieces[0];
10785     AsmPieces.clear();
10786     SplitString(AsmStr, AsmPieces, " \t,");
10787
10788     // rev $0, $1
10789     if (AsmPieces.size() == 3 &&
10790         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10791         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10792       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10793       if (Ty && Ty->getBitWidth() == 32)
10794         return IntrinsicLowering::LowerToByteSwap(CI);
10795     }
10796     break;
10797   }
10798
10799   return false;
10800 }
10801
10802 /// getConstraintType - Given a constraint letter, return the type of
10803 /// constraint it is for this target.
10804 ARMTargetLowering::ConstraintType
10805 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10806   if (Constraint.size() == 1) {
10807     switch (Constraint[0]) {
10808     default:  break;
10809     case 'l': return C_RegisterClass;
10810     case 'w': return C_RegisterClass;
10811     case 'h': return C_RegisterClass;
10812     case 'x': return C_RegisterClass;
10813     case 't': return C_RegisterClass;
10814     case 'j': return C_Other; // Constant for movw.
10815       // An address with a single base register. Due to the way we
10816       // currently handle addresses it is the same as an 'r' memory constraint.
10817     case 'Q': return C_Memory;
10818     }
10819   } else if (Constraint.size() == 2) {
10820     switch (Constraint[0]) {
10821     default: break;
10822     // All 'U+' constraints are addresses.
10823     case 'U': return C_Memory;
10824     }
10825   }
10826   return TargetLowering::getConstraintType(Constraint);
10827 }
10828
10829 /// Examine constraint type and operand type and determine a weight value.
10830 /// This object must already have been set up with the operand type
10831 /// and the current alternative constraint selected.
10832 TargetLowering::ConstraintWeight
10833 ARMTargetLowering::getSingleConstraintMatchWeight(
10834     AsmOperandInfo &info, const char *constraint) const {
10835   ConstraintWeight weight = CW_Invalid;
10836   Value *CallOperandVal = info.CallOperandVal;
10837     // If we don't have a value, we can't do a match,
10838     // but allow it at the lowest weight.
10839   if (!CallOperandVal)
10840     return CW_Default;
10841   Type *type = CallOperandVal->getType();
10842   // Look at the constraint type.
10843   switch (*constraint) {
10844   default:
10845     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10846     break;
10847   case 'l':
10848     if (type->isIntegerTy()) {
10849       if (Subtarget->isThumb())
10850         weight = CW_SpecificReg;
10851       else
10852         weight = CW_Register;
10853     }
10854     break;
10855   case 'w':
10856     if (type->isFloatingPointTy())
10857       weight = CW_Register;
10858     break;
10859   }
10860   return weight;
10861 }
10862
10863 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10864 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
10865     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
10866   if (Constraint.size() == 1) {
10867     // GCC ARM Constraint Letters
10868     switch (Constraint[0]) {
10869     case 'l': // Low regs or general regs.
10870       if (Subtarget->isThumb())
10871         return RCPair(0U, &ARM::tGPRRegClass);
10872       return RCPair(0U, &ARM::GPRRegClass);
10873     case 'h': // High regs or no regs.
10874       if (Subtarget->isThumb())
10875         return RCPair(0U, &ARM::hGPRRegClass);
10876       break;
10877     case 'r':
10878       if (Subtarget->isThumb1Only())
10879         return RCPair(0U, &ARM::tGPRRegClass);
10880       return RCPair(0U, &ARM::GPRRegClass);
10881     case 'w':
10882       if (VT == MVT::Other)
10883         break;
10884       if (VT == MVT::f32)
10885         return RCPair(0U, &ARM::SPRRegClass);
10886       if (VT.getSizeInBits() == 64)
10887         return RCPair(0U, &ARM::DPRRegClass);
10888       if (VT.getSizeInBits() == 128)
10889         return RCPair(0U, &ARM::QPRRegClass);
10890       break;
10891     case 'x':
10892       if (VT == MVT::Other)
10893         break;
10894       if (VT == MVT::f32)
10895         return RCPair(0U, &ARM::SPR_8RegClass);
10896       if (VT.getSizeInBits() == 64)
10897         return RCPair(0U, &ARM::DPR_8RegClass);
10898       if (VT.getSizeInBits() == 128)
10899         return RCPair(0U, &ARM::QPR_8RegClass);
10900       break;
10901     case 't':
10902       if (VT == MVT::f32)
10903         return RCPair(0U, &ARM::SPRRegClass);
10904       break;
10905     }
10906   }
10907   if (StringRef("{cc}").equals_lower(Constraint))
10908     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10909
10910   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10911 }
10912
10913 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10914 /// vector.  If it is invalid, don't add anything to Ops.
10915 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10916                                                      std::string &Constraint,
10917                                                      std::vector<SDValue>&Ops,
10918                                                      SelectionDAG &DAG) const {
10919   SDValue Result;
10920
10921   // Currently only support length 1 constraints.
10922   if (Constraint.length() != 1) return;
10923
10924   char ConstraintLetter = Constraint[0];
10925   switch (ConstraintLetter) {
10926   default: break;
10927   case 'j':
10928   case 'I': case 'J': case 'K': case 'L':
10929   case 'M': case 'N': case 'O':
10930     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10931     if (!C)
10932       return;
10933
10934     int64_t CVal64 = C->getSExtValue();
10935     int CVal = (int) CVal64;
10936     // None of these constraints allow values larger than 32 bits.  Check
10937     // that the value fits in an int.
10938     if (CVal != CVal64)
10939       return;
10940
10941     switch (ConstraintLetter) {
10942       case 'j':
10943         // Constant suitable for movw, must be between 0 and
10944         // 65535.
10945         if (Subtarget->hasV6T2Ops())
10946           if (CVal >= 0 && CVal <= 65535)
10947             break;
10948         return;
10949       case 'I':
10950         if (Subtarget->isThumb1Only()) {
10951           // This must be a constant between 0 and 255, for ADD
10952           // immediates.
10953           if (CVal >= 0 && CVal <= 255)
10954             break;
10955         } else if (Subtarget->isThumb2()) {
10956           // A constant that can be used as an immediate value in a
10957           // data-processing instruction.
10958           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10959             break;
10960         } else {
10961           // A constant that can be used as an immediate value in a
10962           // data-processing instruction.
10963           if (ARM_AM::getSOImmVal(CVal) != -1)
10964             break;
10965         }
10966         return;
10967
10968       case 'J':
10969         if (Subtarget->isThumb()) {  // FIXME thumb2
10970           // This must be a constant between -255 and -1, for negated ADD
10971           // immediates. This can be used in GCC with an "n" modifier that
10972           // prints the negated value, for use with SUB instructions. It is
10973           // not useful otherwise but is implemented for compatibility.
10974           if (CVal >= -255 && CVal <= -1)
10975             break;
10976         } else {
10977           // This must be a constant between -4095 and 4095. It is not clear
10978           // what this constraint is intended for. Implemented for
10979           // compatibility with GCC.
10980           if (CVal >= -4095 && CVal <= 4095)
10981             break;
10982         }
10983         return;
10984
10985       case 'K':
10986         if (Subtarget->isThumb1Only()) {
10987           // A 32-bit value where only one byte has a nonzero value. Exclude
10988           // zero to match GCC. This constraint is used by GCC internally for
10989           // constants that can be loaded with a move/shift combination.
10990           // It is not useful otherwise but is implemented for compatibility.
10991           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10992             break;
10993         } else if (Subtarget->isThumb2()) {
10994           // A constant whose bitwise inverse can be used as an immediate
10995           // value in a data-processing instruction. This can be used in GCC
10996           // with a "B" modifier that prints the inverted value, for use with
10997           // BIC and MVN instructions. It is not useful otherwise but is
10998           // implemented for compatibility.
10999           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11000             break;
11001         } else {
11002           // A constant whose bitwise inverse can be used as an immediate
11003           // value in a data-processing instruction. This can be used in GCC
11004           // with a "B" modifier that prints the inverted value, for use with
11005           // BIC and MVN instructions. It is not useful otherwise but is
11006           // implemented for compatibility.
11007           if (ARM_AM::getSOImmVal(~CVal) != -1)
11008             break;
11009         }
11010         return;
11011
11012       case 'L':
11013         if (Subtarget->isThumb1Only()) {
11014           // This must be a constant between -7 and 7,
11015           // for 3-operand ADD/SUB immediate instructions.
11016           if (CVal >= -7 && CVal < 7)
11017             break;
11018         } else if (Subtarget->isThumb2()) {
11019           // A constant whose negation can be used as an immediate value in a
11020           // data-processing instruction. This can be used in GCC with an "n"
11021           // modifier that prints the negated value, for use with SUB
11022           // instructions. It is not useful otherwise but is implemented for
11023           // compatibility.
11024           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11025             break;
11026         } else {
11027           // A constant whose negation can be used as an immediate value in a
11028           // data-processing instruction. This can be used in GCC with an "n"
11029           // modifier that prints the negated value, for use with SUB
11030           // instructions. It is not useful otherwise but is implemented for
11031           // compatibility.
11032           if (ARM_AM::getSOImmVal(-CVal) != -1)
11033             break;
11034         }
11035         return;
11036
11037       case 'M':
11038         if (Subtarget->isThumb()) { // FIXME thumb2
11039           // This must be a multiple of 4 between 0 and 1020, for
11040           // ADD sp + immediate.
11041           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11042             break;
11043         } else {
11044           // A power of two or a constant between 0 and 32.  This is used in
11045           // GCC for the shift amount on shifted register operands, but it is
11046           // useful in general for any shift amounts.
11047           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11048             break;
11049         }
11050         return;
11051
11052       case 'N':
11053         if (Subtarget->isThumb()) {  // FIXME thumb2
11054           // This must be a constant between 0 and 31, for shift amounts.
11055           if (CVal >= 0 && CVal <= 31)
11056             break;
11057         }
11058         return;
11059
11060       case 'O':
11061         if (Subtarget->isThumb()) {  // FIXME thumb2
11062           // This must be a multiple of 4 between -508 and 508, for
11063           // ADD/SUB sp = sp + immediate.
11064           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11065             break;
11066         }
11067         return;
11068     }
11069     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11070     break;
11071   }
11072
11073   if (Result.getNode()) {
11074     Ops.push_back(Result);
11075     return;
11076   }
11077   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11078 }
11079
11080 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11081   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11082          "Register-based DivRem lowering only");
11083   unsigned Opcode = Op->getOpcode();
11084   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11085          "Invalid opcode for Div/Rem lowering");
11086   bool isSigned = (Opcode == ISD::SDIVREM);
11087   EVT VT = Op->getValueType(0);
11088   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11089
11090   RTLIB::Libcall LC;
11091   switch (VT.getSimpleVT().SimpleTy) {
11092   default: llvm_unreachable("Unexpected request for libcall!");
11093   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11094   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11095   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11096   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11097   }
11098
11099   SDValue InChain = DAG.getEntryNode();
11100
11101   TargetLowering::ArgListTy Args;
11102   TargetLowering::ArgListEntry Entry;
11103   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11104     EVT ArgVT = Op->getOperand(i).getValueType();
11105     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11106     Entry.Node = Op->getOperand(i);
11107     Entry.Ty = ArgTy;
11108     Entry.isSExt = isSigned;
11109     Entry.isZExt = !isSigned;
11110     Args.push_back(Entry);
11111   }
11112
11113   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11114                                          getPointerTy(DAG.getDataLayout()));
11115
11116   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11117
11118   SDLoc dl(Op);
11119   TargetLowering::CallLoweringInfo CLI(DAG);
11120   CLI.setDebugLoc(dl).setChain(InChain)
11121     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11122     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11123
11124   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11125   return CallInfo.first;
11126 }
11127
11128 SDValue
11129 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11130   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11131   SDLoc DL(Op);
11132
11133   // Get the inputs.
11134   SDValue Chain = Op.getOperand(0);
11135   SDValue Size  = Op.getOperand(1);
11136
11137   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11138                               DAG.getConstant(2, DL, MVT::i32));
11139
11140   SDValue Flag;
11141   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11142   Flag = Chain.getValue(1);
11143
11144   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11145   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11146
11147   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11148   Chain = NewSP.getValue(1);
11149
11150   SDValue Ops[2] = { NewSP, Chain };
11151   return DAG.getMergeValues(Ops, DL);
11152 }
11153
11154 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11155   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11156          "Unexpected type for custom-lowering FP_EXTEND");
11157
11158   RTLIB::Libcall LC;
11159   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11160
11161   SDValue SrcVal = Op.getOperand(0);
11162   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11163                      /*isSigned*/ false, SDLoc(Op)).first;
11164 }
11165
11166 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11167   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11168          Subtarget->isFPOnlySP() &&
11169          "Unexpected type for custom-lowering FP_ROUND");
11170
11171   RTLIB::Libcall LC;
11172   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11173
11174   SDValue SrcVal = Op.getOperand(0);
11175   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11176                      /*isSigned*/ false, SDLoc(Op)).first;
11177 }
11178
11179 bool
11180 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11181   // The ARM target isn't yet aware of offsets.
11182   return false;
11183 }
11184
11185 bool ARM::isBitFieldInvertedMask(unsigned v) {
11186   if (v == 0xffffffff)
11187     return false;
11188
11189   // there can be 1's on either or both "outsides", all the "inside"
11190   // bits must be 0's
11191   return isShiftedMask_32(~v);
11192 }
11193
11194 /// isFPImmLegal - Returns true if the target can instruction select the
11195 /// specified FP immediate natively. If false, the legalizer will
11196 /// materialize the FP immediate as a load from a constant pool.
11197 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11198   if (!Subtarget->hasVFP3())
11199     return false;
11200   if (VT == MVT::f32)
11201     return ARM_AM::getFP32Imm(Imm) != -1;
11202   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11203     return ARM_AM::getFP64Imm(Imm) != -1;
11204   return false;
11205 }
11206
11207 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11208 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11209 /// specified in the intrinsic calls.
11210 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11211                                            const CallInst &I,
11212                                            unsigned Intrinsic) const {
11213   switch (Intrinsic) {
11214   case Intrinsic::arm_neon_vld1:
11215   case Intrinsic::arm_neon_vld2:
11216   case Intrinsic::arm_neon_vld3:
11217   case Intrinsic::arm_neon_vld4:
11218   case Intrinsic::arm_neon_vld2lane:
11219   case Intrinsic::arm_neon_vld3lane:
11220   case Intrinsic::arm_neon_vld4lane: {
11221     Info.opc = ISD::INTRINSIC_W_CHAIN;
11222     // Conservatively set memVT to the entire set of vectors loaded.
11223     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11224     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11225     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11226     Info.ptrVal = I.getArgOperand(0);
11227     Info.offset = 0;
11228     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11229     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11230     Info.vol = false; // volatile loads with NEON intrinsics not supported
11231     Info.readMem = true;
11232     Info.writeMem = false;
11233     return true;
11234   }
11235   case Intrinsic::arm_neon_vst1:
11236   case Intrinsic::arm_neon_vst2:
11237   case Intrinsic::arm_neon_vst3:
11238   case Intrinsic::arm_neon_vst4:
11239   case Intrinsic::arm_neon_vst2lane:
11240   case Intrinsic::arm_neon_vst3lane:
11241   case Intrinsic::arm_neon_vst4lane: {
11242     Info.opc = ISD::INTRINSIC_VOID;
11243     // Conservatively set memVT to the entire set of vectors stored.
11244     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11245     unsigned NumElts = 0;
11246     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11247       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11248       if (!ArgTy->isVectorTy())
11249         break;
11250       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11251     }
11252     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11253     Info.ptrVal = I.getArgOperand(0);
11254     Info.offset = 0;
11255     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11256     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11257     Info.vol = false; // volatile stores with NEON intrinsics not supported
11258     Info.readMem = false;
11259     Info.writeMem = true;
11260     return true;
11261   }
11262   case Intrinsic::arm_ldaex:
11263   case Intrinsic::arm_ldrex: {
11264     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11265     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11266     Info.opc = ISD::INTRINSIC_W_CHAIN;
11267     Info.memVT = MVT::getVT(PtrTy->getElementType());
11268     Info.ptrVal = I.getArgOperand(0);
11269     Info.offset = 0;
11270     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11271     Info.vol = true;
11272     Info.readMem = true;
11273     Info.writeMem = false;
11274     return true;
11275   }
11276   case Intrinsic::arm_stlex:
11277   case Intrinsic::arm_strex: {
11278     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11279     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11280     Info.opc = ISD::INTRINSIC_W_CHAIN;
11281     Info.memVT = MVT::getVT(PtrTy->getElementType());
11282     Info.ptrVal = I.getArgOperand(1);
11283     Info.offset = 0;
11284     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11285     Info.vol = true;
11286     Info.readMem = false;
11287     Info.writeMem = true;
11288     return true;
11289   }
11290   case Intrinsic::arm_stlexd:
11291   case Intrinsic::arm_strexd: {
11292     Info.opc = ISD::INTRINSIC_W_CHAIN;
11293     Info.memVT = MVT::i64;
11294     Info.ptrVal = I.getArgOperand(2);
11295     Info.offset = 0;
11296     Info.align = 8;
11297     Info.vol = true;
11298     Info.readMem = false;
11299     Info.writeMem = true;
11300     return true;
11301   }
11302   case Intrinsic::arm_ldaexd:
11303   case Intrinsic::arm_ldrexd: {
11304     Info.opc = ISD::INTRINSIC_W_CHAIN;
11305     Info.memVT = MVT::i64;
11306     Info.ptrVal = I.getArgOperand(0);
11307     Info.offset = 0;
11308     Info.align = 8;
11309     Info.vol = true;
11310     Info.readMem = true;
11311     Info.writeMem = false;
11312     return true;
11313   }
11314   default:
11315     break;
11316   }
11317
11318   return false;
11319 }
11320
11321 /// \brief Returns true if it is beneficial to convert a load of a constant
11322 /// to just the constant itself.
11323 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11324                                                           Type *Ty) const {
11325   assert(Ty->isIntegerTy());
11326
11327   unsigned Bits = Ty->getPrimitiveSizeInBits();
11328   if (Bits == 0 || Bits > 32)
11329     return false;
11330   return true;
11331 }
11332
11333 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11334
11335 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11336                                         ARM_MB::MemBOpt Domain) const {
11337   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11338
11339   // First, if the target has no DMB, see what fallback we can use.
11340   if (!Subtarget->hasDataBarrier()) {
11341     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11342     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11343     // here.
11344     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11345       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11346       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11347                         Builder.getInt32(0), Builder.getInt32(7),
11348                         Builder.getInt32(10), Builder.getInt32(5)};
11349       return Builder.CreateCall(MCR, args);
11350     } else {
11351       // Instead of using barriers, atomic accesses on these subtargets use
11352       // libcalls.
11353       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11354     }
11355   } else {
11356     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11357     // Only a full system barrier exists in the M-class architectures.
11358     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11359     Constant *CDomain = Builder.getInt32(Domain);
11360     return Builder.CreateCall(DMB, CDomain);
11361   }
11362 }
11363
11364 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11365 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11366                                          AtomicOrdering Ord, bool IsStore,
11367                                          bool IsLoad) const {
11368   if (!getInsertFencesForAtomic())
11369     return nullptr;
11370
11371   switch (Ord) {
11372   case NotAtomic:
11373   case Unordered:
11374     llvm_unreachable("Invalid fence: unordered/non-atomic");
11375   case Monotonic:
11376   case Acquire:
11377     return nullptr; // Nothing to do
11378   case SequentiallyConsistent:
11379     if (!IsStore)
11380       return nullptr; // Nothing to do
11381     /*FALLTHROUGH*/
11382   case Release:
11383   case AcquireRelease:
11384     if (Subtarget->isSwift())
11385       return makeDMB(Builder, ARM_MB::ISHST);
11386     // FIXME: add a comment with a link to documentation justifying this.
11387     else
11388       return makeDMB(Builder, ARM_MB::ISH);
11389   }
11390   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11391 }
11392
11393 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11394                                           AtomicOrdering Ord, bool IsStore,
11395                                           bool IsLoad) const {
11396   if (!getInsertFencesForAtomic())
11397     return nullptr;
11398
11399   switch (Ord) {
11400   case NotAtomic:
11401   case Unordered:
11402     llvm_unreachable("Invalid fence: unordered/not-atomic");
11403   case Monotonic:
11404   case Release:
11405     return nullptr; // Nothing to do
11406   case Acquire:
11407   case AcquireRelease:
11408   case SequentiallyConsistent:
11409     return makeDMB(Builder, ARM_MB::ISH);
11410   }
11411   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11412 }
11413
11414 // Loads and stores less than 64-bits are already atomic; ones above that
11415 // are doomed anyway, so defer to the default libcall and blame the OS when
11416 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11417 // anything for those.
11418 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11419   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11420   return (Size == 64) && !Subtarget->isMClass();
11421 }
11422
11423 // Loads and stores less than 64-bits are already atomic; ones above that
11424 // are doomed anyway, so defer to the default libcall and blame the OS when
11425 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11426 // anything for those.
11427 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11428 // guarantee, see DDI0406C ARM architecture reference manual,
11429 // sections A8.8.72-74 LDRD)
11430 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11431   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11432   return (Size == 64) && !Subtarget->isMClass();
11433 }
11434
11435 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11436 // and up to 64 bits on the non-M profiles
11437 TargetLoweringBase::AtomicRMWExpansionKind
11438 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11439   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11440   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11441              ? AtomicRMWExpansionKind::LLSC
11442              : AtomicRMWExpansionKind::None;
11443 }
11444
11445 // This has so far only been implemented for MachO.
11446 bool ARMTargetLowering::useLoadStackGuardNode() const {
11447   return Subtarget->isTargetMachO();
11448 }
11449
11450 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11451                                                   unsigned &Cost) const {
11452   // If we do not have NEON, vector types are not natively supported.
11453   if (!Subtarget->hasNEON())
11454     return false;
11455
11456   // Floating point values and vector values map to the same register file.
11457   // Therefore, although we could do a store extract of a vector type, this is
11458   // better to leave at float as we have more freedom in the addressing mode for
11459   // those.
11460   if (VectorTy->isFPOrFPVectorTy())
11461     return false;
11462
11463   // If the index is unknown at compile time, this is very expensive to lower
11464   // and it is not possible to combine the store with the extract.
11465   if (!isa<ConstantInt>(Idx))
11466     return false;
11467
11468   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11469   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11470   // We can do a store + vector extract on any vector that fits perfectly in a D
11471   // or Q register.
11472   if (BitWidth == 64 || BitWidth == 128) {
11473     Cost = 0;
11474     return true;
11475   }
11476   return false;
11477 }
11478
11479 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11480                                          AtomicOrdering Ord) const {
11481   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11482   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11483   bool IsAcquire = isAtLeastAcquire(Ord);
11484
11485   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11486   // intrinsic must return {i32, i32} and we have to recombine them into a
11487   // single i64 here.
11488   if (ValTy->getPrimitiveSizeInBits() == 64) {
11489     Intrinsic::ID Int =
11490         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11491     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11492
11493     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11494     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11495
11496     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11497     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11498     if (!Subtarget->isLittle())
11499       std::swap (Lo, Hi);
11500     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11501     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11502     return Builder.CreateOr(
11503         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11504   }
11505
11506   Type *Tys[] = { Addr->getType() };
11507   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11508   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11509
11510   return Builder.CreateTruncOrBitCast(
11511       Builder.CreateCall(Ldrex, Addr),
11512       cast<PointerType>(Addr->getType())->getElementType());
11513 }
11514
11515 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11516                                                Value *Addr,
11517                                                AtomicOrdering Ord) const {
11518   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11519   bool IsRelease = isAtLeastRelease(Ord);
11520
11521   // Since the intrinsics must have legal type, the i64 intrinsics take two
11522   // parameters: "i32, i32". We must marshal Val into the appropriate form
11523   // before the call.
11524   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11525     Intrinsic::ID Int =
11526         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11527     Function *Strex = Intrinsic::getDeclaration(M, Int);
11528     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11529
11530     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11531     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11532     if (!Subtarget->isLittle())
11533       std::swap (Lo, Hi);
11534     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11535     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11536   }
11537
11538   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11539   Type *Tys[] = { Addr->getType() };
11540   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11541
11542   return Builder.CreateCall(
11543       Strex, {Builder.CreateZExtOrBitCast(
11544                   Val, Strex->getFunctionType()->getParamType(0)),
11545               Addr});
11546 }
11547
11548 /// \brief Lower an interleaved load into a vldN intrinsic.
11549 ///
11550 /// E.g. Lower an interleaved load (Factor = 2):
11551 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11552 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11553 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11554 ///
11555 ///      Into:
11556 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11557 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11558 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11559 bool ARMTargetLowering::lowerInterleavedLoad(
11560     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11561     ArrayRef<unsigned> Indices, unsigned Factor) const {
11562   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11563          "Invalid interleave factor");
11564   assert(!Shuffles.empty() && "Empty shufflevector input");
11565   assert(Shuffles.size() == Indices.size() &&
11566          "Unmatched number of shufflevectors and indices");
11567
11568   VectorType *VecTy = Shuffles[0]->getType();
11569   Type *EltTy = VecTy->getVectorElementType();
11570
11571   const DataLayout &DL = LI->getModule()->getDataLayout();
11572   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11573   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11574
11575   // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11576   // support i64/f64 element).
11577   if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11578     return false;
11579
11580   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11581   // load integer vectors first and then convert to pointer vectors.
11582   if (EltTy->isPointerTy())
11583     VecTy =
11584         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11585
11586   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11587                                             Intrinsic::arm_neon_vld3,
11588                                             Intrinsic::arm_neon_vld4};
11589
11590   Function *VldnFunc =
11591       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11592
11593   IRBuilder<> Builder(LI);
11594   SmallVector<Value *, 2> Ops;
11595
11596   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11597   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11598   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11599
11600   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11601
11602   // Replace uses of each shufflevector with the corresponding vector loaded
11603   // by ldN.
11604   for (unsigned i = 0; i < Shuffles.size(); i++) {
11605     ShuffleVectorInst *SV = Shuffles[i];
11606     unsigned Index = Indices[i];
11607
11608     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11609
11610     // Convert the integer vector to pointer vector if the element is pointer.
11611     if (EltTy->isPointerTy())
11612       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11613
11614     SV->replaceAllUsesWith(SubVec);
11615   }
11616
11617   return true;
11618 }
11619
11620 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11621 ///
11622 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11623 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11624                                    unsigned NumElts) {
11625   SmallVector<Constant *, 16> Mask;
11626   for (unsigned i = 0; i < NumElts; i++)
11627     Mask.push_back(Builder.getInt32(Start + i));
11628
11629   return ConstantVector::get(Mask);
11630 }
11631
11632 /// \brief Lower an interleaved store into a vstN intrinsic.
11633 ///
11634 /// E.g. Lower an interleaved store (Factor = 3):
11635 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11636 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11637 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11638 ///
11639 ///      Into:
11640 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11641 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11642 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11643 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11644 ///
11645 /// Note that the new shufflevectors will be removed and we'll only generate one
11646 /// vst3 instruction in CodeGen.
11647 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11648                                               ShuffleVectorInst *SVI,
11649                                               unsigned Factor) const {
11650   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11651          "Invalid interleave factor");
11652
11653   VectorType *VecTy = SVI->getType();
11654   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11655          "Invalid interleaved store");
11656
11657   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11658   Type *EltTy = VecTy->getVectorElementType();
11659   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11660
11661   const DataLayout &DL = SI->getModule()->getDataLayout();
11662   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11663   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11664
11665   // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11666   // doesn't support i64/f64 element).
11667   if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11668     return false;
11669
11670   Value *Op0 = SVI->getOperand(0);
11671   Value *Op1 = SVI->getOperand(1);
11672   IRBuilder<> Builder(SI);
11673
11674   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11675   // vectors to integer vectors.
11676   if (EltTy->isPointerTy()) {
11677     Type *IntTy = DL.getIntPtrType(EltTy);
11678
11679     // Convert to the corresponding integer vector.
11680     Type *IntVecTy =
11681         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11682     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11683     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11684
11685     SubVecTy = VectorType::get(IntTy, NumSubElts);
11686   }
11687
11688   static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11689                                        Intrinsic::arm_neon_vst3,
11690                                        Intrinsic::arm_neon_vst4};
11691   Function *VstNFunc = Intrinsic::getDeclaration(
11692       SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11693
11694   SmallVector<Value *, 6> Ops;
11695
11696   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11697   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11698
11699   // Split the shufflevector operands into sub vectors for the new vstN call.
11700   for (unsigned i = 0; i < Factor; i++)
11701     Ops.push_back(Builder.CreateShuffleVector(
11702         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11703
11704   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11705   Builder.CreateCall(VstNFunc, Ops);
11706   return true;
11707 }
11708
11709 enum HABaseType {
11710   HA_UNKNOWN = 0,
11711   HA_FLOAT,
11712   HA_DOUBLE,
11713   HA_VECT64,
11714   HA_VECT128
11715 };
11716
11717 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11718                                    uint64_t &Members) {
11719   if (auto *ST = dyn_cast<StructType>(Ty)) {
11720     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11721       uint64_t SubMembers = 0;
11722       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11723         return false;
11724       Members += SubMembers;
11725     }
11726   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11727     uint64_t SubMembers = 0;
11728     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11729       return false;
11730     Members += SubMembers * AT->getNumElements();
11731   } else if (Ty->isFloatTy()) {
11732     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11733       return false;
11734     Members = 1;
11735     Base = HA_FLOAT;
11736   } else if (Ty->isDoubleTy()) {
11737     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11738       return false;
11739     Members = 1;
11740     Base = HA_DOUBLE;
11741   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11742     Members = 1;
11743     switch (Base) {
11744     case HA_FLOAT:
11745     case HA_DOUBLE:
11746       return false;
11747     case HA_VECT64:
11748       return VT->getBitWidth() == 64;
11749     case HA_VECT128:
11750       return VT->getBitWidth() == 128;
11751     case HA_UNKNOWN:
11752       switch (VT->getBitWidth()) {
11753       case 64:
11754         Base = HA_VECT64;
11755         return true;
11756       case 128:
11757         Base = HA_VECT128;
11758         return true;
11759       default:
11760         return false;
11761       }
11762     }
11763   }
11764
11765   return (Members > 0 && Members <= 4);
11766 }
11767
11768 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11769 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11770 /// passing according to AAPCS rules.
11771 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11772     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11773   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11774       CallingConv::ARM_AAPCS_VFP)
11775     return false;
11776
11777   HABaseType Base = HA_UNKNOWN;
11778   uint64_t Members = 0;
11779   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11780   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11781
11782   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11783   return IsHA || IsIntArray;
11784 }