ARM: support windows division routines
[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::SELECT_CC);
587     setTargetDAGCombine(ISD::BUILD_VECTOR);
588     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
589     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
590     setTargetDAGCombine(ISD::STORE);
591     setTargetDAGCombine(ISD::FP_TO_SINT);
592     setTargetDAGCombine(ISD::FP_TO_UINT);
593     setTargetDAGCombine(ISD::FDIV);
594     setTargetDAGCombine(ISD::LOAD);
595
596     // It is legal to extload from v4i8 to v4i16 or v4i32.
597     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
598                    MVT::v2i32}) {
599       for (MVT VT : MVT::integer_vector_valuetypes()) {
600         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
601         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
602         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
603       }
604     }
605   }
606
607   // ARM and Thumb2 support UMLAL/SMLAL.
608   if (!Subtarget->isThumb1Only())
609     setTargetDAGCombine(ISD::ADDC);
610
611   if (Subtarget->isFPOnlySP()) {
612     // When targetting a floating-point unit with only single-precision
613     // operations, f64 is legal for the few double-precision instructions which
614     // are present However, no double-precision operations other than moves,
615     // loads and stores are provided by the hardware.
616     setOperationAction(ISD::FADD,       MVT::f64, Expand);
617     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
618     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
619     setOperationAction(ISD::FMA,        MVT::f64, Expand);
620     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
621     setOperationAction(ISD::FREM,       MVT::f64, Expand);
622     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
623     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
624     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
625     setOperationAction(ISD::FABS,       MVT::f64, Expand);
626     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
627     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
628     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
629     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
630     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
631     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
632     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
633     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
634     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
635     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
636     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
637     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
638     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
639     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
640     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
641     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
642     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
643     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
644     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
645     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
646     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
647     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
648     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
649   }
650
651   computeRegisterProperties(Subtarget->getRegisterInfo());
652
653   // ARM does not have floating-point extending loads.
654   for (MVT VT : MVT::fp_valuetypes()) {
655     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
656     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
657   }
658
659   // ... or truncating stores
660   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
661   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
662   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
663
664   // ARM does not have i1 sign extending load.
665   for (MVT VT : MVT::integer_valuetypes())
666     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
667
668   // ARM supports all 4 flavors of integer indexed load / store.
669   if (!Subtarget->isThumb1Only()) {
670     for (unsigned im = (unsigned)ISD::PRE_INC;
671          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
672       setIndexedLoadAction(im,  MVT::i1,  Legal);
673       setIndexedLoadAction(im,  MVT::i8,  Legal);
674       setIndexedLoadAction(im,  MVT::i16, Legal);
675       setIndexedLoadAction(im,  MVT::i32, Legal);
676       setIndexedStoreAction(im, MVT::i1,  Legal);
677       setIndexedStoreAction(im, MVT::i8,  Legal);
678       setIndexedStoreAction(im, MVT::i16, Legal);
679       setIndexedStoreAction(im, MVT::i32, Legal);
680     }
681   }
682
683   setOperationAction(ISD::SADDO, MVT::i32, Custom);
684   setOperationAction(ISD::UADDO, MVT::i32, Custom);
685   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
686   setOperationAction(ISD::USUBO, MVT::i32, Custom);
687
688   // i64 operation support.
689   setOperationAction(ISD::MUL,     MVT::i64, Expand);
690   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
691   if (Subtarget->isThumb1Only()) {
692     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
693     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
694   }
695   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
696       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
697     setOperationAction(ISD::MULHS, MVT::i32, Expand);
698
699   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
700   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
701   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
702   setOperationAction(ISD::SRL,       MVT::i64, Custom);
703   setOperationAction(ISD::SRA,       MVT::i64, Custom);
704
705   if (!Subtarget->isThumb1Only()) {
706     // FIXME: We should do this for Thumb1 as well.
707     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
708     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
709     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
710     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
711   }
712
713   // ARM does not have ROTL.
714   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
715   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
716   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
717   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
718     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
719
720   // These just redirect to CTTZ and CTLZ on ARM.
721   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
722   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
723
724   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
725
726   // Only ARMv6 has BSWAP.
727   if (!Subtarget->hasV6Ops())
728     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
729
730   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
731       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
732     // These are expanded into libcalls if the cpu doesn't have HW divider.
733     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
734     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
735   }
736
737   // FIXME: Also set divmod for SREM on EABI/androideabi
738   setOperationAction(ISD::SREM,  MVT::i32, Expand);
739   setOperationAction(ISD::UREM,  MVT::i32, Expand);
740   // Register based DivRem for AEABI (RTABI 4.2)
741   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
742     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
743     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
744     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
745     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
746     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
747     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
748     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
749     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
750
751     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
752     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
753     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
754     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
755     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
756     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
757     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
758     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
759
760     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
761     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
762   } else {
763     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
764     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
765   }
766
767   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
768   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
769   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
770   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
771   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
772
773   setOperationAction(ISD::TRAP, MVT::Other, Legal);
774
775   // Use the default implementation.
776   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
777   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
778   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
779   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
780   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
781   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
782
783   if (!Subtarget->isTargetMachO()) {
784     // Non-MachO platforms may return values in these registers via the
785     // personality function.
786     setExceptionPointerRegister(ARM::R0);
787     setExceptionSelectorRegister(ARM::R1);
788   }
789
790   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
791     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
792   else
793     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
794
795   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
796   // the default expansion. If we are targeting a single threaded system,
797   // then set them all for expand so we can lower them later into their
798   // non-atomic form.
799   if (TM.Options.ThreadModel == ThreadModel::Single)
800     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
801   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
802     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
803     // to ldrex/strex loops already.
804     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
805
806     // On v8, we have particularly efficient implementations of atomic fences
807     // if they can be combined with nearby atomic loads and stores.
808     if (!Subtarget->hasV8Ops()) {
809       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
810       setInsertFencesForAtomic(true);
811     }
812   } else {
813     // If there's anything we can use as a barrier, go through custom lowering
814     // for ATOMIC_FENCE.
815     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
816                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
817
818     // Set them all for expansion, which will force libcalls.
819     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
820     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
821     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
822     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
823     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
824     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
825     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
826     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
827     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
828     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
829     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
830     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
831     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
832     // Unordered/Monotonic case.
833     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
834     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
835   }
836
837   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
838
839   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
840   if (!Subtarget->hasV6Ops()) {
841     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
842     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
843   }
844   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
845
846   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
847       !Subtarget->isThumb1Only()) {
848     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
849     // iff target supports vfp2.
850     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
851     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
852   }
853
854   // We want to custom lower some of our intrinsics.
855   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
856   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
857   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
858   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
859   if (Subtarget->isTargetDarwin())
860     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
861
862   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
863   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
864   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
865   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
866   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
867   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
868   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
869   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
870   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
871
872   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
873   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
874   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
875   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
876   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
877
878   // We don't support sin/cos/fmod/copysign/pow
879   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
880   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
881   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
882   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
883   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
884   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
885   setOperationAction(ISD::FREM,      MVT::f64, Expand);
886   setOperationAction(ISD::FREM,      MVT::f32, Expand);
887   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
888       !Subtarget->isThumb1Only()) {
889     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
890     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
891   }
892   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
893   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
894
895   if (!Subtarget->hasVFP4()) {
896     setOperationAction(ISD::FMA, MVT::f64, Expand);
897     setOperationAction(ISD::FMA, MVT::f32, Expand);
898   }
899
900   // Various VFP goodness
901   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
902     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
903     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
904       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
905       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
906     }
907
908     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
909     if (!Subtarget->hasFP16()) {
910       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
911       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
912     }
913   }
914
915   // Combine sin / cos into one node or libcall if possible.
916   if (Subtarget->hasSinCos()) {
917     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
918     setLibcallName(RTLIB::SINCOS_F64, "sincos");
919     if (Subtarget->getTargetTriple().isiOS()) {
920       // For iOS, we don't want to the normal expansion of a libcall to
921       // sincos. We want to issue a libcall to __sincos_stret.
922       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
923       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
924     }
925   }
926
927   // FP-ARMv8 implements a lot of rounding-like FP operations.
928   if (Subtarget->hasFPARMv8()) {
929     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
930     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
931     setOperationAction(ISD::FROUND, MVT::f32, Legal);
932     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
933     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
934     setOperationAction(ISD::FRINT, MVT::f32, Legal);
935     if (!Subtarget->isFPOnlySP()) {
936       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
937       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
938       setOperationAction(ISD::FROUND, MVT::f64, Legal);
939       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
940       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
941       setOperationAction(ISD::FRINT, MVT::f64, Legal);
942     }
943   }
944   // We have target-specific dag combine patterns for the following nodes:
945   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
946   setTargetDAGCombine(ISD::ADD);
947   setTargetDAGCombine(ISD::SUB);
948   setTargetDAGCombine(ISD::MUL);
949   setTargetDAGCombine(ISD::AND);
950   setTargetDAGCombine(ISD::OR);
951   setTargetDAGCombine(ISD::XOR);
952
953   if (Subtarget->hasV6Ops())
954     setTargetDAGCombine(ISD::SRL);
955
956   setStackPointerRegisterToSaveRestore(ARM::SP);
957
958   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
959       !Subtarget->hasVFP2())
960     setSchedulingPreference(Sched::RegPressure);
961   else
962     setSchedulingPreference(Sched::Hybrid);
963
964   //// temporary - rewrite interface to use type
965   MaxStoresPerMemset = 8;
966   MaxStoresPerMemsetOptSize = 4;
967   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
968   MaxStoresPerMemcpyOptSize = 2;
969   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
970   MaxStoresPerMemmoveOptSize = 2;
971
972   // On ARM arguments smaller than 4 bytes are extended, so all arguments
973   // are at least 4 bytes aligned.
974   setMinStackArgumentAlignment(4);
975
976   // Prefer likely predicted branches to selects on out-of-order cores.
977   PredictableSelectIsExpensive = Subtarget->isLikeA9();
978
979   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
980 }
981
982 bool ARMTargetLowering::useSoftFloat() const {
983   return Subtarget->useSoftFloat();
984 }
985
986 // FIXME: It might make sense to define the representative register class as the
987 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
988 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
989 // SPR's representative would be DPR_VFP2. This should work well if register
990 // pressure tracking were modified such that a register use would increment the
991 // pressure of the register class's representative and all of it's super
992 // classes' representatives transitively. We have not implemented this because
993 // of the difficulty prior to coalescing of modeling operand register classes
994 // due to the common occurrence of cross class copies and subregister insertions
995 // and extractions.
996 std::pair<const TargetRegisterClass *, uint8_t>
997 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
998                                            MVT VT) const {
999   const TargetRegisterClass *RRC = nullptr;
1000   uint8_t Cost = 1;
1001   switch (VT.SimpleTy) {
1002   default:
1003     return TargetLowering::findRepresentativeClass(TRI, VT);
1004   // Use DPR as representative register class for all floating point
1005   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1006   // the cost is 1 for both f32 and f64.
1007   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1008   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1009     RRC = &ARM::DPRRegClass;
1010     // When NEON is used for SP, only half of the register file is available
1011     // because operations that define both SP and DP results will be constrained
1012     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1013     // coalescing by double-counting the SP regs. See the FIXME above.
1014     if (Subtarget->useNEONForSinglePrecisionFP())
1015       Cost = 2;
1016     break;
1017   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1018   case MVT::v4f32: case MVT::v2f64:
1019     RRC = &ARM::DPRRegClass;
1020     Cost = 2;
1021     break;
1022   case MVT::v4i64:
1023     RRC = &ARM::DPRRegClass;
1024     Cost = 4;
1025     break;
1026   case MVT::v8i64:
1027     RRC = &ARM::DPRRegClass;
1028     Cost = 8;
1029     break;
1030   }
1031   return std::make_pair(RRC, Cost);
1032 }
1033
1034 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1035   switch ((ARMISD::NodeType)Opcode) {
1036   case ARMISD::FIRST_NUMBER:  break;
1037   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1038   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1039   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1040   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1041   case ARMISD::CALL:          return "ARMISD::CALL";
1042   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1043   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1044   case ARMISD::tCALL:         return "ARMISD::tCALL";
1045   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1046   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1047   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1048   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1049   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1050   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1051   case ARMISD::CMP:           return "ARMISD::CMP";
1052   case ARMISD::CMN:           return "ARMISD::CMN";
1053   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1054   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1055   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1056   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1057   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1058
1059   case ARMISD::CMOV:          return "ARMISD::CMOV";
1060
1061   case ARMISD::RBIT:          return "ARMISD::RBIT";
1062
1063   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1064   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1065   case ARMISD::RRX:           return "ARMISD::RRX";
1066
1067   case ARMISD::ADDC:          return "ARMISD::ADDC";
1068   case ARMISD::ADDE:          return "ARMISD::ADDE";
1069   case ARMISD::SUBC:          return "ARMISD::SUBC";
1070   case ARMISD::SUBE:          return "ARMISD::SUBE";
1071
1072   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1073   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1074
1075   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1076   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1077   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1078
1079   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1080
1081   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1082
1083   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1084
1085   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1086
1087   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1088
1089   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1090
1091   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1092   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1093   case ARMISD::VCGE:          return "ARMISD::VCGE";
1094   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1095   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1096   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1097   case ARMISD::VCGT:          return "ARMISD::VCGT";
1098   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1099   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1100   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1101   case ARMISD::VTST:          return "ARMISD::VTST";
1102
1103   case ARMISD::VSHL:          return "ARMISD::VSHL";
1104   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1105   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1106   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1107   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1108   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1109   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1110   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1111   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1112   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1113   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1114   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1115   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1116   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1117   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1118   case ARMISD::VSLI:          return "ARMISD::VSLI";
1119   case ARMISD::VSRI:          return "ARMISD::VSRI";
1120   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1121   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1122   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1123   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1124   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1125   case ARMISD::VDUP:          return "ARMISD::VDUP";
1126   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1127   case ARMISD::VEXT:          return "ARMISD::VEXT";
1128   case ARMISD::VREV64:        return "ARMISD::VREV64";
1129   case ARMISD::VREV32:        return "ARMISD::VREV32";
1130   case ARMISD::VREV16:        return "ARMISD::VREV16";
1131   case ARMISD::VZIP:          return "ARMISD::VZIP";
1132   case ARMISD::VUZP:          return "ARMISD::VUZP";
1133   case ARMISD::VTRN:          return "ARMISD::VTRN";
1134   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1135   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1136   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1137   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1138   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1139   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1140   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1141   case ARMISD::FMAX:          return "ARMISD::FMAX";
1142   case ARMISD::FMIN:          return "ARMISD::FMIN";
1143   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1144   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1145   case ARMISD::BFI:           return "ARMISD::BFI";
1146   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1147   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1148   case ARMISD::VBSL:          return "ARMISD::VBSL";
1149   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1150   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1151   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1152   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1153   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1154   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1155   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1156   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1157   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1158   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1159   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1160   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1161   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1162   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1163   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1164   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1165   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1166   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1167   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1168   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1169   }
1170   return nullptr;
1171 }
1172
1173 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1174                                           EVT VT) const {
1175   if (!VT.isVector())
1176     return getPointerTy(DL);
1177   return VT.changeVectorElementTypeToInteger();
1178 }
1179
1180 /// getRegClassFor - Return the register class that should be used for the
1181 /// specified value type.
1182 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1183   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1184   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1185   // load / store 4 to 8 consecutive D registers.
1186   if (Subtarget->hasNEON()) {
1187     if (VT == MVT::v4i64)
1188       return &ARM::QQPRRegClass;
1189     if (VT == MVT::v8i64)
1190       return &ARM::QQQQPRRegClass;
1191   }
1192   return TargetLowering::getRegClassFor(VT);
1193 }
1194
1195 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1196 // source/dest is aligned and the copy size is large enough. We therefore want
1197 // to align such objects passed to memory intrinsics.
1198 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1199                                                unsigned &PrefAlign) const {
1200   if (!isa<MemIntrinsic>(CI))
1201     return false;
1202   MinSize = 8;
1203   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1204   // cycle faster than 4-byte aligned LDM.
1205   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1206   return true;
1207 }
1208
1209 // Create a fast isel object.
1210 FastISel *
1211 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1212                                   const TargetLibraryInfo *libInfo) const {
1213   return ARM::createFastISel(funcInfo, libInfo);
1214 }
1215
1216 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1217   unsigned NumVals = N->getNumValues();
1218   if (!NumVals)
1219     return Sched::RegPressure;
1220
1221   for (unsigned i = 0; i != NumVals; ++i) {
1222     EVT VT = N->getValueType(i);
1223     if (VT == MVT::Glue || VT == MVT::Other)
1224       continue;
1225     if (VT.isFloatingPoint() || VT.isVector())
1226       return Sched::ILP;
1227   }
1228
1229   if (!N->isMachineOpcode())
1230     return Sched::RegPressure;
1231
1232   // Load are scheduled for latency even if there instruction itinerary
1233   // is not available.
1234   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1235   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1236
1237   if (MCID.getNumDefs() == 0)
1238     return Sched::RegPressure;
1239   if (!Itins->isEmpty() &&
1240       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1241     return Sched::ILP;
1242
1243   return Sched::RegPressure;
1244 }
1245
1246 //===----------------------------------------------------------------------===//
1247 // Lowering Code
1248 //===----------------------------------------------------------------------===//
1249
1250 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1251 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1252   switch (CC) {
1253   default: llvm_unreachable("Unknown condition code!");
1254   case ISD::SETNE:  return ARMCC::NE;
1255   case ISD::SETEQ:  return ARMCC::EQ;
1256   case ISD::SETGT:  return ARMCC::GT;
1257   case ISD::SETGE:  return ARMCC::GE;
1258   case ISD::SETLT:  return ARMCC::LT;
1259   case ISD::SETLE:  return ARMCC::LE;
1260   case ISD::SETUGT: return ARMCC::HI;
1261   case ISD::SETUGE: return ARMCC::HS;
1262   case ISD::SETULT: return ARMCC::LO;
1263   case ISD::SETULE: return ARMCC::LS;
1264   }
1265 }
1266
1267 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1268 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1269                         ARMCC::CondCodes &CondCode2) {
1270   CondCode2 = ARMCC::AL;
1271   switch (CC) {
1272   default: llvm_unreachable("Unknown FP condition!");
1273   case ISD::SETEQ:
1274   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1275   case ISD::SETGT:
1276   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1277   case ISD::SETGE:
1278   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1279   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1280   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1281   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1282   case ISD::SETO:   CondCode = ARMCC::VC; break;
1283   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1284   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1285   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1286   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1287   case ISD::SETLT:
1288   case ISD::SETULT: CondCode = ARMCC::LT; break;
1289   case ISD::SETLE:
1290   case ISD::SETULE: CondCode = ARMCC::LE; break;
1291   case ISD::SETNE:
1292   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1293   }
1294 }
1295
1296 //===----------------------------------------------------------------------===//
1297 //                      Calling Convention Implementation
1298 //===----------------------------------------------------------------------===//
1299
1300 #include "ARMGenCallingConv.inc"
1301
1302 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1303 /// account presence of floating point hardware and calling convention
1304 /// limitations, such as support for variadic functions.
1305 CallingConv::ID
1306 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1307                                            bool isVarArg) const {
1308   switch (CC) {
1309   default:
1310     llvm_unreachable("Unsupported calling convention");
1311   case CallingConv::ARM_AAPCS:
1312   case CallingConv::ARM_APCS:
1313   case CallingConv::GHC:
1314     return CC;
1315   case CallingConv::ARM_AAPCS_VFP:
1316     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1317   case CallingConv::C:
1318     if (!Subtarget->isAAPCS_ABI())
1319       return CallingConv::ARM_APCS;
1320     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1321              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1322              !isVarArg)
1323       return CallingConv::ARM_AAPCS_VFP;
1324     else
1325       return CallingConv::ARM_AAPCS;
1326   case CallingConv::Fast:
1327     if (!Subtarget->isAAPCS_ABI()) {
1328       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1329         return CallingConv::Fast;
1330       return CallingConv::ARM_APCS;
1331     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1332       return CallingConv::ARM_AAPCS_VFP;
1333     else
1334       return CallingConv::ARM_AAPCS;
1335   }
1336 }
1337
1338 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1339 /// CallingConvention.
1340 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1341                                                  bool Return,
1342                                                  bool isVarArg) const {
1343   switch (getEffectiveCallingConv(CC, isVarArg)) {
1344   default:
1345     llvm_unreachable("Unsupported calling convention");
1346   case CallingConv::ARM_APCS:
1347     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1348   case CallingConv::ARM_AAPCS:
1349     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1350   case CallingConv::ARM_AAPCS_VFP:
1351     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1352   case CallingConv::Fast:
1353     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1354   case CallingConv::GHC:
1355     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1356   }
1357 }
1358
1359 /// LowerCallResult - Lower the result values of a call into the
1360 /// appropriate copies out of appropriate physical registers.
1361 SDValue
1362 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1363                                    CallingConv::ID CallConv, bool isVarArg,
1364                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1365                                    SDLoc dl, SelectionDAG &DAG,
1366                                    SmallVectorImpl<SDValue> &InVals,
1367                                    bool isThisReturn, SDValue ThisVal) const {
1368
1369   // Assign locations to each value returned by this call.
1370   SmallVector<CCValAssign, 16> RVLocs;
1371   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1372                     *DAG.getContext(), Call);
1373   CCInfo.AnalyzeCallResult(Ins,
1374                            CCAssignFnForNode(CallConv, /* Return*/ true,
1375                                              isVarArg));
1376
1377   // Copy all of the result registers out of their specified physreg.
1378   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1379     CCValAssign VA = RVLocs[i];
1380
1381     // Pass 'this' value directly from the argument to return value, to avoid
1382     // reg unit interference
1383     if (i == 0 && isThisReturn) {
1384       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1385              "unexpected return calling convention register assignment");
1386       InVals.push_back(ThisVal);
1387       continue;
1388     }
1389
1390     SDValue Val;
1391     if (VA.needsCustom()) {
1392       // Handle f64 or half of a v2f64.
1393       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1394                                       InFlag);
1395       Chain = Lo.getValue(1);
1396       InFlag = Lo.getValue(2);
1397       VA = RVLocs[++i]; // skip ahead to next loc
1398       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1399                                       InFlag);
1400       Chain = Hi.getValue(1);
1401       InFlag = Hi.getValue(2);
1402       if (!Subtarget->isLittle())
1403         std::swap (Lo, Hi);
1404       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1405
1406       if (VA.getLocVT() == MVT::v2f64) {
1407         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1408         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1409                           DAG.getConstant(0, dl, MVT::i32));
1410
1411         VA = RVLocs[++i]; // skip ahead to next loc
1412         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1413         Chain = Lo.getValue(1);
1414         InFlag = Lo.getValue(2);
1415         VA = RVLocs[++i]; // skip ahead to next loc
1416         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1417         Chain = Hi.getValue(1);
1418         InFlag = Hi.getValue(2);
1419         if (!Subtarget->isLittle())
1420           std::swap (Lo, Hi);
1421         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1422         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1423                           DAG.getConstant(1, dl, MVT::i32));
1424       }
1425     } else {
1426       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1427                                InFlag);
1428       Chain = Val.getValue(1);
1429       InFlag = Val.getValue(2);
1430     }
1431
1432     switch (VA.getLocInfo()) {
1433     default: llvm_unreachable("Unknown loc info!");
1434     case CCValAssign::Full: break;
1435     case CCValAssign::BCvt:
1436       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1437       break;
1438     }
1439
1440     InVals.push_back(Val);
1441   }
1442
1443   return Chain;
1444 }
1445
1446 /// LowerMemOpCallTo - Store the argument to the stack.
1447 SDValue
1448 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1449                                     SDValue StackPtr, SDValue Arg,
1450                                     SDLoc dl, SelectionDAG &DAG,
1451                                     const CCValAssign &VA,
1452                                     ISD::ArgFlagsTy Flags) const {
1453   unsigned LocMemOffset = VA.getLocMemOffset();
1454   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1455   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1456                        StackPtr, PtrOff);
1457   return DAG.getStore(Chain, dl, Arg, PtrOff,
1458                       MachinePointerInfo::getStack(LocMemOffset),
1459                       false, false, 0);
1460 }
1461
1462 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1463                                          SDValue Chain, SDValue &Arg,
1464                                          RegsToPassVector &RegsToPass,
1465                                          CCValAssign &VA, CCValAssign &NextVA,
1466                                          SDValue &StackPtr,
1467                                          SmallVectorImpl<SDValue> &MemOpChains,
1468                                          ISD::ArgFlagsTy Flags) const {
1469
1470   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1471                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1472   unsigned id = Subtarget->isLittle() ? 0 : 1;
1473   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1474
1475   if (NextVA.isRegLoc())
1476     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1477   else {
1478     assert(NextVA.isMemLoc());
1479     if (!StackPtr.getNode())
1480       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1481                                     getPointerTy(DAG.getDataLayout()));
1482
1483     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1484                                            dl, DAG, NextVA,
1485                                            Flags));
1486   }
1487 }
1488
1489 /// LowerCall - Lowering a call into a callseq_start <-
1490 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1491 /// nodes.
1492 SDValue
1493 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1494                              SmallVectorImpl<SDValue> &InVals) const {
1495   SelectionDAG &DAG                     = CLI.DAG;
1496   SDLoc &dl                             = CLI.DL;
1497   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1498   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1499   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1500   SDValue Chain                         = CLI.Chain;
1501   SDValue Callee                        = CLI.Callee;
1502   bool &isTailCall                      = CLI.IsTailCall;
1503   CallingConv::ID CallConv              = CLI.CallConv;
1504   bool doesNotRet                       = CLI.DoesNotReturn;
1505   bool isVarArg                         = CLI.IsVarArg;
1506
1507   MachineFunction &MF = DAG.getMachineFunction();
1508   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1509   bool isThisReturn   = false;
1510   bool isSibCall      = false;
1511   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1512
1513   // Disable tail calls if they're not supported.
1514   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1515     isTailCall = false;
1516
1517   if (isTailCall) {
1518     // Check if it's really possible to do a tail call.
1519     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1520                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1521                                                    Outs, OutVals, Ins, DAG);
1522     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1523       report_fatal_error("failed to perform tail call elimination on a call "
1524                          "site marked musttail");
1525     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1526     // detected sibcalls.
1527     if (isTailCall) {
1528       ++NumTailCalls;
1529       isSibCall = true;
1530     }
1531   }
1532
1533   // Analyze operands of the call, assigning locations to each operand.
1534   SmallVector<CCValAssign, 16> ArgLocs;
1535   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1536                     *DAG.getContext(), Call);
1537   CCInfo.AnalyzeCallOperands(Outs,
1538                              CCAssignFnForNode(CallConv, /* Return*/ false,
1539                                                isVarArg));
1540
1541   // Get a count of how many bytes are to be pushed on the stack.
1542   unsigned NumBytes = CCInfo.getNextStackOffset();
1543
1544   // For tail calls, memory operands are available in our caller's stack.
1545   if (isSibCall)
1546     NumBytes = 0;
1547
1548   // Adjust the stack pointer for the new arguments...
1549   // These operations are automatically eliminated by the prolog/epilog pass
1550   if (!isSibCall)
1551     Chain = DAG.getCALLSEQ_START(Chain,
1552                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1553
1554   SDValue StackPtr =
1555       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1556
1557   RegsToPassVector RegsToPass;
1558   SmallVector<SDValue, 8> MemOpChains;
1559
1560   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1561   // of tail call optimization, arguments are handled later.
1562   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1563        i != e;
1564        ++i, ++realArgIdx) {
1565     CCValAssign &VA = ArgLocs[i];
1566     SDValue Arg = OutVals[realArgIdx];
1567     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1568     bool isByVal = Flags.isByVal();
1569
1570     // Promote the value if needed.
1571     switch (VA.getLocInfo()) {
1572     default: llvm_unreachable("Unknown loc info!");
1573     case CCValAssign::Full: break;
1574     case CCValAssign::SExt:
1575       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1576       break;
1577     case CCValAssign::ZExt:
1578       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1579       break;
1580     case CCValAssign::AExt:
1581       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1582       break;
1583     case CCValAssign::BCvt:
1584       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1585       break;
1586     }
1587
1588     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1589     if (VA.needsCustom()) {
1590       if (VA.getLocVT() == MVT::v2f64) {
1591         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1592                                   DAG.getConstant(0, dl, MVT::i32));
1593         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1594                                   DAG.getConstant(1, dl, MVT::i32));
1595
1596         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1597                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1598
1599         VA = ArgLocs[++i]; // skip ahead to next loc
1600         if (VA.isRegLoc()) {
1601           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1602                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1603         } else {
1604           assert(VA.isMemLoc());
1605
1606           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1607                                                  dl, DAG, VA, Flags));
1608         }
1609       } else {
1610         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1611                          StackPtr, MemOpChains, Flags);
1612       }
1613     } else if (VA.isRegLoc()) {
1614       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1615         assert(VA.getLocVT() == MVT::i32 &&
1616                "unexpected calling convention register assignment");
1617         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1618                "unexpected use of 'returned'");
1619         isThisReturn = true;
1620       }
1621       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1622     } else if (isByVal) {
1623       assert(VA.isMemLoc());
1624       unsigned offset = 0;
1625
1626       // True if this byval aggregate will be split between registers
1627       // and memory.
1628       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1629       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1630
1631       if (CurByValIdx < ByValArgsCount) {
1632
1633         unsigned RegBegin, RegEnd;
1634         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1635
1636         EVT PtrVT =
1637             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1638         unsigned int i, j;
1639         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1640           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1641           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1642           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1643                                      MachinePointerInfo(),
1644                                      false, false, false,
1645                                      DAG.InferPtrAlignment(AddArg));
1646           MemOpChains.push_back(Load.getValue(1));
1647           RegsToPass.push_back(std::make_pair(j, Load));
1648         }
1649
1650         // If parameter size outsides register area, "offset" value
1651         // helps us to calculate stack slot for remained part properly.
1652         offset = RegEnd - RegBegin;
1653
1654         CCInfo.nextInRegsParam();
1655       }
1656
1657       if (Flags.getByValSize() > 4*offset) {
1658         auto PtrVT = getPointerTy(DAG.getDataLayout());
1659         unsigned LocMemOffset = VA.getLocMemOffset();
1660         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1661         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1662         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1663         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1664         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1665                                            MVT::i32);
1666         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1667                                             MVT::i32);
1668
1669         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1670         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1671         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1672                                           Ops));
1673       }
1674     } else if (!isSibCall) {
1675       assert(VA.isMemLoc());
1676
1677       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1678                                              dl, DAG, VA, Flags));
1679     }
1680   }
1681
1682   if (!MemOpChains.empty())
1683     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1684
1685   // Build a sequence of copy-to-reg nodes chained together with token chain
1686   // and flag operands which copy the outgoing args into the appropriate regs.
1687   SDValue InFlag;
1688   // Tail call byval lowering might overwrite argument registers so in case of
1689   // tail call optimization the copies to registers are lowered later.
1690   if (!isTailCall)
1691     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1692       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1693                                RegsToPass[i].second, InFlag);
1694       InFlag = Chain.getValue(1);
1695     }
1696
1697   // For tail calls lower the arguments to the 'real' stack slot.
1698   if (isTailCall) {
1699     // Force all the incoming stack arguments to be loaded from the stack
1700     // before any new outgoing arguments are stored to the stack, because the
1701     // outgoing stack slots may alias the incoming argument stack slots, and
1702     // the alias isn't otherwise explicit. This is slightly more conservative
1703     // than necessary, because it means that each store effectively depends
1704     // on every argument instead of just those arguments it would clobber.
1705
1706     // Do not flag preceding copytoreg stuff together with the following stuff.
1707     InFlag = SDValue();
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     InFlag = SDValue();
1714   }
1715
1716   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1717   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1718   // node so that legalize doesn't hack it.
1719   bool isDirect = false;
1720   bool isARMFunc = false;
1721   bool isLocalARMFunc = false;
1722   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1723   auto PtrVt = getPointerTy(DAG.getDataLayout());
1724
1725   if (Subtarget->genLongCalls()) {
1726     assert((Subtarget->isTargetWindows() ||
1727             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1728            "long-calls with non-static relocation model!");
1729     // Handle a global address or an external symbol. If it's not one of
1730     // those, the target's already in a register, so we don't need to do
1731     // anything extra.
1732     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1733       const GlobalValue *GV = G->getGlobal();
1734       // Create a constant pool entry for the callee address
1735       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1736       ARMConstantPoolValue *CPV =
1737         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1738
1739       // Get the address of the callee into a register
1740       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1741       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1742       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1743                            MachinePointerInfo::getConstantPool(), false, false,
1744                            false, 0);
1745     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1746       const char *Sym = S->getSymbol();
1747
1748       // Create a constant pool entry for the callee address
1749       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1750       ARMConstantPoolValue *CPV =
1751         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1752                                       ARMPCLabelIndex, 0);
1753       // Get the address of the callee into a register
1754       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1755       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1756       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1757                            MachinePointerInfo::getConstantPool(), false, false,
1758                            false, 0);
1759     }
1760   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1761     const GlobalValue *GV = G->getGlobal();
1762     isDirect = true;
1763     bool isDef = GV->isStrongDefinitionForLinker();
1764     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1765                    getTargetMachine().getRelocationModel() != Reloc::Static;
1766     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1767     // ARM call to a local ARM function is predicable.
1768     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1769     // tBX takes a register source operand.
1770     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1771       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1772       Callee = DAG.getNode(
1773           ARMISD::WrapperPIC, dl, PtrVt,
1774           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1775       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1776                            MachinePointerInfo::getGOT(), false, false, true, 0);
1777     } else if (Subtarget->isTargetCOFF()) {
1778       assert(Subtarget->isTargetWindows() &&
1779              "Windows is the only supported COFF target");
1780       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1781                                  ? ARMII::MO_DLLIMPORT
1782                                  : ARMII::MO_NO_FLAG;
1783       Callee =
1784           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1785       if (GV->hasDLLImportStorageClass())
1786         Callee =
1787             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1788                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1789                         MachinePointerInfo::getGOT(), false, false, false, 0);
1790     } else {
1791       // On ELF targets for PIC code, direct calls should go through the PLT
1792       unsigned OpFlags = 0;
1793       if (Subtarget->isTargetELF() &&
1794           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1795         OpFlags = ARMII::MO_PLT;
1796       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1797     }
1798   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1799     isDirect = true;
1800     bool isStub = Subtarget->isTargetMachO() &&
1801                   getTargetMachine().getRelocationModel() != Reloc::Static;
1802     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1803     // tBX takes a register source operand.
1804     const char *Sym = S->getSymbol();
1805     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1806       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1807       ARMConstantPoolValue *CPV =
1808         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1809                                       ARMPCLabelIndex, 4);
1810       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1811       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1812       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1813                            MachinePointerInfo::getConstantPool(), false, false,
1814                            false, 0);
1815       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1816       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1817     } else {
1818       unsigned OpFlags = 0;
1819       // On ELF targets for PIC code, direct calls should go through the PLT
1820       if (Subtarget->isTargetELF() &&
1821                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1822         OpFlags = ARMII::MO_PLT;
1823       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1824     }
1825   }
1826
1827   // FIXME: handle tail calls differently.
1828   unsigned CallOpc;
1829   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1830   if (Subtarget->isThumb()) {
1831     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1832       CallOpc = ARMISD::CALL_NOLINK;
1833     else
1834       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1835   } else {
1836     if (!isDirect && !Subtarget->hasV5TOps())
1837       CallOpc = ARMISD::CALL_NOLINK;
1838     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1839                // Emit regular call when code size is the priority
1840                !HasMinSizeAttr)
1841       // "mov lr, pc; b _foo" to avoid confusing the RSP
1842       CallOpc = ARMISD::CALL_NOLINK;
1843     else
1844       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1845   }
1846
1847   std::vector<SDValue> Ops;
1848   Ops.push_back(Chain);
1849   Ops.push_back(Callee);
1850
1851   // Add argument registers to the end of the list so that they are known live
1852   // into the call.
1853   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1854     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1855                                   RegsToPass[i].second.getValueType()));
1856
1857   // Add a register mask operand representing the call-preserved registers.
1858   if (!isTailCall) {
1859     const uint32_t *Mask;
1860     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1861     if (isThisReturn) {
1862       // For 'this' returns, use the R0-preserving mask if applicable
1863       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1864       if (!Mask) {
1865         // Set isThisReturn to false if the calling convention is not one that
1866         // allows 'returned' to be modeled in this way, so LowerCallResult does
1867         // not try to pass 'this' straight through
1868         isThisReturn = false;
1869         Mask = ARI->getCallPreservedMask(MF, CallConv);
1870       }
1871     } else
1872       Mask = ARI->getCallPreservedMask(MF, CallConv);
1873
1874     assert(Mask && "Missing call preserved mask for calling convention");
1875     Ops.push_back(DAG.getRegisterMask(Mask));
1876   }
1877
1878   if (InFlag.getNode())
1879     Ops.push_back(InFlag);
1880
1881   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1882   if (isTailCall) {
1883     MF.getFrameInfo()->setHasTailCall();
1884     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1885   }
1886
1887   // Returns a chain and a flag for retval copy to use.
1888   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1889   InFlag = Chain.getValue(1);
1890
1891   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1892                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1893   if (!Ins.empty())
1894     InFlag = Chain.getValue(1);
1895
1896   // Handle result values, copying them out of physregs into vregs that we
1897   // return.
1898   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1899                          InVals, isThisReturn,
1900                          isThisReturn ? OutVals[0] : SDValue());
1901 }
1902
1903 /// HandleByVal - Every parameter *after* a byval parameter is passed
1904 /// on the stack.  Remember the next parameter register to allocate,
1905 /// and then confiscate the rest of the parameter registers to insure
1906 /// this.
1907 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1908                                     unsigned Align) const {
1909   assert((State->getCallOrPrologue() == Prologue ||
1910           State->getCallOrPrologue() == Call) &&
1911          "unhandled ParmContext");
1912
1913   // Byval (as with any stack) slots are always at least 4 byte aligned.
1914   Align = std::max(Align, 4U);
1915
1916   unsigned Reg = State->AllocateReg(GPRArgRegs);
1917   if (!Reg)
1918     return;
1919
1920   unsigned AlignInRegs = Align / 4;
1921   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1922   for (unsigned i = 0; i < Waste; ++i)
1923     Reg = State->AllocateReg(GPRArgRegs);
1924
1925   if (!Reg)
1926     return;
1927
1928   unsigned Excess = 4 * (ARM::R4 - Reg);
1929
1930   // Special case when NSAA != SP and parameter size greater than size of
1931   // all remained GPR regs. In that case we can't split parameter, we must
1932   // send it to stack. We also must set NCRN to R4, so waste all
1933   // remained registers.
1934   const unsigned NSAAOffset = State->getNextStackOffset();
1935   if (NSAAOffset != 0 && Size > Excess) {
1936     while (State->AllocateReg(GPRArgRegs))
1937       ;
1938     return;
1939   }
1940
1941   // First register for byval parameter is the first register that wasn't
1942   // allocated before this method call, so it would be "reg".
1943   // If parameter is small enough to be saved in range [reg, r4), then
1944   // the end (first after last) register would be reg + param-size-in-regs,
1945   // else parameter would be splitted between registers and stack,
1946   // end register would be r4 in this case.
1947   unsigned ByValRegBegin = Reg;
1948   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1949   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1950   // Note, first register is allocated in the beginning of function already,
1951   // allocate remained amount of registers we need.
1952   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1953     State->AllocateReg(GPRArgRegs);
1954   // A byval parameter that is split between registers and memory needs its
1955   // size truncated here.
1956   // In the case where the entire structure fits in registers, we set the
1957   // size in memory to zero.
1958   Size = std::max<int>(Size - Excess, 0);
1959 }
1960
1961 /// MatchingStackOffset - Return true if the given stack call argument is
1962 /// already available in the same position (relatively) of the caller's
1963 /// incoming argument stack.
1964 static
1965 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1966                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1967                          const TargetInstrInfo *TII) {
1968   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1969   int FI = INT_MAX;
1970   if (Arg.getOpcode() == ISD::CopyFromReg) {
1971     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1972     if (!TargetRegisterInfo::isVirtualRegister(VR))
1973       return false;
1974     MachineInstr *Def = MRI->getVRegDef(VR);
1975     if (!Def)
1976       return false;
1977     if (!Flags.isByVal()) {
1978       if (!TII->isLoadFromStackSlot(Def, FI))
1979         return false;
1980     } else {
1981       return false;
1982     }
1983   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1984     if (Flags.isByVal())
1985       // ByVal argument is passed in as a pointer but it's now being
1986       // dereferenced. e.g.
1987       // define @foo(%struct.X* %A) {
1988       //   tail call @bar(%struct.X* byval %A)
1989       // }
1990       return false;
1991     SDValue Ptr = Ld->getBasePtr();
1992     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1993     if (!FINode)
1994       return false;
1995     FI = FINode->getIndex();
1996   } else
1997     return false;
1998
1999   assert(FI != INT_MAX);
2000   if (!MFI->isFixedObjectIndex(FI))
2001     return false;
2002   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2003 }
2004
2005 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2006 /// for tail call optimization. Targets which want to do tail call
2007 /// optimization should implement this function.
2008 bool
2009 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2010                                                      CallingConv::ID CalleeCC,
2011                                                      bool isVarArg,
2012                                                      bool isCalleeStructRet,
2013                                                      bool isCallerStructRet,
2014                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2015                                     const SmallVectorImpl<SDValue> &OutVals,
2016                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2017                                                      SelectionDAG& DAG) const {
2018   const Function *CallerF = DAG.getMachineFunction().getFunction();
2019   CallingConv::ID CallerCC = CallerF->getCallingConv();
2020   bool CCMatch = CallerCC == CalleeCC;
2021
2022   // Look for obvious safe cases to perform tail call optimization that do not
2023   // require ABI changes. This is what gcc calls sibcall.
2024
2025   // Do not sibcall optimize vararg calls unless the call site is not passing
2026   // any arguments.
2027   if (isVarArg && !Outs.empty())
2028     return false;
2029
2030   // Exception-handling functions need a special set of instructions to indicate
2031   // a return to the hardware. Tail-calling another function would probably
2032   // break this.
2033   if (CallerF->hasFnAttribute("interrupt"))
2034     return false;
2035
2036   // Also avoid sibcall optimization if either caller or callee uses struct
2037   // return semantics.
2038   if (isCalleeStructRet || isCallerStructRet)
2039     return false;
2040
2041   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2042   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2043   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2044   // support in the assembler and linker to be used. This would need to be
2045   // fixed to fully support tail calls in Thumb1.
2046   //
2047   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2048   // LR.  This means if we need to reload LR, it takes an extra instructions,
2049   // which outweighs the value of the tail call; but here we don't know yet
2050   // whether LR is going to be used.  Probably the right approach is to
2051   // generate the tail call here and turn it back into CALL/RET in
2052   // emitEpilogue if LR is used.
2053
2054   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2055   // but we need to make sure there are enough registers; the only valid
2056   // registers are the 4 used for parameters.  We don't currently do this
2057   // case.
2058   if (Subtarget->isThumb1Only())
2059     return false;
2060
2061   // Externally-defined functions with weak linkage should not be
2062   // tail-called on ARM when the OS does not support dynamic
2063   // pre-emption of symbols, as the AAELF spec requires normal calls
2064   // to undefined weak functions to be replaced with a NOP or jump to the
2065   // next instruction. The behaviour of branch instructions in this
2066   // situation (as used for tail calls) is implementation-defined, so we
2067   // cannot rely on the linker replacing the tail call with a return.
2068   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2069     const GlobalValue *GV = G->getGlobal();
2070     const Triple &TT = getTargetMachine().getTargetTriple();
2071     if (GV->hasExternalWeakLinkage() &&
2072         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2073       return false;
2074   }
2075
2076   // If the calling conventions do not match, then we'd better make sure the
2077   // results are returned in the same way as what the caller expects.
2078   if (!CCMatch) {
2079     SmallVector<CCValAssign, 16> RVLocs1;
2080     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2081                        *DAG.getContext(), Call);
2082     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2083
2084     SmallVector<CCValAssign, 16> RVLocs2;
2085     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2086                        *DAG.getContext(), Call);
2087     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2088
2089     if (RVLocs1.size() != RVLocs2.size())
2090       return false;
2091     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2092       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2093         return false;
2094       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2095         return false;
2096       if (RVLocs1[i].isRegLoc()) {
2097         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2098           return false;
2099       } else {
2100         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2101           return false;
2102       }
2103     }
2104   }
2105
2106   // If Caller's vararg or byval argument has been split between registers and
2107   // stack, do not perform tail call, since part of the argument is in caller's
2108   // local frame.
2109   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2110                                       getInfo<ARMFunctionInfo>();
2111   if (AFI_Caller->getArgRegsSaveSize())
2112     return false;
2113
2114   // If the callee takes no arguments then go on to check the results of the
2115   // call.
2116   if (!Outs.empty()) {
2117     // Check if stack adjustment is needed. For now, do not do this if any
2118     // argument is passed on the stack.
2119     SmallVector<CCValAssign, 16> ArgLocs;
2120     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2121                       *DAG.getContext(), Call);
2122     CCInfo.AnalyzeCallOperands(Outs,
2123                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2124     if (CCInfo.getNextStackOffset()) {
2125       MachineFunction &MF = DAG.getMachineFunction();
2126
2127       // Check if the arguments are already laid out in the right way as
2128       // the caller's fixed stack objects.
2129       MachineFrameInfo *MFI = MF.getFrameInfo();
2130       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2131       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2132       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2133            i != e;
2134            ++i, ++realArgIdx) {
2135         CCValAssign &VA = ArgLocs[i];
2136         EVT RegVT = VA.getLocVT();
2137         SDValue Arg = OutVals[realArgIdx];
2138         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2139         if (VA.getLocInfo() == CCValAssign::Indirect)
2140           return false;
2141         if (VA.needsCustom()) {
2142           // f64 and vector types are split into multiple registers or
2143           // register/stack-slot combinations.  The types will not match
2144           // the registers; give up on memory f64 refs until we figure
2145           // out what to do about this.
2146           if (!VA.isRegLoc())
2147             return false;
2148           if (!ArgLocs[++i].isRegLoc())
2149             return false;
2150           if (RegVT == MVT::v2f64) {
2151             if (!ArgLocs[++i].isRegLoc())
2152               return false;
2153             if (!ArgLocs[++i].isRegLoc())
2154               return false;
2155           }
2156         } else if (!VA.isRegLoc()) {
2157           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2158                                    MFI, MRI, TII))
2159             return false;
2160         }
2161       }
2162     }
2163   }
2164
2165   return true;
2166 }
2167
2168 bool
2169 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2170                                   MachineFunction &MF, bool isVarArg,
2171                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2172                                   LLVMContext &Context) const {
2173   SmallVector<CCValAssign, 16> RVLocs;
2174   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2175   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2176                                                     isVarArg));
2177 }
2178
2179 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2180                                     SDLoc DL, SelectionDAG &DAG) {
2181   const MachineFunction &MF = DAG.getMachineFunction();
2182   const Function *F = MF.getFunction();
2183
2184   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2185
2186   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2187   // version of the "preferred return address". These offsets affect the return
2188   // instruction if this is a return from PL1 without hypervisor extensions.
2189   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2190   //    SWI:     0      "subs pc, lr, #0"
2191   //    ABORT:   +4     "subs pc, lr, #4"
2192   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2193   // UNDEF varies depending on where the exception came from ARM or Thumb
2194   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2195
2196   int64_t LROffset;
2197   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2198       IntKind == "ABORT")
2199     LROffset = 4;
2200   else if (IntKind == "SWI" || IntKind == "UNDEF")
2201     LROffset = 0;
2202   else
2203     report_fatal_error("Unsupported interrupt attribute. If present, value "
2204                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2205
2206   RetOps.insert(RetOps.begin() + 1,
2207                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2208
2209   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2210 }
2211
2212 SDValue
2213 ARMTargetLowering::LowerReturn(SDValue Chain,
2214                                CallingConv::ID CallConv, bool isVarArg,
2215                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2216                                const SmallVectorImpl<SDValue> &OutVals,
2217                                SDLoc dl, SelectionDAG &DAG) const {
2218
2219   // CCValAssign - represent the assignment of the return value to a location.
2220   SmallVector<CCValAssign, 16> RVLocs;
2221
2222   // CCState - Info about the registers and stack slots.
2223   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2224                     *DAG.getContext(), Call);
2225
2226   // Analyze outgoing return values.
2227   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2228                                                isVarArg));
2229
2230   SDValue Flag;
2231   SmallVector<SDValue, 4> RetOps;
2232   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2233   bool isLittleEndian = Subtarget->isLittle();
2234
2235   MachineFunction &MF = DAG.getMachineFunction();
2236   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2237   AFI->setReturnRegsCount(RVLocs.size());
2238
2239   // Copy the result values into the output registers.
2240   for (unsigned i = 0, realRVLocIdx = 0;
2241        i != RVLocs.size();
2242        ++i, ++realRVLocIdx) {
2243     CCValAssign &VA = RVLocs[i];
2244     assert(VA.isRegLoc() && "Can only return in registers!");
2245
2246     SDValue Arg = OutVals[realRVLocIdx];
2247
2248     switch (VA.getLocInfo()) {
2249     default: llvm_unreachable("Unknown loc info!");
2250     case CCValAssign::Full: break;
2251     case CCValAssign::BCvt:
2252       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2253       break;
2254     }
2255
2256     if (VA.needsCustom()) {
2257       if (VA.getLocVT() == MVT::v2f64) {
2258         // Extract the first half and return it in two registers.
2259         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2260                                    DAG.getConstant(0, dl, MVT::i32));
2261         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2262                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2263
2264         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2265                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2266                                  Flag);
2267         Flag = Chain.getValue(1);
2268         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2269         VA = RVLocs[++i]; // skip ahead to next loc
2270         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2271                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2272                                  Flag);
2273         Flag = Chain.getValue(1);
2274         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2275         VA = RVLocs[++i]; // skip ahead to next loc
2276
2277         // Extract the 2nd half and fall through to handle it as an f64 value.
2278         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2279                           DAG.getConstant(1, dl, MVT::i32));
2280       }
2281       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2282       // available.
2283       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2284                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2285       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2286                                fmrrd.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                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2293                                Flag);
2294     } else
2295       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2296
2297     // Guarantee that all emitted copies are
2298     // stuck together, avoiding something bad.
2299     Flag = Chain.getValue(1);
2300     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2301   }
2302
2303   // Update chain and glue.
2304   RetOps[0] = Chain;
2305   if (Flag.getNode())
2306     RetOps.push_back(Flag);
2307
2308   // CPUs which aren't M-class use a special sequence to return from
2309   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2310   // though we use "subs pc, lr, #N").
2311   //
2312   // M-class CPUs actually use a normal return sequence with a special
2313   // (hardware-provided) value in LR, so the normal code path works.
2314   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2315       !Subtarget->isMClass()) {
2316     if (Subtarget->isThumb1Only())
2317       report_fatal_error("interrupt attribute is not supported in Thumb1");
2318     return LowerInterruptReturn(RetOps, dl, DAG);
2319   }
2320
2321   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2322 }
2323
2324 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2325   if (N->getNumValues() != 1)
2326     return false;
2327   if (!N->hasNUsesOfValue(1, 0))
2328     return false;
2329
2330   SDValue TCChain = Chain;
2331   SDNode *Copy = *N->use_begin();
2332   if (Copy->getOpcode() == ISD::CopyToReg) {
2333     // If the copy has a glue operand, we conservatively assume it isn't safe to
2334     // perform a tail call.
2335     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2336       return false;
2337     TCChain = Copy->getOperand(0);
2338   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2339     SDNode *VMov = Copy;
2340     // f64 returned in a pair of GPRs.
2341     SmallPtrSet<SDNode*, 2> Copies;
2342     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2343          UI != UE; ++UI) {
2344       if (UI->getOpcode() != ISD::CopyToReg)
2345         return false;
2346       Copies.insert(*UI);
2347     }
2348     if (Copies.size() > 2)
2349       return false;
2350
2351     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2352          UI != UE; ++UI) {
2353       SDValue UseChain = UI->getOperand(0);
2354       if (Copies.count(UseChain.getNode()))
2355         // Second CopyToReg
2356         Copy = *UI;
2357       else {
2358         // We are at the top of this chain.
2359         // If the copy has a glue operand, we conservatively assume it
2360         // isn't safe to perform a tail call.
2361         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2362           return false;
2363         // First CopyToReg
2364         TCChain = UseChain;
2365       }
2366     }
2367   } else if (Copy->getOpcode() == ISD::BITCAST) {
2368     // f32 returned in a single GPR.
2369     if (!Copy->hasOneUse())
2370       return false;
2371     Copy = *Copy->use_begin();
2372     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2373       return false;
2374     // If the copy has a glue operand, we conservatively assume it isn't safe to
2375     // perform a tail call.
2376     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2377       return false;
2378     TCChain = Copy->getOperand(0);
2379   } else {
2380     return false;
2381   }
2382
2383   bool HasRet = false;
2384   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2385        UI != UE; ++UI) {
2386     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2387         UI->getOpcode() != ARMISD::INTRET_FLAG)
2388       return false;
2389     HasRet = true;
2390   }
2391
2392   if (!HasRet)
2393     return false;
2394
2395   Chain = TCChain;
2396   return true;
2397 }
2398
2399 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2400   if (!Subtarget->supportsTailCall())
2401     return false;
2402
2403   auto Attr =
2404       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2405   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2406     return false;
2407
2408   return !Subtarget->isThumb1Only();
2409 }
2410
2411 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2412 // and pass the lower and high parts through.
2413 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2414   SDLoc DL(Op);
2415   SDValue WriteValue = Op->getOperand(2);
2416
2417   // This function is only supposed to be called for i64 type argument.
2418   assert(WriteValue.getValueType() == MVT::i64
2419           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2420
2421   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2422                            DAG.getConstant(0, DL, MVT::i32));
2423   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2424                            DAG.getConstant(1, DL, MVT::i32));
2425   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2426   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2427 }
2428
2429 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2430 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2431 // one of the above mentioned nodes. It has to be wrapped because otherwise
2432 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2433 // be used to form addressing mode. These wrapped nodes will be selected
2434 // into MOVi.
2435 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2436   EVT PtrVT = Op.getValueType();
2437   // FIXME there is no actual debug info here
2438   SDLoc dl(Op);
2439   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2440   SDValue Res;
2441   if (CP->isMachineConstantPoolEntry())
2442     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2443                                     CP->getAlignment());
2444   else
2445     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2446                                     CP->getAlignment());
2447   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2448 }
2449
2450 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2451   return MachineJumpTableInfo::EK_Inline;
2452 }
2453
2454 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2455                                              SelectionDAG &DAG) const {
2456   MachineFunction &MF = DAG.getMachineFunction();
2457   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2458   unsigned ARMPCLabelIndex = 0;
2459   SDLoc DL(Op);
2460   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2461   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2462   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2463   SDValue CPAddr;
2464   if (RelocM == Reloc::Static) {
2465     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2466   } else {
2467     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2468     ARMPCLabelIndex = AFI->createPICLabelUId();
2469     ARMConstantPoolValue *CPV =
2470       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2471                                       ARMCP::CPBlockAddress, PCAdj);
2472     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2473   }
2474   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2475   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2476                                MachinePointerInfo::getConstantPool(),
2477                                false, false, false, 0);
2478   if (RelocM == Reloc::Static)
2479     return Result;
2480   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2481   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2482 }
2483
2484 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2485 SDValue
2486 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2487                                                  SelectionDAG &DAG) const {
2488   SDLoc dl(GA);
2489   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2490   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2491   MachineFunction &MF = DAG.getMachineFunction();
2492   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2493   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2494   ARMConstantPoolValue *CPV =
2495     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2496                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2497   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2498   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2499   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2500                          MachinePointerInfo::getConstantPool(),
2501                          false, false, false, 0);
2502   SDValue Chain = Argument.getValue(1);
2503
2504   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2505   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2506
2507   // call __tls_get_addr.
2508   ArgListTy Args;
2509   ArgListEntry Entry;
2510   Entry.Node = Argument;
2511   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2512   Args.push_back(Entry);
2513
2514   // FIXME: is there useful debug info available here?
2515   TargetLowering::CallLoweringInfo CLI(DAG);
2516   CLI.setDebugLoc(dl).setChain(Chain)
2517     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2518                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2519                0);
2520
2521   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2522   return CallResult.first;
2523 }
2524
2525 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2526 // "local exec" model.
2527 SDValue
2528 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2529                                         SelectionDAG &DAG,
2530                                         TLSModel::Model model) const {
2531   const GlobalValue *GV = GA->getGlobal();
2532   SDLoc dl(GA);
2533   SDValue Offset;
2534   SDValue Chain = DAG.getEntryNode();
2535   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2536   // Get the Thread Pointer
2537   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2538
2539   if (model == TLSModel::InitialExec) {
2540     MachineFunction &MF = DAG.getMachineFunction();
2541     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2542     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2543     // Initial exec model.
2544     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2545     ARMConstantPoolValue *CPV =
2546       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2547                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2548                                       true);
2549     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2550     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2551     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2552                          MachinePointerInfo::getConstantPool(),
2553                          false, false, false, 0);
2554     Chain = Offset.getValue(1);
2555
2556     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2557     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2558
2559     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2560                          MachinePointerInfo::getConstantPool(),
2561                          false, false, false, 0);
2562   } else {
2563     // local exec model
2564     assert(model == TLSModel::LocalExec);
2565     ARMConstantPoolValue *CPV =
2566       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2567     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2568     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2569     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2570                          MachinePointerInfo::getConstantPool(),
2571                          false, false, false, 0);
2572   }
2573
2574   // The address of the thread local variable is the add of the thread
2575   // pointer with the offset of the variable.
2576   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2577 }
2578
2579 SDValue
2580 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2581   // TODO: implement the "local dynamic" model
2582   assert(Subtarget->isTargetELF() &&
2583          "TLS not implemented for non-ELF targets");
2584   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2585   if (DAG.getTarget().Options.EmulatedTLS)
2586     return LowerToTLSEmulatedModel(GA, DAG);
2587
2588   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2589
2590   switch (model) {
2591     case TLSModel::GeneralDynamic:
2592     case TLSModel::LocalDynamic:
2593       return LowerToTLSGeneralDynamicModel(GA, DAG);
2594     case TLSModel::InitialExec:
2595     case TLSModel::LocalExec:
2596       return LowerToTLSExecModels(GA, DAG, model);
2597   }
2598   llvm_unreachable("bogus TLS model");
2599 }
2600
2601 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2602                                                  SelectionDAG &DAG) const {
2603   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2604   SDLoc dl(Op);
2605   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2606   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2607     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2608     ARMConstantPoolValue *CPV =
2609       ARMConstantPoolConstant::Create(GV,
2610                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2611     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2612     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2613     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2614                                  CPAddr,
2615                                  MachinePointerInfo::getConstantPool(),
2616                                  false, false, false, 0);
2617     SDValue Chain = Result.getValue(1);
2618     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2619     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2620     if (!UseGOTOFF)
2621       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2622                            MachinePointerInfo::getGOT(),
2623                            false, false, false, 0);
2624     return Result;
2625   }
2626
2627   // If we have T2 ops, we can materialize the address directly via movt/movw
2628   // pair. This is always cheaper.
2629   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2630     ++NumMovwMovt;
2631     // FIXME: Once remat is capable of dealing with instructions with register
2632     // operands, expand this into two nodes.
2633     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2634                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2635   } else {
2636     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2637     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2638     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2639                        MachinePointerInfo::getConstantPool(),
2640                        false, false, false, 0);
2641   }
2642 }
2643
2644 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2645                                                     SelectionDAG &DAG) const {
2646   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2647   SDLoc dl(Op);
2648   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2649   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2650
2651   if (Subtarget->useMovt(DAG.getMachineFunction()))
2652     ++NumMovwMovt;
2653
2654   // FIXME: Once remat is capable of dealing with instructions with register
2655   // operands, expand this into multiple nodes
2656   unsigned Wrapper =
2657       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2658
2659   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2660   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2661
2662   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2663     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2664                          MachinePointerInfo::getGOT(), false, false, false, 0);
2665   return Result;
2666 }
2667
2668 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2669                                                      SelectionDAG &DAG) const {
2670   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2671   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2672          "Windows on ARM expects to use movw/movt");
2673
2674   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2675   const ARMII::TOF TargetFlags =
2676     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2677   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2678   SDValue Result;
2679   SDLoc DL(Op);
2680
2681   ++NumMovwMovt;
2682
2683   // FIXME: Once remat is capable of dealing with instructions with register
2684   // operands, expand this into two nodes.
2685   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2686                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2687                                                   TargetFlags));
2688   if (GV->hasDLLImportStorageClass())
2689     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2690                          MachinePointerInfo::getGOT(), false, false, false, 0);
2691   return Result;
2692 }
2693
2694 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2695                                                     SelectionDAG &DAG) const {
2696   assert(Subtarget->isTargetELF() &&
2697          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2698   MachineFunction &MF = DAG.getMachineFunction();
2699   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2700   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2701   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2702   SDLoc dl(Op);
2703   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2704   ARMConstantPoolValue *CPV =
2705     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2706                                   ARMPCLabelIndex, PCAdj);
2707   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2708   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2709   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2710                                MachinePointerInfo::getConstantPool(),
2711                                false, false, false, 0);
2712   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2713   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2714 }
2715
2716 SDValue
2717 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2718   SDLoc dl(Op);
2719   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2720   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2721                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2722                      Op.getOperand(1), Val);
2723 }
2724
2725 SDValue
2726 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2727   SDLoc dl(Op);
2728   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2729                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2730 }
2731
2732 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2733                                                       SelectionDAG &DAG) const {
2734   SDLoc dl(Op);
2735   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2736                      Op.getOperand(0));
2737 }
2738
2739 SDValue
2740 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2741                                           const ARMSubtarget *Subtarget) const {
2742   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2743   SDLoc dl(Op);
2744   switch (IntNo) {
2745   default: return SDValue();    // Don't custom lower most intrinsics.
2746   case Intrinsic::arm_rbit: {
2747     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2748            "RBIT intrinsic must have i32 type!");
2749     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2750   }
2751   case Intrinsic::arm_thread_pointer: {
2752     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2753     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2754   }
2755   case Intrinsic::eh_sjlj_lsda: {
2756     MachineFunction &MF = DAG.getMachineFunction();
2757     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2758     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2759     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2760     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2761     SDValue CPAddr;
2762     unsigned PCAdj = (RelocM != Reloc::PIC_)
2763       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2764     ARMConstantPoolValue *CPV =
2765       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2766                                       ARMCP::CPLSDA, PCAdj);
2767     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2768     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2769     SDValue Result =
2770       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2771                   MachinePointerInfo::getConstantPool(),
2772                   false, false, false, 0);
2773
2774     if (RelocM == Reloc::PIC_) {
2775       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2776       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2777     }
2778     return Result;
2779   }
2780   case Intrinsic::arm_neon_vmulls:
2781   case Intrinsic::arm_neon_vmullu: {
2782     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2783       ? ARMISD::VMULLs : ARMISD::VMULLu;
2784     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2785                        Op.getOperand(1), Op.getOperand(2));
2786   }
2787   }
2788 }
2789
2790 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2791                                  const ARMSubtarget *Subtarget) {
2792   // FIXME: handle "fence singlethread" more efficiently.
2793   SDLoc dl(Op);
2794   if (!Subtarget->hasDataBarrier()) {
2795     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2796     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2797     // here.
2798     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2799            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2800     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2801                        DAG.getConstant(0, dl, MVT::i32));
2802   }
2803
2804   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2805   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2806   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2807   if (Subtarget->isMClass()) {
2808     // Only a full system barrier exists in the M-class architectures.
2809     Domain = ARM_MB::SY;
2810   } else if (Subtarget->isSwift() && Ord == Release) {
2811     // Swift happens to implement ISHST barriers in a way that's compatible with
2812     // Release semantics but weaker than ISH so we'd be fools not to use
2813     // it. Beware: other processors probably don't!
2814     Domain = ARM_MB::ISHST;
2815   }
2816
2817   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2818                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2819                      DAG.getConstant(Domain, dl, MVT::i32));
2820 }
2821
2822 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2823                              const ARMSubtarget *Subtarget) {
2824   // ARM pre v5TE and Thumb1 does not have preload instructions.
2825   if (!(Subtarget->isThumb2() ||
2826         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2827     // Just preserve the chain.
2828     return Op.getOperand(0);
2829
2830   SDLoc dl(Op);
2831   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2832   if (!isRead &&
2833       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2834     // ARMv7 with MP extension has PLDW.
2835     return Op.getOperand(0);
2836
2837   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2838   if (Subtarget->isThumb()) {
2839     // Invert the bits.
2840     isRead = ~isRead & 1;
2841     isData = ~isData & 1;
2842   }
2843
2844   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2845                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2846                      DAG.getConstant(isData, dl, MVT::i32));
2847 }
2848
2849 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2850   MachineFunction &MF = DAG.getMachineFunction();
2851   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2852
2853   // vastart just stores the address of the VarArgsFrameIndex slot into the
2854   // memory location argument.
2855   SDLoc dl(Op);
2856   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2857   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2858   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2859   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2860                       MachinePointerInfo(SV), false, false, 0);
2861 }
2862
2863 SDValue
2864 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2865                                         SDValue &Root, SelectionDAG &DAG,
2866                                         SDLoc dl) const {
2867   MachineFunction &MF = DAG.getMachineFunction();
2868   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2869
2870   const TargetRegisterClass *RC;
2871   if (AFI->isThumb1OnlyFunction())
2872     RC = &ARM::tGPRRegClass;
2873   else
2874     RC = &ARM::GPRRegClass;
2875
2876   // Transform the arguments stored in physical registers into virtual ones.
2877   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2878   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2879
2880   SDValue ArgValue2;
2881   if (NextVA.isMemLoc()) {
2882     MachineFrameInfo *MFI = MF.getFrameInfo();
2883     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2884
2885     // Create load node to retrieve arguments from the stack.
2886     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2887     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2888                             MachinePointerInfo::getFixedStack(FI),
2889                             false, false, false, 0);
2890   } else {
2891     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2892     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2893   }
2894   if (!Subtarget->isLittle())
2895     std::swap (ArgValue, ArgValue2);
2896   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2897 }
2898
2899 // The remaining GPRs hold either the beginning of variable-argument
2900 // data, or the beginning of an aggregate passed by value (usually
2901 // byval).  Either way, we allocate stack slots adjacent to the data
2902 // provided by our caller, and store the unallocated registers there.
2903 // If this is a variadic function, the va_list pointer will begin with
2904 // these values; otherwise, this reassembles a (byval) structure that
2905 // was split between registers and memory.
2906 // Return: The frame index registers were stored into.
2907 int
2908 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2909                                   SDLoc dl, SDValue &Chain,
2910                                   const Value *OrigArg,
2911                                   unsigned InRegsParamRecordIdx,
2912                                   int ArgOffset,
2913                                   unsigned ArgSize) const {
2914   // Currently, two use-cases possible:
2915   // Case #1. Non-var-args function, and we meet first byval parameter.
2916   //          Setup first unallocated register as first byval register;
2917   //          eat all remained registers
2918   //          (these two actions are performed by HandleByVal method).
2919   //          Then, here, we initialize stack frame with
2920   //          "store-reg" instructions.
2921   // Case #2. Var-args function, that doesn't contain byval parameters.
2922   //          The same: eat all remained unallocated registers,
2923   //          initialize stack frame.
2924
2925   MachineFunction &MF = DAG.getMachineFunction();
2926   MachineFrameInfo *MFI = MF.getFrameInfo();
2927   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2928   unsigned RBegin, REnd;
2929   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2930     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2931   } else {
2932     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2933     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2934     REnd = ARM::R4;
2935   }
2936
2937   if (REnd != RBegin)
2938     ArgOffset = -4 * (ARM::R4 - RBegin);
2939
2940   auto PtrVT = getPointerTy(DAG.getDataLayout());
2941   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2942   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
2943
2944   SmallVector<SDValue, 4> MemOps;
2945   const TargetRegisterClass *RC =
2946       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2947
2948   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2949     unsigned VReg = MF.addLiveIn(Reg, RC);
2950     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2951     SDValue Store =
2952         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2953                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2954     MemOps.push_back(Store);
2955     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
2956   }
2957
2958   if (!MemOps.empty())
2959     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2960   return FrameIndex;
2961 }
2962
2963 // Setup stack frame, the va_list pointer will start from.
2964 void
2965 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2966                                         SDLoc dl, SDValue &Chain,
2967                                         unsigned ArgOffset,
2968                                         unsigned TotalArgRegsSaveSize,
2969                                         bool ForceMutable) const {
2970   MachineFunction &MF = DAG.getMachineFunction();
2971   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2972
2973   // Try to store any remaining integer argument regs
2974   // to their spots on the stack so that they may be loaded by deferencing
2975   // the result of va_next.
2976   // If there is no regs to be stored, just point address after last
2977   // argument passed via stack.
2978   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2979                                   CCInfo.getInRegsParamsCount(),
2980                                   CCInfo.getNextStackOffset(), 4);
2981   AFI->setVarArgsFrameIndex(FrameIndex);
2982 }
2983
2984 SDValue
2985 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2986                                         CallingConv::ID CallConv, bool isVarArg,
2987                                         const SmallVectorImpl<ISD::InputArg>
2988                                           &Ins,
2989                                         SDLoc dl, SelectionDAG &DAG,
2990                                         SmallVectorImpl<SDValue> &InVals)
2991                                           const {
2992   MachineFunction &MF = DAG.getMachineFunction();
2993   MachineFrameInfo *MFI = MF.getFrameInfo();
2994
2995   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2996
2997   // Assign locations to all of the incoming arguments.
2998   SmallVector<CCValAssign, 16> ArgLocs;
2999   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3000                     *DAG.getContext(), Prologue);
3001   CCInfo.AnalyzeFormalArguments(Ins,
3002                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3003                                                   isVarArg));
3004
3005   SmallVector<SDValue, 16> ArgValues;
3006   SDValue ArgValue;
3007   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3008   unsigned CurArgIdx = 0;
3009
3010   // Initially ArgRegsSaveSize is zero.
3011   // Then we increase this value each time we meet byval parameter.
3012   // We also increase this value in case of varargs function.
3013   AFI->setArgRegsSaveSize(0);
3014
3015   // Calculate the amount of stack space that we need to allocate to store
3016   // byval and variadic arguments that are passed in registers.
3017   // We need to know this before we allocate the first byval or variadic
3018   // argument, as they will be allocated a stack slot below the CFA (Canonical
3019   // Frame Address, the stack pointer at entry to the function).
3020   unsigned ArgRegBegin = ARM::R4;
3021   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3022     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3023       break;
3024
3025     CCValAssign &VA = ArgLocs[i];
3026     unsigned Index = VA.getValNo();
3027     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3028     if (!Flags.isByVal())
3029       continue;
3030
3031     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3032     unsigned RBegin, REnd;
3033     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3034     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3035
3036     CCInfo.nextInRegsParam();
3037   }
3038   CCInfo.rewindByValRegsInfo();
3039
3040   int lastInsIndex = -1;
3041   if (isVarArg && MFI->hasVAStart()) {
3042     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3043     if (RegIdx != array_lengthof(GPRArgRegs))
3044       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3045   }
3046
3047   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3048   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3049   auto PtrVT = getPointerTy(DAG.getDataLayout());
3050
3051   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3052     CCValAssign &VA = ArgLocs[i];
3053     if (Ins[VA.getValNo()].isOrigArg()) {
3054       std::advance(CurOrigArg,
3055                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3056       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3057     }
3058     // Arguments stored in registers.
3059     if (VA.isRegLoc()) {
3060       EVT RegVT = VA.getLocVT();
3061
3062       if (VA.needsCustom()) {
3063         // f64 and vector types are split up into multiple registers or
3064         // combinations of registers and stack slots.
3065         if (VA.getLocVT() == MVT::v2f64) {
3066           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3067                                                    Chain, DAG, dl);
3068           VA = ArgLocs[++i]; // skip ahead to next loc
3069           SDValue ArgValue2;
3070           if (VA.isMemLoc()) {
3071             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3072             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3073             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3074                                     MachinePointerInfo::getFixedStack(FI),
3075                                     false, false, false, 0);
3076           } else {
3077             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3078                                              Chain, DAG, dl);
3079           }
3080           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3081           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3082                                  ArgValue, ArgValue1,
3083                                  DAG.getIntPtrConstant(0, dl));
3084           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3085                                  ArgValue, ArgValue2,
3086                                  DAG.getIntPtrConstant(1, dl));
3087         } else
3088           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3089
3090       } else {
3091         const TargetRegisterClass *RC;
3092
3093         if (RegVT == MVT::f32)
3094           RC = &ARM::SPRRegClass;
3095         else if (RegVT == MVT::f64)
3096           RC = &ARM::DPRRegClass;
3097         else if (RegVT == MVT::v2f64)
3098           RC = &ARM::QPRRegClass;
3099         else if (RegVT == MVT::i32)
3100           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3101                                            : &ARM::GPRRegClass;
3102         else
3103           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3104
3105         // Transform the arguments in physical registers into virtual ones.
3106         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3107         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3108       }
3109
3110       // If this is an 8 or 16-bit value, it is really passed promoted
3111       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3112       // truncate to the right size.
3113       switch (VA.getLocInfo()) {
3114       default: llvm_unreachable("Unknown loc info!");
3115       case CCValAssign::Full: break;
3116       case CCValAssign::BCvt:
3117         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3118         break;
3119       case CCValAssign::SExt:
3120         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3121                                DAG.getValueType(VA.getValVT()));
3122         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3123         break;
3124       case CCValAssign::ZExt:
3125         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3126                                DAG.getValueType(VA.getValVT()));
3127         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3128         break;
3129       }
3130
3131       InVals.push_back(ArgValue);
3132
3133     } else { // VA.isRegLoc()
3134
3135       // sanity check
3136       assert(VA.isMemLoc());
3137       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3138
3139       int index = VA.getValNo();
3140
3141       // Some Ins[] entries become multiple ArgLoc[] entries.
3142       // Process them only once.
3143       if (index != lastInsIndex)
3144         {
3145           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3146           // FIXME: For now, all byval parameter objects are marked mutable.
3147           // This can be changed with more analysis.
3148           // In case of tail call optimization mark all arguments mutable.
3149           // Since they could be overwritten by lowering of arguments in case of
3150           // a tail call.
3151           if (Flags.isByVal()) {
3152             assert(Ins[index].isOrigArg() &&
3153                    "Byval arguments cannot be implicit");
3154             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3155
3156             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3157                                             CurByValIndex, VA.getLocMemOffset(),
3158                                             Flags.getByValSize());
3159             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3160             CCInfo.nextInRegsParam();
3161           } else {
3162             unsigned FIOffset = VA.getLocMemOffset();
3163             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3164                                             FIOffset, true);
3165
3166             // Create load nodes to retrieve arguments from the stack.
3167             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3168             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3169                                          MachinePointerInfo::getFixedStack(FI),
3170                                          false, false, false, 0));
3171           }
3172           lastInsIndex = index;
3173         }
3174     }
3175   }
3176
3177   // varargs
3178   if (isVarArg && MFI->hasVAStart())
3179     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3180                          CCInfo.getNextStackOffset(),
3181                          TotalArgRegsSaveSize);
3182
3183   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3184
3185   return Chain;
3186 }
3187
3188 /// isFloatingPointZero - Return true if this is +0.0.
3189 static bool isFloatingPointZero(SDValue Op) {
3190   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3191     return CFP->getValueAPF().isPosZero();
3192   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3193     // Maybe this has already been legalized into the constant pool?
3194     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3195       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3196       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3197         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3198           return CFP->getValueAPF().isPosZero();
3199     }
3200   } else if (Op->getOpcode() == ISD::BITCAST &&
3201              Op->getValueType(0) == MVT::f64) {
3202     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3203     // created by LowerConstantFP().
3204     SDValue BitcastOp = Op->getOperand(0);
3205     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3206       SDValue MoveOp = BitcastOp->getOperand(0);
3207       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3208           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3209         return true;
3210       }
3211     }
3212   }
3213   return false;
3214 }
3215
3216 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3217 /// the given operands.
3218 SDValue
3219 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3220                              SDValue &ARMcc, SelectionDAG &DAG,
3221                              SDLoc dl) const {
3222   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3223     unsigned C = RHSC->getZExtValue();
3224     if (!isLegalICmpImmediate(C)) {
3225       // Constant does not fit, try adjusting it by one?
3226       switch (CC) {
3227       default: break;
3228       case ISD::SETLT:
3229       case ISD::SETGE:
3230         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3231           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3232           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3233         }
3234         break;
3235       case ISD::SETULT:
3236       case ISD::SETUGE:
3237         if (C != 0 && isLegalICmpImmediate(C-1)) {
3238           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3239           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3240         }
3241         break;
3242       case ISD::SETLE:
3243       case ISD::SETGT:
3244         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3245           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3246           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3247         }
3248         break;
3249       case ISD::SETULE:
3250       case ISD::SETUGT:
3251         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3252           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3253           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3254         }
3255         break;
3256       }
3257     }
3258   }
3259
3260   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3261   ARMISD::NodeType CompareType;
3262   switch (CondCode) {
3263   default:
3264     CompareType = ARMISD::CMP;
3265     break;
3266   case ARMCC::EQ:
3267   case ARMCC::NE:
3268     // Uses only Z Flag
3269     CompareType = ARMISD::CMPZ;
3270     break;
3271   }
3272   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3273   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3274 }
3275
3276 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3277 SDValue
3278 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3279                              SDLoc dl) const {
3280   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3281   SDValue Cmp;
3282   if (!isFloatingPointZero(RHS))
3283     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3284   else
3285     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3286   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3287 }
3288
3289 /// duplicateCmp - Glue values can have only one use, so this function
3290 /// duplicates a comparison node.
3291 SDValue
3292 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3293   unsigned Opc = Cmp.getOpcode();
3294   SDLoc DL(Cmp);
3295   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3296     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3297
3298   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3299   Cmp = Cmp.getOperand(0);
3300   Opc = Cmp.getOpcode();
3301   if (Opc == ARMISD::CMPFP)
3302     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3303   else {
3304     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3305     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3306   }
3307   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3308 }
3309
3310 std::pair<SDValue, SDValue>
3311 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3312                                  SDValue &ARMcc) const {
3313   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3314
3315   SDValue Value, OverflowCmp;
3316   SDValue LHS = Op.getOperand(0);
3317   SDValue RHS = Op.getOperand(1);
3318   SDLoc dl(Op);
3319
3320   // FIXME: We are currently always generating CMPs because we don't support
3321   // generating CMN through the backend. This is not as good as the natural
3322   // CMP case because it causes a register dependency and cannot be folded
3323   // later.
3324
3325   switch (Op.getOpcode()) {
3326   default:
3327     llvm_unreachable("Unknown overflow instruction!");
3328   case ISD::SADDO:
3329     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3330     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3331     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3332     break;
3333   case ISD::UADDO:
3334     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3335     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3336     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3337     break;
3338   case ISD::SSUBO:
3339     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3340     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3341     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3342     break;
3343   case ISD::USUBO:
3344     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3345     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3346     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3347     break;
3348   } // switch (...)
3349
3350   return std::make_pair(Value, OverflowCmp);
3351 }
3352
3353
3354 SDValue
3355 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3356   // Let legalize expand this if it isn't a legal type yet.
3357   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3358     return SDValue();
3359
3360   SDValue Value, OverflowCmp;
3361   SDValue ARMcc;
3362   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3363   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3364   SDLoc dl(Op);
3365   // We use 0 and 1 as false and true values.
3366   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3367   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3368   EVT VT = Op.getValueType();
3369
3370   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3371                                  ARMcc, CCR, OverflowCmp);
3372
3373   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3374   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3375 }
3376
3377
3378 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3379   SDValue Cond = Op.getOperand(0);
3380   SDValue SelectTrue = Op.getOperand(1);
3381   SDValue SelectFalse = Op.getOperand(2);
3382   SDLoc dl(Op);
3383   unsigned Opc = Cond.getOpcode();
3384
3385   if (Cond.getResNo() == 1 &&
3386       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3387        Opc == ISD::USUBO)) {
3388     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3389       return SDValue();
3390
3391     SDValue Value, OverflowCmp;
3392     SDValue ARMcc;
3393     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3394     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3395     EVT VT = Op.getValueType();
3396
3397     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3398                    OverflowCmp, DAG);
3399   }
3400
3401   // Convert:
3402   //
3403   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3404   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3405   //
3406   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3407     const ConstantSDNode *CMOVTrue =
3408       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3409     const ConstantSDNode *CMOVFalse =
3410       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3411
3412     if (CMOVTrue && CMOVFalse) {
3413       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3414       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3415
3416       SDValue True;
3417       SDValue False;
3418       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3419         True = SelectTrue;
3420         False = SelectFalse;
3421       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3422         True = SelectFalse;
3423         False = SelectTrue;
3424       }
3425
3426       if (True.getNode() && False.getNode()) {
3427         EVT VT = Op.getValueType();
3428         SDValue ARMcc = Cond.getOperand(2);
3429         SDValue CCR = Cond.getOperand(3);
3430         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3431         assert(True.getValueType() == VT);
3432         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3433       }
3434     }
3435   }
3436
3437   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3438   // undefined bits before doing a full-word comparison with zero.
3439   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3440                      DAG.getConstant(1, dl, Cond.getValueType()));
3441
3442   return DAG.getSelectCC(dl, Cond,
3443                          DAG.getConstant(0, dl, Cond.getValueType()),
3444                          SelectTrue, SelectFalse, ISD::SETNE);
3445 }
3446
3447 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3448                                  bool &swpCmpOps, bool &swpVselOps) {
3449   // Start by selecting the GE condition code for opcodes that return true for
3450   // 'equality'
3451   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3452       CC == ISD::SETULE)
3453     CondCode = ARMCC::GE;
3454
3455   // and GT for opcodes that return false for 'equality'.
3456   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3457            CC == ISD::SETULT)
3458     CondCode = ARMCC::GT;
3459
3460   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3461   // to swap the compare operands.
3462   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3463       CC == ISD::SETULT)
3464     swpCmpOps = true;
3465
3466   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3467   // If we have an unordered opcode, we need to swap the operands to the VSEL
3468   // instruction (effectively negating the condition).
3469   //
3470   // This also has the effect of swapping which one of 'less' or 'greater'
3471   // returns true, so we also swap the compare operands. It also switches
3472   // whether we return true for 'equality', so we compensate by picking the
3473   // opposite condition code to our original choice.
3474   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3475       CC == ISD::SETUGT) {
3476     swpCmpOps = !swpCmpOps;
3477     swpVselOps = !swpVselOps;
3478     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3479   }
3480
3481   // 'ordered' is 'anything but unordered', so use the VS condition code and
3482   // swap the VSEL operands.
3483   if (CC == ISD::SETO) {
3484     CondCode = ARMCC::VS;
3485     swpVselOps = true;
3486   }
3487
3488   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3489   // code and swap the VSEL operands.
3490   if (CC == ISD::SETUNE) {
3491     CondCode = ARMCC::EQ;
3492     swpVselOps = true;
3493   }
3494 }
3495
3496 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3497                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3498                                    SDValue Cmp, SelectionDAG &DAG) const {
3499   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3500     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3501                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3502     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3503                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3504
3505     SDValue TrueLow = TrueVal.getValue(0);
3506     SDValue TrueHigh = TrueVal.getValue(1);
3507     SDValue FalseLow = FalseVal.getValue(0);
3508     SDValue FalseHigh = FalseVal.getValue(1);
3509
3510     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3511                               ARMcc, CCR, Cmp);
3512     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3513                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3514
3515     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3516   } else {
3517     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3518                        Cmp);
3519   }
3520 }
3521
3522 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3523   EVT VT = Op.getValueType();
3524   SDValue LHS = Op.getOperand(0);
3525   SDValue RHS = Op.getOperand(1);
3526   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3527   SDValue TrueVal = Op.getOperand(2);
3528   SDValue FalseVal = Op.getOperand(3);
3529   SDLoc dl(Op);
3530
3531   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3532     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3533                                                     dl);
3534
3535     // If softenSetCCOperands only returned one value, we should compare it to
3536     // zero.
3537     if (!RHS.getNode()) {
3538       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3539       CC = ISD::SETNE;
3540     }
3541   }
3542
3543   if (LHS.getValueType() == MVT::i32) {
3544     // Try to generate VSEL on ARMv8.
3545     // The VSEL instruction can't use all the usual ARM condition
3546     // codes: it only has two bits to select the condition code, so it's
3547     // constrained to use only GE, GT, VS and EQ.
3548     //
3549     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3550     // swap the operands of the previous compare instruction (effectively
3551     // inverting the compare condition, swapping 'less' and 'greater') and
3552     // sometimes need to swap the operands to the VSEL (which inverts the
3553     // condition in the sense of firing whenever the previous condition didn't)
3554     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3555                                     TrueVal.getValueType() == MVT::f64)) {
3556       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3557       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3558           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3559         CC = ISD::getSetCCInverse(CC, true);
3560         std::swap(TrueVal, FalseVal);
3561       }
3562     }
3563
3564     SDValue ARMcc;
3565     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3566     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3567     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3568   }
3569
3570   ARMCC::CondCodes CondCode, CondCode2;
3571   FPCCToARMCC(CC, CondCode, CondCode2);
3572
3573   // Try to generate VMAXNM/VMINNM on ARMv8.
3574   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3575                                   TrueVal.getValueType() == MVT::f64)) {
3576     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3577     // same operands, as follows:
3578     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3579     //   select c, a, b
3580     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3581     bool swapSides = false;
3582     if (!getTargetMachine().Options.NoNaNsFPMath) {
3583       // transformability may depend on which way around we compare
3584       switch (CC) {
3585       default:
3586         break;
3587       case ISD::SETOGT:
3588       case ISD::SETOGE:
3589       case ISD::SETOLT:
3590       case ISD::SETOLE:
3591         // the non-NaN should be RHS
3592         swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3593         break;
3594       case ISD::SETUGT:
3595       case ISD::SETUGE:
3596       case ISD::SETULT:
3597       case ISD::SETULE:
3598         // the non-NaN should be LHS
3599         swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3600         break;
3601       }
3602     }
3603     swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3604     if (swapSides) {
3605       CC = ISD::getSetCCSwappedOperands(CC);
3606       std::swap(LHS, RHS);
3607     }
3608     if (LHS == TrueVal && RHS == FalseVal) {
3609       bool canTransform = true;
3610       // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3611       if (!getTargetMachine().Options.UnsafeFPMath &&
3612           !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3613         const ConstantFPSDNode *Zero;
3614         switch (CC) {
3615         default:
3616           break;
3617         case ISD::SETOGT:
3618         case ISD::SETUGT:
3619         case ISD::SETGT:
3620           // RHS must not be -0
3621           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3622                          !Zero->isNegative();
3623           break;
3624         case ISD::SETOGE:
3625         case ISD::SETUGE:
3626         case ISD::SETGE:
3627           // LHS must not be -0
3628           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3629                          !Zero->isNegative();
3630           break;
3631         case ISD::SETOLT:
3632         case ISD::SETULT:
3633         case ISD::SETLT:
3634           // RHS must not be +0
3635           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3636                           Zero->isNegative();
3637           break;
3638         case ISD::SETOLE:
3639         case ISD::SETULE:
3640         case ISD::SETLE:
3641           // LHS must not be +0
3642           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3643                           Zero->isNegative();
3644           break;
3645         }
3646       }
3647       if (canTransform) {
3648         // Note: If one of the elements in a pair is a number and the other
3649         // element is NaN, the corresponding result element is the number.
3650         // This is consistent with the IEEE 754-2008 standard.
3651         // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3652         switch (CC) {
3653         default:
3654           break;
3655         case ISD::SETOGT:
3656         case ISD::SETOGE:
3657           if (!DAG.isKnownNeverNaN(RHS))
3658             break;
3659           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3660         case ISD::SETUGT:
3661         case ISD::SETUGE:
3662           if (!DAG.isKnownNeverNaN(LHS))
3663             break;
3664         case ISD::SETGT:
3665         case ISD::SETGE:
3666           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3667         case ISD::SETOLT:
3668         case ISD::SETOLE:
3669           if (!DAG.isKnownNeverNaN(RHS))
3670             break;
3671           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3672         case ISD::SETULT:
3673         case ISD::SETULE:
3674           if (!DAG.isKnownNeverNaN(LHS))
3675             break;
3676         case ISD::SETLT:
3677         case ISD::SETLE:
3678           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3679         }
3680       }
3681     }
3682
3683     bool swpCmpOps = false;
3684     bool swpVselOps = false;
3685     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3686
3687     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3688         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3689       if (swpCmpOps)
3690         std::swap(LHS, RHS);
3691       if (swpVselOps)
3692         std::swap(TrueVal, FalseVal);
3693     }
3694   }
3695
3696   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3697   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3698   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3699   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3700   if (CondCode2 != ARMCC::AL) {
3701     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3702     // FIXME: Needs another CMP because flag can have but one use.
3703     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3704     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3705   }
3706   return Result;
3707 }
3708
3709 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3710 /// to morph to an integer compare sequence.
3711 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3712                            const ARMSubtarget *Subtarget) {
3713   SDNode *N = Op.getNode();
3714   if (!N->hasOneUse())
3715     // Otherwise it requires moving the value from fp to integer registers.
3716     return false;
3717   if (!N->getNumValues())
3718     return false;
3719   EVT VT = Op.getValueType();
3720   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3721     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3722     // vmrs are very slow, e.g. cortex-a8.
3723     return false;
3724
3725   if (isFloatingPointZero(Op)) {
3726     SeenZero = true;
3727     return true;
3728   }
3729   return ISD::isNormalLoad(N);
3730 }
3731
3732 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3733   if (isFloatingPointZero(Op))
3734     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3735
3736   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3737     return DAG.getLoad(MVT::i32, SDLoc(Op),
3738                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3739                        Ld->isVolatile(), Ld->isNonTemporal(),
3740                        Ld->isInvariant(), Ld->getAlignment());
3741
3742   llvm_unreachable("Unknown VFP cmp argument!");
3743 }
3744
3745 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3746                            SDValue &RetVal1, SDValue &RetVal2) {
3747   SDLoc dl(Op);
3748
3749   if (isFloatingPointZero(Op)) {
3750     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3751     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3752     return;
3753   }
3754
3755   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3756     SDValue Ptr = Ld->getBasePtr();
3757     RetVal1 = DAG.getLoad(MVT::i32, dl,
3758                           Ld->getChain(), Ptr,
3759                           Ld->getPointerInfo(),
3760                           Ld->isVolatile(), Ld->isNonTemporal(),
3761                           Ld->isInvariant(), Ld->getAlignment());
3762
3763     EVT PtrType = Ptr.getValueType();
3764     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3765     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3766                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3767     RetVal2 = DAG.getLoad(MVT::i32, dl,
3768                           Ld->getChain(), NewPtr,
3769                           Ld->getPointerInfo().getWithOffset(4),
3770                           Ld->isVolatile(), Ld->isNonTemporal(),
3771                           Ld->isInvariant(), NewAlign);
3772     return;
3773   }
3774
3775   llvm_unreachable("Unknown VFP cmp argument!");
3776 }
3777
3778 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3779 /// f32 and even f64 comparisons to integer ones.
3780 SDValue
3781 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3782   SDValue Chain = Op.getOperand(0);
3783   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3784   SDValue LHS = Op.getOperand(2);
3785   SDValue RHS = Op.getOperand(3);
3786   SDValue Dest = Op.getOperand(4);
3787   SDLoc dl(Op);
3788
3789   bool LHSSeenZero = false;
3790   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3791   bool RHSSeenZero = false;
3792   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3793   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3794     // If unsafe fp math optimization is enabled and there are no other uses of
3795     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3796     // to an integer comparison.
3797     if (CC == ISD::SETOEQ)
3798       CC = ISD::SETEQ;
3799     else if (CC == ISD::SETUNE)
3800       CC = ISD::SETNE;
3801
3802     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3803     SDValue ARMcc;
3804     if (LHS.getValueType() == MVT::f32) {
3805       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3806                         bitcastf32Toi32(LHS, DAG), Mask);
3807       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3808                         bitcastf32Toi32(RHS, DAG), Mask);
3809       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3810       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3811       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3812                          Chain, Dest, ARMcc, CCR, Cmp);
3813     }
3814
3815     SDValue LHS1, LHS2;
3816     SDValue RHS1, RHS2;
3817     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3818     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3819     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3820     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3821     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3822     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3823     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3824     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3825     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3826   }
3827
3828   return SDValue();
3829 }
3830
3831 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3832   SDValue Chain = Op.getOperand(0);
3833   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3834   SDValue LHS = Op.getOperand(2);
3835   SDValue RHS = Op.getOperand(3);
3836   SDValue Dest = Op.getOperand(4);
3837   SDLoc dl(Op);
3838
3839   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3840     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3841                                                     dl);
3842
3843     // If softenSetCCOperands only returned one value, we should compare it to
3844     // zero.
3845     if (!RHS.getNode()) {
3846       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3847       CC = ISD::SETNE;
3848     }
3849   }
3850
3851   if (LHS.getValueType() == MVT::i32) {
3852     SDValue ARMcc;
3853     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3854     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3855     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3856                        Chain, Dest, ARMcc, CCR, Cmp);
3857   }
3858
3859   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3860
3861   if (getTargetMachine().Options.UnsafeFPMath &&
3862       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3863        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3864     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3865     if (Result.getNode())
3866       return Result;
3867   }
3868
3869   ARMCC::CondCodes CondCode, CondCode2;
3870   FPCCToARMCC(CC, CondCode, CondCode2);
3871
3872   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3873   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3874   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3875   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3876   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3877   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3878   if (CondCode2 != ARMCC::AL) {
3879     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3880     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3881     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3882   }
3883   return Res;
3884 }
3885
3886 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3887   SDValue Chain = Op.getOperand(0);
3888   SDValue Table = Op.getOperand(1);
3889   SDValue Index = Op.getOperand(2);
3890   SDLoc dl(Op);
3891
3892   EVT PTy = getPointerTy(DAG.getDataLayout());
3893   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3894   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3895   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3896   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3897   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3898   if (Subtarget->isThumb2()) {
3899     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3900     // which does another jump to the destination. This also makes it easier
3901     // to translate it to TBB / TBH later.
3902     // FIXME: This might not work if the function is extremely large.
3903     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3904                        Addr, Op.getOperand(2), JTI);
3905   }
3906   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3907     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3908                        MachinePointerInfo::getJumpTable(),
3909                        false, false, false, 0);
3910     Chain = Addr.getValue(1);
3911     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3912     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3913   } else {
3914     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3915                        MachinePointerInfo::getJumpTable(),
3916                        false, false, false, 0);
3917     Chain = Addr.getValue(1);
3918     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3919   }
3920 }
3921
3922 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3923   EVT VT = Op.getValueType();
3924   SDLoc dl(Op);
3925
3926   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3927     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3928       return Op;
3929     return DAG.UnrollVectorOp(Op.getNode());
3930   }
3931
3932   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3933          "Invalid type for custom lowering!");
3934   if (VT != MVT::v4i16)
3935     return DAG.UnrollVectorOp(Op.getNode());
3936
3937   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3938   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3939 }
3940
3941 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3942   EVT VT = Op.getValueType();
3943   if (VT.isVector())
3944     return LowerVectorFP_TO_INT(Op, DAG);
3945   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3946     RTLIB::Libcall LC;
3947     if (Op.getOpcode() == ISD::FP_TO_SINT)
3948       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3949                               Op.getValueType());
3950     else
3951       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3952                               Op.getValueType());
3953     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3954                        /*isSigned*/ false, SDLoc(Op)).first;
3955   }
3956
3957   return Op;
3958 }
3959
3960 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3961   EVT VT = Op.getValueType();
3962   SDLoc dl(Op);
3963
3964   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3965     if (VT.getVectorElementType() == MVT::f32)
3966       return Op;
3967     return DAG.UnrollVectorOp(Op.getNode());
3968   }
3969
3970   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3971          "Invalid type for custom lowering!");
3972   if (VT != MVT::v4f32)
3973     return DAG.UnrollVectorOp(Op.getNode());
3974
3975   unsigned CastOpc;
3976   unsigned Opc;
3977   switch (Op.getOpcode()) {
3978   default: llvm_unreachable("Invalid opcode!");
3979   case ISD::SINT_TO_FP:
3980     CastOpc = ISD::SIGN_EXTEND;
3981     Opc = ISD::SINT_TO_FP;
3982     break;
3983   case ISD::UINT_TO_FP:
3984     CastOpc = ISD::ZERO_EXTEND;
3985     Opc = ISD::UINT_TO_FP;
3986     break;
3987   }
3988
3989   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3990   return DAG.getNode(Opc, dl, VT, Op);
3991 }
3992
3993 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3994   EVT VT = Op.getValueType();
3995   if (VT.isVector())
3996     return LowerVectorINT_TO_FP(Op, DAG);
3997   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3998     RTLIB::Libcall LC;
3999     if (Op.getOpcode() == ISD::SINT_TO_FP)
4000       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4001                               Op.getValueType());
4002     else
4003       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4004                               Op.getValueType());
4005     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
4006                        /*isSigned*/ false, SDLoc(Op)).first;
4007   }
4008
4009   return Op;
4010 }
4011
4012 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4013   // Implement fcopysign with a fabs and a conditional fneg.
4014   SDValue Tmp0 = Op.getOperand(0);
4015   SDValue Tmp1 = Op.getOperand(1);
4016   SDLoc dl(Op);
4017   EVT VT = Op.getValueType();
4018   EVT SrcVT = Tmp1.getValueType();
4019   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4020     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4021   bool UseNEON = !InGPR && Subtarget->hasNEON();
4022
4023   if (UseNEON) {
4024     // Use VBSL to copy the sign bit.
4025     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4026     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4027                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4028     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4029     if (VT == MVT::f64)
4030       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4031                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4032                          DAG.getConstant(32, dl, MVT::i32));
4033     else /*if (VT == MVT::f32)*/
4034       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4035     if (SrcVT == MVT::f32) {
4036       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4037       if (VT == MVT::f64)
4038         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4039                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4040                            DAG.getConstant(32, dl, MVT::i32));
4041     } else if (VT == MVT::f32)
4042       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4043                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4044                          DAG.getConstant(32, dl, MVT::i32));
4045     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4046     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4047
4048     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4049                                             dl, MVT::i32);
4050     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4051     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4052                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4053
4054     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4055                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4056                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4057     if (VT == MVT::f32) {
4058       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4059       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4060                         DAG.getConstant(0, dl, MVT::i32));
4061     } else {
4062       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4063     }
4064
4065     return Res;
4066   }
4067
4068   // Bitcast operand 1 to i32.
4069   if (SrcVT == MVT::f64)
4070     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4071                        Tmp1).getValue(1);
4072   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4073
4074   // Or in the signbit with integer operations.
4075   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4076   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4077   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4078   if (VT == MVT::f32) {
4079     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4080                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4081     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4082                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4083   }
4084
4085   // f64: Or the high part with signbit and then combine two parts.
4086   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4087                      Tmp0);
4088   SDValue Lo = Tmp0.getValue(0);
4089   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4090   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4091   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4092 }
4093
4094 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4095   MachineFunction &MF = DAG.getMachineFunction();
4096   MachineFrameInfo *MFI = MF.getFrameInfo();
4097   MFI->setReturnAddressIsTaken(true);
4098
4099   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4100     return SDValue();
4101
4102   EVT VT = Op.getValueType();
4103   SDLoc dl(Op);
4104   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4105   if (Depth) {
4106     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4107     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4108     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4109                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4110                        MachinePointerInfo(), false, false, false, 0);
4111   }
4112
4113   // Return LR, which contains the return address. Mark it an implicit live-in.
4114   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4115   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4116 }
4117
4118 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4119   const ARMBaseRegisterInfo &ARI =
4120     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4121   MachineFunction &MF = DAG.getMachineFunction();
4122   MachineFrameInfo *MFI = MF.getFrameInfo();
4123   MFI->setFrameAddressIsTaken(true);
4124
4125   EVT VT = Op.getValueType();
4126   SDLoc dl(Op);  // FIXME probably not meaningful
4127   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4128   unsigned FrameReg = ARI.getFrameRegister(MF);
4129   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4130   while (Depth--)
4131     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4132                             MachinePointerInfo(),
4133                             false, false, false, 0);
4134   return FrameAddr;
4135 }
4136
4137 // FIXME? Maybe this could be a TableGen attribute on some registers and
4138 // this table could be generated automatically from RegInfo.
4139 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4140                                               SelectionDAG &DAG) const {
4141   unsigned Reg = StringSwitch<unsigned>(RegName)
4142                        .Case("sp", ARM::SP)
4143                        .Default(0);
4144   if (Reg)
4145     return Reg;
4146   report_fatal_error(Twine("Invalid register name \""
4147                               + StringRef(RegName)  + "\"."));
4148 }
4149
4150 // Result is 64 bit value so split into two 32 bit values and return as a
4151 // pair of values.
4152 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4153                                 SelectionDAG &DAG) {
4154   SDLoc DL(N);
4155
4156   // This function is only supposed to be called for i64 type destination.
4157   assert(N->getValueType(0) == MVT::i64
4158           && "ExpandREAD_REGISTER called for non-i64 type result.");
4159
4160   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4161                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4162                              N->getOperand(0),
4163                              N->getOperand(1));
4164
4165   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4166                     Read.getValue(1)));
4167   Results.push_back(Read.getOperand(0));
4168 }
4169
4170 /// ExpandBITCAST - If the target supports VFP, this function is called to
4171 /// expand a bit convert where either the source or destination type is i64 to
4172 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4173 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4174 /// vectors), since the legalizer won't know what to do with that.
4175 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4176   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4177   SDLoc dl(N);
4178   SDValue Op = N->getOperand(0);
4179
4180   // This function is only supposed to be called for i64 types, either as the
4181   // source or destination of the bit convert.
4182   EVT SrcVT = Op.getValueType();
4183   EVT DstVT = N->getValueType(0);
4184   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4185          "ExpandBITCAST called for non-i64 type");
4186
4187   // Turn i64->f64 into VMOVDRR.
4188   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4189     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4190                              DAG.getConstant(0, dl, MVT::i32));
4191     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4192                              DAG.getConstant(1, dl, MVT::i32));
4193     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4194                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4195   }
4196
4197   // Turn f64->i64 into VMOVRRD.
4198   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4199     SDValue Cvt;
4200     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4201         SrcVT.getVectorNumElements() > 1)
4202       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4203                         DAG.getVTList(MVT::i32, MVT::i32),
4204                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4205     else
4206       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4207                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4208     // Merge the pieces into a single i64 value.
4209     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4210   }
4211
4212   return SDValue();
4213 }
4214
4215 /// getZeroVector - Returns a vector of specified type with all zero elements.
4216 /// Zero vectors are used to represent vector negation and in those cases
4217 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4218 /// not support i64 elements, so sometimes the zero vectors will need to be
4219 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4220 /// zero vector.
4221 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4222   assert(VT.isVector() && "Expected a vector type");
4223   // The canonical modified immediate encoding of a zero vector is....0!
4224   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4225   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4226   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4227   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4228 }
4229
4230 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4231 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4232 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4233                                                 SelectionDAG &DAG) const {
4234   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4235   EVT VT = Op.getValueType();
4236   unsigned VTBits = VT.getSizeInBits();
4237   SDLoc dl(Op);
4238   SDValue ShOpLo = Op.getOperand(0);
4239   SDValue ShOpHi = Op.getOperand(1);
4240   SDValue ShAmt  = Op.getOperand(2);
4241   SDValue ARMcc;
4242   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4243
4244   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4245
4246   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4247                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4248   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4249   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4250                                    DAG.getConstant(VTBits, dl, MVT::i32));
4251   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4252   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4253   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4254
4255   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4256   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4257                           ISD::SETGE, ARMcc, DAG, dl);
4258   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4259   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4260                            CCR, Cmp);
4261
4262   SDValue Ops[2] = { Lo, Hi };
4263   return DAG.getMergeValues(Ops, dl);
4264 }
4265
4266 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4267 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4268 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4269                                                SelectionDAG &DAG) const {
4270   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4271   EVT VT = Op.getValueType();
4272   unsigned VTBits = VT.getSizeInBits();
4273   SDLoc dl(Op);
4274   SDValue ShOpLo = Op.getOperand(0);
4275   SDValue ShOpHi = Op.getOperand(1);
4276   SDValue ShAmt  = Op.getOperand(2);
4277   SDValue ARMcc;
4278
4279   assert(Op.getOpcode() == ISD::SHL_PARTS);
4280   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4281                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4282   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4283   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4284                                    DAG.getConstant(VTBits, dl, MVT::i32));
4285   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4286   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4287
4288   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4289   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4290   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4291                           ISD::SETGE, ARMcc, DAG, dl);
4292   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4293   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4294                            CCR, Cmp);
4295
4296   SDValue Ops[2] = { Lo, Hi };
4297   return DAG.getMergeValues(Ops, dl);
4298 }
4299
4300 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4301                                             SelectionDAG &DAG) const {
4302   // The rounding mode is in bits 23:22 of the FPSCR.
4303   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4304   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4305   // so that the shift + and get folded into a bitfield extract.
4306   SDLoc dl(Op);
4307   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4308                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4309                                               MVT::i32));
4310   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4311                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4312   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4313                               DAG.getConstant(22, dl, MVT::i32));
4314   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4315                      DAG.getConstant(3, dl, MVT::i32));
4316 }
4317
4318 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4319                          const ARMSubtarget *ST) {
4320   SDLoc dl(N);
4321   EVT VT = N->getValueType(0);
4322   if (VT.isVector()) {
4323     assert(ST->hasNEON());
4324
4325     // Compute the least significant set bit: LSB = X & -X
4326     SDValue X = N->getOperand(0);
4327     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4328     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4329
4330     EVT ElemTy = VT.getVectorElementType();
4331
4332     if (ElemTy == MVT::i8) {
4333       // Compute with: cttz(x) = ctpop(lsb - 1)
4334       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4335                                 DAG.getTargetConstant(1, dl, ElemTy));
4336       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4337       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4338     }
4339
4340     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4341         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4342       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4343       unsigned NumBits = ElemTy.getSizeInBits();
4344       SDValue WidthMinus1 =
4345           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4346                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4347       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4348       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4349     }
4350
4351     // Compute with: cttz(x) = ctpop(lsb - 1)
4352
4353     // Since we can only compute the number of bits in a byte with vcnt.8, we
4354     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4355     // and i64.
4356
4357     // Compute LSB - 1.
4358     SDValue Bits;
4359     if (ElemTy == MVT::i64) {
4360       // Load constant 0xffff'ffff'ffff'ffff to register.
4361       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4362                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4363       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4364     } else {
4365       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4366                                 DAG.getTargetConstant(1, dl, ElemTy));
4367       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4368     }
4369
4370     // Count #bits with vcnt.8.
4371     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4372     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4373     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4374
4375     // Gather the #bits with vpaddl (pairwise add.)
4376     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4377     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4378         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4379         Cnt8);
4380     if (ElemTy == MVT::i16)
4381       return Cnt16;
4382
4383     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4384     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4385         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4386         Cnt16);
4387     if (ElemTy == MVT::i32)
4388       return Cnt32;
4389
4390     assert(ElemTy == MVT::i64);
4391     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4392         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4393         Cnt32);
4394     return Cnt64;
4395   }
4396
4397   if (!ST->hasV6T2Ops())
4398     return SDValue();
4399
4400   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4401   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4402 }
4403
4404 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4405 /// for each 16-bit element from operand, repeated.  The basic idea is to
4406 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4407 ///
4408 /// Trace for v4i16:
4409 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4410 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4411 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4412 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4413 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4414 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4415 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4416 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4417 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4418   EVT VT = N->getValueType(0);
4419   SDLoc DL(N);
4420
4421   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4422   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4423   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4424   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4425   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4426   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4427 }
4428
4429 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4430 /// bit-count for each 16-bit element from the operand.  We need slightly
4431 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4432 /// 64/128-bit registers.
4433 ///
4434 /// Trace for v4i16:
4435 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4436 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4437 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4438 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4439 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4440   EVT VT = N->getValueType(0);
4441   SDLoc DL(N);
4442
4443   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4444   if (VT.is64BitVector()) {
4445     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4446     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4447                        DAG.getIntPtrConstant(0, DL));
4448   } else {
4449     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4450                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4451     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4452   }
4453 }
4454
4455 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4456 /// bit-count for each 32-bit element from the operand.  The idea here is
4457 /// to split the vector into 16-bit elements, leverage the 16-bit count
4458 /// routine, and then combine the results.
4459 ///
4460 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4461 /// input    = [v0    v1    ] (vi: 32-bit elements)
4462 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4463 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4464 /// vrev: N0 = [k1 k0 k3 k2 ]
4465 ///            [k0 k1 k2 k3 ]
4466 ///       N1 =+[k1 k0 k3 k2 ]
4467 ///            [k0 k2 k1 k3 ]
4468 ///       N2 =+[k1 k3 k0 k2 ]
4469 ///            [k0    k2    k1    k3    ]
4470 /// Extended =+[k1    k3    k0    k2    ]
4471 ///            [k0    k2    ]
4472 /// Extracted=+[k1    k3    ]
4473 ///
4474 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4475   EVT VT = N->getValueType(0);
4476   SDLoc DL(N);
4477
4478   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4479
4480   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4481   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4482   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4483   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4484   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4485
4486   if (VT.is64BitVector()) {
4487     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4488     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4489                        DAG.getIntPtrConstant(0, DL));
4490   } else {
4491     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4492                                     DAG.getIntPtrConstant(0, DL));
4493     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4494   }
4495 }
4496
4497 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4498                           const ARMSubtarget *ST) {
4499   EVT VT = N->getValueType(0);
4500
4501   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4502   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4503           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4504          "Unexpected type for custom ctpop lowering");
4505
4506   if (VT.getVectorElementType() == MVT::i32)
4507     return lowerCTPOP32BitElements(N, DAG);
4508   else
4509     return lowerCTPOP16BitElements(N, DAG);
4510 }
4511
4512 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4513                           const ARMSubtarget *ST) {
4514   EVT VT = N->getValueType(0);
4515   SDLoc dl(N);
4516
4517   if (!VT.isVector())
4518     return SDValue();
4519
4520   // Lower vector shifts on NEON to use VSHL.
4521   assert(ST->hasNEON() && "unexpected vector shift");
4522
4523   // Left shifts translate directly to the vshiftu intrinsic.
4524   if (N->getOpcode() == ISD::SHL)
4525     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4526                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4527                                        MVT::i32),
4528                        N->getOperand(0), N->getOperand(1));
4529
4530   assert((N->getOpcode() == ISD::SRA ||
4531           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4532
4533   // NEON uses the same intrinsics for both left and right shifts.  For
4534   // right shifts, the shift amounts are negative, so negate the vector of
4535   // shift amounts.
4536   EVT ShiftVT = N->getOperand(1).getValueType();
4537   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4538                                      getZeroVector(ShiftVT, DAG, dl),
4539                                      N->getOperand(1));
4540   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4541                              Intrinsic::arm_neon_vshifts :
4542                              Intrinsic::arm_neon_vshiftu);
4543   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4544                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4545                      N->getOperand(0), NegatedCount);
4546 }
4547
4548 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4549                                 const ARMSubtarget *ST) {
4550   EVT VT = N->getValueType(0);
4551   SDLoc dl(N);
4552
4553   // We can get here for a node like i32 = ISD::SHL i32, i64
4554   if (VT != MVT::i64)
4555     return SDValue();
4556
4557   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4558          "Unknown shift to lower!");
4559
4560   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4561   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4562       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4563     return SDValue();
4564
4565   // If we are in thumb mode, we don't have RRX.
4566   if (ST->isThumb1Only()) return SDValue();
4567
4568   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4569   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4570                            DAG.getConstant(0, dl, MVT::i32));
4571   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4572                            DAG.getConstant(1, dl, MVT::i32));
4573
4574   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4575   // captures the result into a carry flag.
4576   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4577   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4578
4579   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4580   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4581
4582   // Merge the pieces into a single i64 value.
4583  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4584 }
4585
4586 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4587   SDValue TmpOp0, TmpOp1;
4588   bool Invert = false;
4589   bool Swap = false;
4590   unsigned Opc = 0;
4591
4592   SDValue Op0 = Op.getOperand(0);
4593   SDValue Op1 = Op.getOperand(1);
4594   SDValue CC = Op.getOperand(2);
4595   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4596   EVT VT = Op.getValueType();
4597   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4598   SDLoc dl(Op);
4599
4600   if (Op1.getValueType().isFloatingPoint()) {
4601     switch (SetCCOpcode) {
4602     default: llvm_unreachable("Illegal FP comparison");
4603     case ISD::SETUNE:
4604     case ISD::SETNE:  Invert = true; // Fallthrough
4605     case ISD::SETOEQ:
4606     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4607     case ISD::SETOLT:
4608     case ISD::SETLT: Swap = true; // Fallthrough
4609     case ISD::SETOGT:
4610     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4611     case ISD::SETOLE:
4612     case ISD::SETLE:  Swap = true; // Fallthrough
4613     case ISD::SETOGE:
4614     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4615     case ISD::SETUGE: Swap = true; // Fallthrough
4616     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4617     case ISD::SETUGT: Swap = true; // Fallthrough
4618     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4619     case ISD::SETUEQ: Invert = true; // Fallthrough
4620     case ISD::SETONE:
4621       // Expand this to (OLT | OGT).
4622       TmpOp0 = Op0;
4623       TmpOp1 = Op1;
4624       Opc = ISD::OR;
4625       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4626       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4627       break;
4628     case ISD::SETUO: Invert = true; // Fallthrough
4629     case ISD::SETO:
4630       // Expand this to (OLT | OGE).
4631       TmpOp0 = Op0;
4632       TmpOp1 = Op1;
4633       Opc = ISD::OR;
4634       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4635       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4636       break;
4637     }
4638   } else {
4639     // Integer comparisons.
4640     switch (SetCCOpcode) {
4641     default: llvm_unreachable("Illegal integer comparison");
4642     case ISD::SETNE:  Invert = true;
4643     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4644     case ISD::SETLT:  Swap = true;
4645     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4646     case ISD::SETLE:  Swap = true;
4647     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4648     case ISD::SETULT: Swap = true;
4649     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4650     case ISD::SETULE: Swap = true;
4651     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4652     }
4653
4654     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4655     if (Opc == ARMISD::VCEQ) {
4656
4657       SDValue AndOp;
4658       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4659         AndOp = Op0;
4660       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4661         AndOp = Op1;
4662
4663       // Ignore bitconvert.
4664       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4665         AndOp = AndOp.getOperand(0);
4666
4667       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4668         Opc = ARMISD::VTST;
4669         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4670         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4671         Invert = !Invert;
4672       }
4673     }
4674   }
4675
4676   if (Swap)
4677     std::swap(Op0, Op1);
4678
4679   // If one of the operands is a constant vector zero, attempt to fold the
4680   // comparison to a specialized compare-against-zero form.
4681   SDValue SingleOp;
4682   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4683     SingleOp = Op0;
4684   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4685     if (Opc == ARMISD::VCGE)
4686       Opc = ARMISD::VCLEZ;
4687     else if (Opc == ARMISD::VCGT)
4688       Opc = ARMISD::VCLTZ;
4689     SingleOp = Op1;
4690   }
4691
4692   SDValue Result;
4693   if (SingleOp.getNode()) {
4694     switch (Opc) {
4695     case ARMISD::VCEQ:
4696       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4697     case ARMISD::VCGE:
4698       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4699     case ARMISD::VCLEZ:
4700       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4701     case ARMISD::VCGT:
4702       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4703     case ARMISD::VCLTZ:
4704       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4705     default:
4706       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4707     }
4708   } else {
4709      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4710   }
4711
4712   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4713
4714   if (Invert)
4715     Result = DAG.getNOT(dl, Result, VT);
4716
4717   return Result;
4718 }
4719
4720 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4721 /// valid vector constant for a NEON instruction with a "modified immediate"
4722 /// operand (e.g., VMOV).  If so, return the encoded value.
4723 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4724                                  unsigned SplatBitSize, SelectionDAG &DAG,
4725                                  SDLoc dl, EVT &VT, bool is128Bits,
4726                                  NEONModImmType type) {
4727   unsigned OpCmode, Imm;
4728
4729   // SplatBitSize is set to the smallest size that splats the vector, so a
4730   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4731   // immediate instructions others than VMOV do not support the 8-bit encoding
4732   // of a zero vector, and the default encoding of zero is supposed to be the
4733   // 32-bit version.
4734   if (SplatBits == 0)
4735     SplatBitSize = 32;
4736
4737   switch (SplatBitSize) {
4738   case 8:
4739     if (type != VMOVModImm)
4740       return SDValue();
4741     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4742     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4743     OpCmode = 0xe;
4744     Imm = SplatBits;
4745     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4746     break;
4747
4748   case 16:
4749     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4750     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4751     if ((SplatBits & ~0xff) == 0) {
4752       // Value = 0x00nn: Op=x, Cmode=100x.
4753       OpCmode = 0x8;
4754       Imm = SplatBits;
4755       break;
4756     }
4757     if ((SplatBits & ~0xff00) == 0) {
4758       // Value = 0xnn00: Op=x, Cmode=101x.
4759       OpCmode = 0xa;
4760       Imm = SplatBits >> 8;
4761       break;
4762     }
4763     return SDValue();
4764
4765   case 32:
4766     // NEON's 32-bit VMOV supports splat values where:
4767     // * only one byte is nonzero, or
4768     // * the least significant byte is 0xff and the second byte is nonzero, or
4769     // * the least significant 2 bytes are 0xff and the third is nonzero.
4770     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4771     if ((SplatBits & ~0xff) == 0) {
4772       // Value = 0x000000nn: Op=x, Cmode=000x.
4773       OpCmode = 0;
4774       Imm = SplatBits;
4775       break;
4776     }
4777     if ((SplatBits & ~0xff00) == 0) {
4778       // Value = 0x0000nn00: Op=x, Cmode=001x.
4779       OpCmode = 0x2;
4780       Imm = SplatBits >> 8;
4781       break;
4782     }
4783     if ((SplatBits & ~0xff0000) == 0) {
4784       // Value = 0x00nn0000: Op=x, Cmode=010x.
4785       OpCmode = 0x4;
4786       Imm = SplatBits >> 16;
4787       break;
4788     }
4789     if ((SplatBits & ~0xff000000) == 0) {
4790       // Value = 0xnn000000: Op=x, Cmode=011x.
4791       OpCmode = 0x6;
4792       Imm = SplatBits >> 24;
4793       break;
4794     }
4795
4796     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4797     if (type == OtherModImm) return SDValue();
4798
4799     if ((SplatBits & ~0xffff) == 0 &&
4800         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4801       // Value = 0x0000nnff: Op=x, Cmode=1100.
4802       OpCmode = 0xc;
4803       Imm = SplatBits >> 8;
4804       break;
4805     }
4806
4807     if ((SplatBits & ~0xffffff) == 0 &&
4808         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4809       // Value = 0x00nnffff: Op=x, Cmode=1101.
4810       OpCmode = 0xd;
4811       Imm = SplatBits >> 16;
4812       break;
4813     }
4814
4815     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4816     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4817     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4818     // and fall through here to test for a valid 64-bit splat.  But, then the
4819     // caller would also need to check and handle the change in size.
4820     return SDValue();
4821
4822   case 64: {
4823     if (type != VMOVModImm)
4824       return SDValue();
4825     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4826     uint64_t BitMask = 0xff;
4827     uint64_t Val = 0;
4828     unsigned ImmMask = 1;
4829     Imm = 0;
4830     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4831       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4832         Val |= BitMask;
4833         Imm |= ImmMask;
4834       } else if ((SplatBits & BitMask) != 0) {
4835         return SDValue();
4836       }
4837       BitMask <<= 8;
4838       ImmMask <<= 1;
4839     }
4840
4841     if (DAG.getDataLayout().isBigEndian())
4842       // swap higher and lower 32 bit word
4843       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4844
4845     // Op=1, Cmode=1110.
4846     OpCmode = 0x1e;
4847     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4848     break;
4849   }
4850
4851   default:
4852     llvm_unreachable("unexpected size for isNEONModifiedImm");
4853   }
4854
4855   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4856   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4857 }
4858
4859 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4860                                            const ARMSubtarget *ST) const {
4861   if (!ST->hasVFP3())
4862     return SDValue();
4863
4864   bool IsDouble = Op.getValueType() == MVT::f64;
4865   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4866
4867   // Use the default (constant pool) lowering for double constants when we have
4868   // an SP-only FPU
4869   if (IsDouble && Subtarget->isFPOnlySP())
4870     return SDValue();
4871
4872   // Try splatting with a VMOV.f32...
4873   APFloat FPVal = CFP->getValueAPF();
4874   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4875
4876   if (ImmVal != -1) {
4877     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4878       // We have code in place to select a valid ConstantFP already, no need to
4879       // do any mangling.
4880       return Op;
4881     }
4882
4883     // It's a float and we are trying to use NEON operations where
4884     // possible. Lower it to a splat followed by an extract.
4885     SDLoc DL(Op);
4886     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4887     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4888                                       NewVal);
4889     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4890                        DAG.getConstant(0, DL, MVT::i32));
4891   }
4892
4893   // The rest of our options are NEON only, make sure that's allowed before
4894   // proceeding..
4895   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4896     return SDValue();
4897
4898   EVT VMovVT;
4899   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4900
4901   // It wouldn't really be worth bothering for doubles except for one very
4902   // important value, which does happen to match: 0.0. So make sure we don't do
4903   // anything stupid.
4904   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4905     return SDValue();
4906
4907   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4908   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4909                                      VMovVT, false, VMOVModImm);
4910   if (NewVal != SDValue()) {
4911     SDLoc DL(Op);
4912     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4913                                       NewVal);
4914     if (IsDouble)
4915       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4916
4917     // It's a float: cast and extract a vector element.
4918     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4919                                        VecConstant);
4920     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4921                        DAG.getConstant(0, DL, MVT::i32));
4922   }
4923
4924   // Finally, try a VMVN.i32
4925   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4926                              false, VMVNModImm);
4927   if (NewVal != SDValue()) {
4928     SDLoc DL(Op);
4929     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4930
4931     if (IsDouble)
4932       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4933
4934     // It's a float: cast and extract a vector element.
4935     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4936                                        VecConstant);
4937     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4938                        DAG.getConstant(0, DL, MVT::i32));
4939   }
4940
4941   return SDValue();
4942 }
4943
4944 // check if an VEXT instruction can handle the shuffle mask when the
4945 // vector sources of the shuffle are the same.
4946 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4947   unsigned NumElts = VT.getVectorNumElements();
4948
4949   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4950   if (M[0] < 0)
4951     return false;
4952
4953   Imm = M[0];
4954
4955   // If this is a VEXT shuffle, the immediate value is the index of the first
4956   // element.  The other shuffle indices must be the successive elements after
4957   // the first one.
4958   unsigned ExpectedElt = Imm;
4959   for (unsigned i = 1; i < NumElts; ++i) {
4960     // Increment the expected index.  If it wraps around, just follow it
4961     // back to index zero and keep going.
4962     ++ExpectedElt;
4963     if (ExpectedElt == NumElts)
4964       ExpectedElt = 0;
4965
4966     if (M[i] < 0) continue; // ignore UNDEF indices
4967     if (ExpectedElt != static_cast<unsigned>(M[i]))
4968       return false;
4969   }
4970
4971   return true;
4972 }
4973
4974
4975 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4976                        bool &ReverseVEXT, unsigned &Imm) {
4977   unsigned NumElts = VT.getVectorNumElements();
4978   ReverseVEXT = false;
4979
4980   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4981   if (M[0] < 0)
4982     return false;
4983
4984   Imm = M[0];
4985
4986   // If this is a VEXT shuffle, the immediate value is the index of the first
4987   // element.  The other shuffle indices must be the successive elements after
4988   // the first one.
4989   unsigned ExpectedElt = Imm;
4990   for (unsigned i = 1; i < NumElts; ++i) {
4991     // Increment the expected index.  If it wraps around, it may still be
4992     // a VEXT but the source vectors must be swapped.
4993     ExpectedElt += 1;
4994     if (ExpectedElt == NumElts * 2) {
4995       ExpectedElt = 0;
4996       ReverseVEXT = true;
4997     }
4998
4999     if (M[i] < 0) continue; // ignore UNDEF indices
5000     if (ExpectedElt != static_cast<unsigned>(M[i]))
5001       return false;
5002   }
5003
5004   // Adjust the index value if the source operands will be swapped.
5005   if (ReverseVEXT)
5006     Imm -= NumElts;
5007
5008   return true;
5009 }
5010
5011 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5012 /// instruction with the specified blocksize.  (The order of the elements
5013 /// within each block of the vector is reversed.)
5014 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5015   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5016          "Only possible block sizes for VREV are: 16, 32, 64");
5017
5018   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5019   if (EltSz == 64)
5020     return false;
5021
5022   unsigned NumElts = VT.getVectorNumElements();
5023   unsigned BlockElts = M[0] + 1;
5024   // If the first shuffle index is UNDEF, be optimistic.
5025   if (M[0] < 0)
5026     BlockElts = BlockSize / EltSz;
5027
5028   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5029     return false;
5030
5031   for (unsigned i = 0; i < NumElts; ++i) {
5032     if (M[i] < 0) continue; // ignore UNDEF indices
5033     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5034       return false;
5035   }
5036
5037   return true;
5038 }
5039
5040 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5041   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5042   // range, then 0 is placed into the resulting vector. So pretty much any mask
5043   // of 8 elements can work here.
5044   return VT == MVT::v8i8 && M.size() == 8;
5045 }
5046
5047 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5048 // checking that pairs of elements in the shuffle mask represent the same index
5049 // in each vector, incrementing the expected index by 2 at each step.
5050 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5051 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5052 //  v2={e,f,g,h}
5053 // WhichResult gives the offset for each element in the mask based on which
5054 // of the two results it belongs to.
5055 //
5056 // The transpose can be represented either as:
5057 // result1 = shufflevector v1, v2, result1_shuffle_mask
5058 // result2 = shufflevector v1, v2, result2_shuffle_mask
5059 // where v1/v2 and the shuffle masks have the same number of elements
5060 // (here WhichResult (see below) indicates which result is being checked)
5061 //
5062 // or as:
5063 // results = shufflevector v1, v2, shuffle_mask
5064 // where both results are returned in one vector and the shuffle mask has twice
5065 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5066 // want to check the low half and high half of the shuffle mask as if it were
5067 // the other case
5068 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5069   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5070   if (EltSz == 64)
5071     return false;
5072
5073   unsigned NumElts = VT.getVectorNumElements();
5074   if (M.size() != NumElts && M.size() != NumElts*2)
5075     return false;
5076
5077   // If the mask is twice as long as the result then we need to check the upper
5078   // and lower parts of the mask
5079   for (unsigned i = 0; i < M.size(); i += NumElts) {
5080     WhichResult = M[i] == 0 ? 0 : 1;
5081     for (unsigned j = 0; j < NumElts; j += 2) {
5082       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5083           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5084         return false;
5085     }
5086   }
5087
5088   if (M.size() == NumElts*2)
5089     WhichResult = 0;
5090
5091   return true;
5092 }
5093
5094 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5095 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5096 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5097 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5098   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5099   if (EltSz == 64)
5100     return false;
5101
5102   unsigned NumElts = VT.getVectorNumElements();
5103   if (M.size() != NumElts && M.size() != NumElts*2)
5104     return false;
5105
5106   for (unsigned i = 0; i < M.size(); i += NumElts) {
5107     WhichResult = M[i] == 0 ? 0 : 1;
5108     for (unsigned j = 0; j < NumElts; j += 2) {
5109       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5110           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5111         return false;
5112     }
5113   }
5114
5115   if (M.size() == NumElts*2)
5116     WhichResult = 0;
5117
5118   return true;
5119 }
5120
5121 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5122 // that the mask elements are either all even and in steps of size 2 or all odd
5123 // and in steps of size 2.
5124 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5125 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5126 //  v2={e,f,g,h}
5127 // Requires similar checks to that of isVTRNMask with
5128 // respect the how results are returned.
5129 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5130   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5131   if (EltSz == 64)
5132     return false;
5133
5134   unsigned NumElts = VT.getVectorNumElements();
5135   if (M.size() != NumElts && M.size() != NumElts*2)
5136     return false;
5137
5138   for (unsigned i = 0; i < M.size(); i += NumElts) {
5139     WhichResult = M[i] == 0 ? 0 : 1;
5140     for (unsigned j = 0; j < NumElts; ++j) {
5141       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5142         return false;
5143     }
5144   }
5145
5146   if (M.size() == NumElts*2)
5147     WhichResult = 0;
5148
5149   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5150   if (VT.is64BitVector() && EltSz == 32)
5151     return false;
5152
5153   return true;
5154 }
5155
5156 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5157 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5158 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5159 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5160   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5161   if (EltSz == 64)
5162     return false;
5163
5164   unsigned NumElts = VT.getVectorNumElements();
5165   if (M.size() != NumElts && M.size() != NumElts*2)
5166     return false;
5167
5168   unsigned Half = NumElts / 2;
5169   for (unsigned i = 0; i < M.size(); i += NumElts) {
5170     WhichResult = M[i] == 0 ? 0 : 1;
5171     for (unsigned j = 0; j < NumElts; j += Half) {
5172       unsigned Idx = WhichResult;
5173       for (unsigned k = 0; k < Half; ++k) {
5174         int MIdx = M[i + j + k];
5175         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5176           return false;
5177         Idx += 2;
5178       }
5179     }
5180   }
5181
5182   if (M.size() == NumElts*2)
5183     WhichResult = 0;
5184
5185   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5186   if (VT.is64BitVector() && EltSz == 32)
5187     return false;
5188
5189   return true;
5190 }
5191
5192 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5193 // that pairs of elements of the shufflemask represent the same index in each
5194 // vector incrementing sequentially through the vectors.
5195 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5196 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5197 //  v2={e,f,g,h}
5198 // Requires similar checks to that of isVTRNMask with respect the how results
5199 // are returned.
5200 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5201   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5202   if (EltSz == 64)
5203     return false;
5204
5205   unsigned NumElts = VT.getVectorNumElements();
5206   if (M.size() != NumElts && M.size() != NumElts*2)
5207     return false;
5208
5209   for (unsigned i = 0; i < M.size(); i += NumElts) {
5210     WhichResult = M[i] == 0 ? 0 : 1;
5211     unsigned Idx = WhichResult * NumElts / 2;
5212     for (unsigned j = 0; j < NumElts; j += 2) {
5213       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5214           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5215         return false;
5216       Idx += 1;
5217     }
5218   }
5219
5220   if (M.size() == NumElts*2)
5221     WhichResult = 0;
5222
5223   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5224   if (VT.is64BitVector() && EltSz == 32)
5225     return false;
5226
5227   return true;
5228 }
5229
5230 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5231 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5232 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5233 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5234   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5235   if (EltSz == 64)
5236     return false;
5237
5238   unsigned NumElts = VT.getVectorNumElements();
5239   if (M.size() != NumElts && M.size() != NumElts*2)
5240     return false;
5241
5242   for (unsigned i = 0; i < M.size(); i += NumElts) {
5243     WhichResult = M[i] == 0 ? 0 : 1;
5244     unsigned Idx = WhichResult * NumElts / 2;
5245     for (unsigned j = 0; j < NumElts; j += 2) {
5246       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5247           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5248         return false;
5249       Idx += 1;
5250     }
5251   }
5252
5253   if (M.size() == NumElts*2)
5254     WhichResult = 0;
5255
5256   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5257   if (VT.is64BitVector() && EltSz == 32)
5258     return false;
5259
5260   return true;
5261 }
5262
5263 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5264 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5265 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5266                                            unsigned &WhichResult,
5267                                            bool &isV_UNDEF) {
5268   isV_UNDEF = false;
5269   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5270     return ARMISD::VTRN;
5271   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5272     return ARMISD::VUZP;
5273   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5274     return ARMISD::VZIP;
5275
5276   isV_UNDEF = true;
5277   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5278     return ARMISD::VTRN;
5279   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5280     return ARMISD::VUZP;
5281   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5282     return ARMISD::VZIP;
5283
5284   return 0;
5285 }
5286
5287 /// \return true if this is a reverse operation on an vector.
5288 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5289   unsigned NumElts = VT.getVectorNumElements();
5290   // Make sure the mask has the right size.
5291   if (NumElts != M.size())
5292       return false;
5293
5294   // Look for <15, ..., 3, -1, 1, 0>.
5295   for (unsigned i = 0; i != NumElts; ++i)
5296     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5297       return false;
5298
5299   return true;
5300 }
5301
5302 // If N is an integer constant that can be moved into a register in one
5303 // instruction, return an SDValue of such a constant (will become a MOV
5304 // instruction).  Otherwise return null.
5305 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5306                                      const ARMSubtarget *ST, SDLoc dl) {
5307   uint64_t Val;
5308   if (!isa<ConstantSDNode>(N))
5309     return SDValue();
5310   Val = cast<ConstantSDNode>(N)->getZExtValue();
5311
5312   if (ST->isThumb1Only()) {
5313     if (Val <= 255 || ~Val <= 255)
5314       return DAG.getConstant(Val, dl, MVT::i32);
5315   } else {
5316     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5317       return DAG.getConstant(Val, dl, MVT::i32);
5318   }
5319   return SDValue();
5320 }
5321
5322 // If this is a case we can't handle, return null and let the default
5323 // expansion code take care of it.
5324 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5325                                              const ARMSubtarget *ST) const {
5326   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5327   SDLoc dl(Op);
5328   EVT VT = Op.getValueType();
5329
5330   APInt SplatBits, SplatUndef;
5331   unsigned SplatBitSize;
5332   bool HasAnyUndefs;
5333   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5334     if (SplatBitSize <= 64) {
5335       // Check if an immediate VMOV works.
5336       EVT VmovVT;
5337       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5338                                       SplatUndef.getZExtValue(), SplatBitSize,
5339                                       DAG, dl, VmovVT, VT.is128BitVector(),
5340                                       VMOVModImm);
5341       if (Val.getNode()) {
5342         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5343         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5344       }
5345
5346       // Try an immediate VMVN.
5347       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5348       Val = isNEONModifiedImm(NegatedImm,
5349                                       SplatUndef.getZExtValue(), SplatBitSize,
5350                                       DAG, dl, VmovVT, VT.is128BitVector(),
5351                                       VMVNModImm);
5352       if (Val.getNode()) {
5353         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5354         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5355       }
5356
5357       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5358       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5359         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5360         if (ImmVal != -1) {
5361           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5362           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5363         }
5364       }
5365     }
5366   }
5367
5368   // Scan through the operands to see if only one value is used.
5369   //
5370   // As an optimisation, even if more than one value is used it may be more
5371   // profitable to splat with one value then change some lanes.
5372   //
5373   // Heuristically we decide to do this if the vector has a "dominant" value,
5374   // defined as splatted to more than half of the lanes.
5375   unsigned NumElts = VT.getVectorNumElements();
5376   bool isOnlyLowElement = true;
5377   bool usesOnlyOneValue = true;
5378   bool hasDominantValue = false;
5379   bool isConstant = true;
5380
5381   // Map of the number of times a particular SDValue appears in the
5382   // element list.
5383   DenseMap<SDValue, unsigned> ValueCounts;
5384   SDValue Value;
5385   for (unsigned i = 0; i < NumElts; ++i) {
5386     SDValue V = Op.getOperand(i);
5387     if (V.getOpcode() == ISD::UNDEF)
5388       continue;
5389     if (i > 0)
5390       isOnlyLowElement = false;
5391     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5392       isConstant = false;
5393
5394     ValueCounts.insert(std::make_pair(V, 0));
5395     unsigned &Count = ValueCounts[V];
5396
5397     // Is this value dominant? (takes up more than half of the lanes)
5398     if (++Count > (NumElts / 2)) {
5399       hasDominantValue = true;
5400       Value = V;
5401     }
5402   }
5403   if (ValueCounts.size() != 1)
5404     usesOnlyOneValue = false;
5405   if (!Value.getNode() && ValueCounts.size() > 0)
5406     Value = ValueCounts.begin()->first;
5407
5408   if (ValueCounts.size() == 0)
5409     return DAG.getUNDEF(VT);
5410
5411   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5412   // Keep going if we are hitting this case.
5413   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5414     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5415
5416   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5417
5418   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5419   // i32 and try again.
5420   if (hasDominantValue && EltSize <= 32) {
5421     if (!isConstant) {
5422       SDValue N;
5423
5424       // If we are VDUPing a value that comes directly from a vector, that will
5425       // cause an unnecessary move to and from a GPR, where instead we could
5426       // just use VDUPLANE. We can only do this if the lane being extracted
5427       // is at a constant index, as the VDUP from lane instructions only have
5428       // constant-index forms.
5429       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5430           isa<ConstantSDNode>(Value->getOperand(1))) {
5431         // We need to create a new undef vector to use for the VDUPLANE if the
5432         // size of the vector from which we get the value is different than the
5433         // size of the vector that we need to create. We will insert the element
5434         // such that the register coalescer will remove unnecessary copies.
5435         if (VT != Value->getOperand(0).getValueType()) {
5436           ConstantSDNode *constIndex;
5437           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5438           assert(constIndex && "The index is not a constant!");
5439           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5440                              VT.getVectorNumElements();
5441           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5442                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5443                         Value, DAG.getConstant(index, dl, MVT::i32)),
5444                            DAG.getConstant(index, dl, MVT::i32));
5445         } else
5446           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5447                         Value->getOperand(0), Value->getOperand(1));
5448       } else
5449         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5450
5451       if (!usesOnlyOneValue) {
5452         // The dominant value was splatted as 'N', but we now have to insert
5453         // all differing elements.
5454         for (unsigned I = 0; I < NumElts; ++I) {
5455           if (Op.getOperand(I) == Value)
5456             continue;
5457           SmallVector<SDValue, 3> Ops;
5458           Ops.push_back(N);
5459           Ops.push_back(Op.getOperand(I));
5460           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5461           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5462         }
5463       }
5464       return N;
5465     }
5466     if (VT.getVectorElementType().isFloatingPoint()) {
5467       SmallVector<SDValue, 8> Ops;
5468       for (unsigned i = 0; i < NumElts; ++i)
5469         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5470                                   Op.getOperand(i)));
5471       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5472       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5473       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5474       if (Val.getNode())
5475         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5476     }
5477     if (usesOnlyOneValue) {
5478       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5479       if (isConstant && Val.getNode())
5480         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5481     }
5482   }
5483
5484   // If all elements are constants and the case above didn't get hit, fall back
5485   // to the default expansion, which will generate a load from the constant
5486   // pool.
5487   if (isConstant)
5488     return SDValue();
5489
5490   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5491   if (NumElts >= 4) {
5492     SDValue shuffle = ReconstructShuffle(Op, DAG);
5493     if (shuffle != SDValue())
5494       return shuffle;
5495   }
5496
5497   // Vectors with 32- or 64-bit elements can be built by directly assigning
5498   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5499   // will be legalized.
5500   if (EltSize >= 32) {
5501     // Do the expansion with floating-point types, since that is what the VFP
5502     // registers are defined to use, and since i64 is not legal.
5503     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5504     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5505     SmallVector<SDValue, 8> Ops;
5506     for (unsigned i = 0; i < NumElts; ++i)
5507       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5508     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5509     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5510   }
5511
5512   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5513   // know the default expansion would otherwise fall back on something even
5514   // worse. For a vector with one or two non-undef values, that's
5515   // scalar_to_vector for the elements followed by a shuffle (provided the
5516   // shuffle is valid for the target) and materialization element by element
5517   // on the stack followed by a load for everything else.
5518   if (!isConstant && !usesOnlyOneValue) {
5519     SDValue Vec = DAG.getUNDEF(VT);
5520     for (unsigned i = 0 ; i < NumElts; ++i) {
5521       SDValue V = Op.getOperand(i);
5522       if (V.getOpcode() == ISD::UNDEF)
5523         continue;
5524       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5525       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5526     }
5527     return Vec;
5528   }
5529
5530   return SDValue();
5531 }
5532
5533 // Gather data to see if the operation can be modelled as a
5534 // shuffle in combination with VEXTs.
5535 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5536                                               SelectionDAG &DAG) const {
5537   SDLoc dl(Op);
5538   EVT VT = Op.getValueType();
5539   unsigned NumElts = VT.getVectorNumElements();
5540
5541   SmallVector<SDValue, 2> SourceVecs;
5542   SmallVector<unsigned, 2> MinElts;
5543   SmallVector<unsigned, 2> MaxElts;
5544
5545   for (unsigned i = 0; i < NumElts; ++i) {
5546     SDValue V = Op.getOperand(i);
5547     if (V.getOpcode() == ISD::UNDEF)
5548       continue;
5549     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5550       // A shuffle can only come from building a vector from various
5551       // elements of other vectors.
5552       return SDValue();
5553     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5554                VT.getVectorElementType()) {
5555       // This code doesn't know how to handle shuffles where the vector
5556       // element types do not match (this happens because type legalization
5557       // promotes the return type of EXTRACT_VECTOR_ELT).
5558       // FIXME: It might be appropriate to extend this code to handle
5559       // mismatched types.
5560       return SDValue();
5561     }
5562
5563     // Record this extraction against the appropriate vector if possible...
5564     SDValue SourceVec = V.getOperand(0);
5565     // If the element number isn't a constant, we can't effectively
5566     // analyze what's going on.
5567     if (!isa<ConstantSDNode>(V.getOperand(1)))
5568       return SDValue();
5569     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5570     bool FoundSource = false;
5571     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5572       if (SourceVecs[j] == SourceVec) {
5573         if (MinElts[j] > EltNo)
5574           MinElts[j] = EltNo;
5575         if (MaxElts[j] < EltNo)
5576           MaxElts[j] = EltNo;
5577         FoundSource = true;
5578         break;
5579       }
5580     }
5581
5582     // Or record a new source if not...
5583     if (!FoundSource) {
5584       SourceVecs.push_back(SourceVec);
5585       MinElts.push_back(EltNo);
5586       MaxElts.push_back(EltNo);
5587     }
5588   }
5589
5590   // Currently only do something sane when at most two source vectors
5591   // involved.
5592   if (SourceVecs.size() > 2)
5593     return SDValue();
5594
5595   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5596   int VEXTOffsets[2] = {0, 0};
5597
5598   // This loop extracts the usage patterns of the source vectors
5599   // and prepares appropriate SDValues for a shuffle if possible.
5600   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5601     if (SourceVecs[i].getValueType() == VT) {
5602       // No VEXT necessary
5603       ShuffleSrcs[i] = SourceVecs[i];
5604       VEXTOffsets[i] = 0;
5605       continue;
5606     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5607       // It probably isn't worth padding out a smaller vector just to
5608       // break it down again in a shuffle.
5609       return SDValue();
5610     }
5611
5612     // Since only 64-bit and 128-bit vectors are legal on ARM and
5613     // we've eliminated the other cases...
5614     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5615            "unexpected vector sizes in ReconstructShuffle");
5616
5617     if (MaxElts[i] - MinElts[i] >= NumElts) {
5618       // Span too large for a VEXT to cope
5619       return SDValue();
5620     }
5621
5622     if (MinElts[i] >= NumElts) {
5623       // The extraction can just take the second half
5624       VEXTOffsets[i] = NumElts;
5625       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5626                                    SourceVecs[i],
5627                                    DAG.getIntPtrConstant(NumElts, dl));
5628     } else if (MaxElts[i] < NumElts) {
5629       // The extraction can just take the first half
5630       VEXTOffsets[i] = 0;
5631       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5632                                    SourceVecs[i],
5633                                    DAG.getIntPtrConstant(0, dl));
5634     } else {
5635       // An actual VEXT is needed
5636       VEXTOffsets[i] = MinElts[i];
5637       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5638                                      SourceVecs[i],
5639                                      DAG.getIntPtrConstant(0, dl));
5640       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5641                                      SourceVecs[i],
5642                                      DAG.getIntPtrConstant(NumElts, dl));
5643       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5644                                    DAG.getConstant(VEXTOffsets[i], dl,
5645                                                    MVT::i32));
5646     }
5647   }
5648
5649   SmallVector<int, 8> Mask;
5650
5651   for (unsigned i = 0; i < NumElts; ++i) {
5652     SDValue Entry = Op.getOperand(i);
5653     if (Entry.getOpcode() == ISD::UNDEF) {
5654       Mask.push_back(-1);
5655       continue;
5656     }
5657
5658     SDValue ExtractVec = Entry.getOperand(0);
5659     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5660                                           .getOperand(1))->getSExtValue();
5661     if (ExtractVec == SourceVecs[0]) {
5662       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5663     } else {
5664       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5665     }
5666   }
5667
5668   // Final check before we try to produce nonsense...
5669   if (isShuffleMaskLegal(Mask, VT))
5670     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5671                                 &Mask[0]);
5672
5673   return SDValue();
5674 }
5675
5676 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5677 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5678 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5679 /// are assumed to be legal.
5680 bool
5681 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5682                                       EVT VT) const {
5683   if (VT.getVectorNumElements() == 4 &&
5684       (VT.is128BitVector() || VT.is64BitVector())) {
5685     unsigned PFIndexes[4];
5686     for (unsigned i = 0; i != 4; ++i) {
5687       if (M[i] < 0)
5688         PFIndexes[i] = 8;
5689       else
5690         PFIndexes[i] = M[i];
5691     }
5692
5693     // Compute the index in the perfect shuffle table.
5694     unsigned PFTableIndex =
5695       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5696     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5697     unsigned Cost = (PFEntry >> 30);
5698
5699     if (Cost <= 4)
5700       return true;
5701   }
5702
5703   bool ReverseVEXT, isV_UNDEF;
5704   unsigned Imm, WhichResult;
5705
5706   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5707   return (EltSize >= 32 ||
5708           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5709           isVREVMask(M, VT, 64) ||
5710           isVREVMask(M, VT, 32) ||
5711           isVREVMask(M, VT, 16) ||
5712           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5713           isVTBLMask(M, VT) ||
5714           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5715           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5716 }
5717
5718 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5719 /// the specified operations to build the shuffle.
5720 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5721                                       SDValue RHS, SelectionDAG &DAG,
5722                                       SDLoc dl) {
5723   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5724   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5725   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5726
5727   enum {
5728     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5729     OP_VREV,
5730     OP_VDUP0,
5731     OP_VDUP1,
5732     OP_VDUP2,
5733     OP_VDUP3,
5734     OP_VEXT1,
5735     OP_VEXT2,
5736     OP_VEXT3,
5737     OP_VUZPL, // VUZP, left result
5738     OP_VUZPR, // VUZP, right result
5739     OP_VZIPL, // VZIP, left result
5740     OP_VZIPR, // VZIP, right result
5741     OP_VTRNL, // VTRN, left result
5742     OP_VTRNR  // VTRN, right result
5743   };
5744
5745   if (OpNum == OP_COPY) {
5746     if (LHSID == (1*9+2)*9+3) return LHS;
5747     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5748     return RHS;
5749   }
5750
5751   SDValue OpLHS, OpRHS;
5752   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5753   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5754   EVT VT = OpLHS.getValueType();
5755
5756   switch (OpNum) {
5757   default: llvm_unreachable("Unknown shuffle opcode!");
5758   case OP_VREV:
5759     // VREV divides the vector in half and swaps within the half.
5760     if (VT.getVectorElementType() == MVT::i32 ||
5761         VT.getVectorElementType() == MVT::f32)
5762       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5763     // vrev <4 x i16> -> VREV32
5764     if (VT.getVectorElementType() == MVT::i16)
5765       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5766     // vrev <4 x i8> -> VREV16
5767     assert(VT.getVectorElementType() == MVT::i8);
5768     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5769   case OP_VDUP0:
5770   case OP_VDUP1:
5771   case OP_VDUP2:
5772   case OP_VDUP3:
5773     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5774                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5775   case OP_VEXT1:
5776   case OP_VEXT2:
5777   case OP_VEXT3:
5778     return DAG.getNode(ARMISD::VEXT, dl, VT,
5779                        OpLHS, OpRHS,
5780                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5781   case OP_VUZPL:
5782   case OP_VUZPR:
5783     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5784                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5785   case OP_VZIPL:
5786   case OP_VZIPR:
5787     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5788                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5789   case OP_VTRNL:
5790   case OP_VTRNR:
5791     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5792                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5793   }
5794 }
5795
5796 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5797                                        ArrayRef<int> ShuffleMask,
5798                                        SelectionDAG &DAG) {
5799   // Check to see if we can use the VTBL instruction.
5800   SDValue V1 = Op.getOperand(0);
5801   SDValue V2 = Op.getOperand(1);
5802   SDLoc DL(Op);
5803
5804   SmallVector<SDValue, 8> VTBLMask;
5805   for (ArrayRef<int>::iterator
5806          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5807     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5808
5809   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5810     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5811                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5812
5813   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5814                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5815 }
5816
5817 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5818                                                       SelectionDAG &DAG) {
5819   SDLoc DL(Op);
5820   SDValue OpLHS = Op.getOperand(0);
5821   EVT VT = OpLHS.getValueType();
5822
5823   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5824          "Expect an v8i16/v16i8 type");
5825   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5826   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5827   // extract the first 8 bytes into the top double word and the last 8 bytes
5828   // into the bottom double word. The v8i16 case is similar.
5829   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5830   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5831                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5832 }
5833
5834 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5835   SDValue V1 = Op.getOperand(0);
5836   SDValue V2 = Op.getOperand(1);
5837   SDLoc dl(Op);
5838   EVT VT = Op.getValueType();
5839   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5840
5841   // Convert shuffles that are directly supported on NEON to target-specific
5842   // DAG nodes, instead of keeping them as shuffles and matching them again
5843   // during code selection.  This is more efficient and avoids the possibility
5844   // of inconsistencies between legalization and selection.
5845   // FIXME: floating-point vectors should be canonicalized to integer vectors
5846   // of the same time so that they get CSEd properly.
5847   ArrayRef<int> ShuffleMask = SVN->getMask();
5848
5849   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5850   if (EltSize <= 32) {
5851     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5852       int Lane = SVN->getSplatIndex();
5853       // If this is undef splat, generate it via "just" vdup, if possible.
5854       if (Lane == -1) Lane = 0;
5855
5856       // Test if V1 is a SCALAR_TO_VECTOR.
5857       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5858         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5859       }
5860       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5861       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5862       // reaches it).
5863       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5864           !isa<ConstantSDNode>(V1.getOperand(0))) {
5865         bool IsScalarToVector = true;
5866         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5867           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5868             IsScalarToVector = false;
5869             break;
5870           }
5871         if (IsScalarToVector)
5872           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5873       }
5874       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5875                          DAG.getConstant(Lane, dl, MVT::i32));
5876     }
5877
5878     bool ReverseVEXT;
5879     unsigned Imm;
5880     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5881       if (ReverseVEXT)
5882         std::swap(V1, V2);
5883       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5884                          DAG.getConstant(Imm, dl, MVT::i32));
5885     }
5886
5887     if (isVREVMask(ShuffleMask, VT, 64))
5888       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5889     if (isVREVMask(ShuffleMask, VT, 32))
5890       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5891     if (isVREVMask(ShuffleMask, VT, 16))
5892       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5893
5894     if (V2->getOpcode() == ISD::UNDEF &&
5895         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5896       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5897                          DAG.getConstant(Imm, dl, MVT::i32));
5898     }
5899
5900     // Check for Neon shuffles that modify both input vectors in place.
5901     // If both results are used, i.e., if there are two shuffles with the same
5902     // source operands and with masks corresponding to both results of one of
5903     // these operations, DAG memoization will ensure that a single node is
5904     // used for both shuffles.
5905     unsigned WhichResult;
5906     bool isV_UNDEF;
5907     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5908             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5909       if (isV_UNDEF)
5910         V2 = V1;
5911       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5912           .getValue(WhichResult);
5913     }
5914
5915     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5916     // shuffles that produce a result larger than their operands with:
5917     //   shuffle(concat(v1, undef), concat(v2, undef))
5918     // ->
5919     //   shuffle(concat(v1, v2), undef)
5920     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5921     //
5922     // This is useful in the general case, but there are special cases where
5923     // native shuffles produce larger results: the two-result ops.
5924     //
5925     // Look through the concat when lowering them:
5926     //   shuffle(concat(v1, v2), undef)
5927     // ->
5928     //   concat(VZIP(v1, v2):0, :1)
5929     //
5930     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5931         V2->getOpcode() == ISD::UNDEF) {
5932       SDValue SubV1 = V1->getOperand(0);
5933       SDValue SubV2 = V1->getOperand(1);
5934       EVT SubVT = SubV1.getValueType();
5935
5936       // We expect these to have been canonicalized to -1.
5937       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5938         return i < (int)VT.getVectorNumElements();
5939       }) && "Unexpected shuffle index into UNDEF operand!");
5940
5941       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5942               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5943         if (isV_UNDEF)
5944           SubV2 = SubV1;
5945         assert((WhichResult == 0) &&
5946                "In-place shuffle of concat can only have one result!");
5947         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5948                                   SubV1, SubV2);
5949         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5950                            Res.getValue(1));
5951       }
5952     }
5953   }
5954
5955   // If the shuffle is not directly supported and it has 4 elements, use
5956   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5957   unsigned NumElts = VT.getVectorNumElements();
5958   if (NumElts == 4) {
5959     unsigned PFIndexes[4];
5960     for (unsigned i = 0; i != 4; ++i) {
5961       if (ShuffleMask[i] < 0)
5962         PFIndexes[i] = 8;
5963       else
5964         PFIndexes[i] = ShuffleMask[i];
5965     }
5966
5967     // Compute the index in the perfect shuffle table.
5968     unsigned PFTableIndex =
5969       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5970     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5971     unsigned Cost = (PFEntry >> 30);
5972
5973     if (Cost <= 4)
5974       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5975   }
5976
5977   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5978   if (EltSize >= 32) {
5979     // Do the expansion with floating-point types, since that is what the VFP
5980     // registers are defined to use, and since i64 is not legal.
5981     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5982     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5983     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5984     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5985     SmallVector<SDValue, 8> Ops;
5986     for (unsigned i = 0; i < NumElts; ++i) {
5987       if (ShuffleMask[i] < 0)
5988         Ops.push_back(DAG.getUNDEF(EltVT));
5989       else
5990         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5991                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5992                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5993                                                   dl, MVT::i32)));
5994     }
5995     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5996     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5997   }
5998
5999   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6000     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6001
6002   if (VT == MVT::v8i8) {
6003     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6004     if (NewOp.getNode())
6005       return NewOp;
6006   }
6007
6008   return SDValue();
6009 }
6010
6011 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6012   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6013   SDValue Lane = Op.getOperand(2);
6014   if (!isa<ConstantSDNode>(Lane))
6015     return SDValue();
6016
6017   return Op;
6018 }
6019
6020 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6021   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6022   SDValue Lane = Op.getOperand(1);
6023   if (!isa<ConstantSDNode>(Lane))
6024     return SDValue();
6025
6026   SDValue Vec = Op.getOperand(0);
6027   if (Op.getValueType() == MVT::i32 &&
6028       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6029     SDLoc dl(Op);
6030     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6031   }
6032
6033   return Op;
6034 }
6035
6036 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6037   // The only time a CONCAT_VECTORS operation can have legal types is when
6038   // two 64-bit vectors are concatenated to a 128-bit vector.
6039   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6040          "unexpected CONCAT_VECTORS");
6041   SDLoc dl(Op);
6042   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6043   SDValue Op0 = Op.getOperand(0);
6044   SDValue Op1 = Op.getOperand(1);
6045   if (Op0.getOpcode() != ISD::UNDEF)
6046     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6047                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6048                       DAG.getIntPtrConstant(0, dl));
6049   if (Op1.getOpcode() != ISD::UNDEF)
6050     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6051                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6052                       DAG.getIntPtrConstant(1, dl));
6053   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6054 }
6055
6056 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6057 /// element has been zero/sign-extended, depending on the isSigned parameter,
6058 /// from an integer type half its size.
6059 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6060                                    bool isSigned) {
6061   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6062   EVT VT = N->getValueType(0);
6063   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6064     SDNode *BVN = N->getOperand(0).getNode();
6065     if (BVN->getValueType(0) != MVT::v4i32 ||
6066         BVN->getOpcode() != ISD::BUILD_VECTOR)
6067       return false;
6068     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6069     unsigned HiElt = 1 - LoElt;
6070     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6071     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6072     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6073     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6074     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6075       return false;
6076     if (isSigned) {
6077       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6078           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6079         return true;
6080     } else {
6081       if (Hi0->isNullValue() && Hi1->isNullValue())
6082         return true;
6083     }
6084     return false;
6085   }
6086
6087   if (N->getOpcode() != ISD::BUILD_VECTOR)
6088     return false;
6089
6090   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6091     SDNode *Elt = N->getOperand(i).getNode();
6092     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6093       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6094       unsigned HalfSize = EltSize / 2;
6095       if (isSigned) {
6096         if (!isIntN(HalfSize, C->getSExtValue()))
6097           return false;
6098       } else {
6099         if (!isUIntN(HalfSize, C->getZExtValue()))
6100           return false;
6101       }
6102       continue;
6103     }
6104     return false;
6105   }
6106
6107   return true;
6108 }
6109
6110 /// isSignExtended - Check if a node is a vector value that is sign-extended
6111 /// or a constant BUILD_VECTOR with sign-extended elements.
6112 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6113   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6114     return true;
6115   if (isExtendedBUILD_VECTOR(N, DAG, true))
6116     return true;
6117   return false;
6118 }
6119
6120 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6121 /// or a constant BUILD_VECTOR with zero-extended elements.
6122 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6123   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6124     return true;
6125   if (isExtendedBUILD_VECTOR(N, DAG, false))
6126     return true;
6127   return false;
6128 }
6129
6130 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6131   if (OrigVT.getSizeInBits() >= 64)
6132     return OrigVT;
6133
6134   assert(OrigVT.isSimple() && "Expecting a simple value type");
6135
6136   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6137   switch (OrigSimpleTy) {
6138   default: llvm_unreachable("Unexpected Vector Type");
6139   case MVT::v2i8:
6140   case MVT::v2i16:
6141      return MVT::v2i32;
6142   case MVT::v4i8:
6143     return  MVT::v4i16;
6144   }
6145 }
6146
6147 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6148 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6149 /// We insert the required extension here to get the vector to fill a D register.
6150 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6151                                             const EVT &OrigTy,
6152                                             const EVT &ExtTy,
6153                                             unsigned ExtOpcode) {
6154   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6155   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6156   // 64-bits we need to insert a new extension so that it will be 64-bits.
6157   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6158   if (OrigTy.getSizeInBits() >= 64)
6159     return N;
6160
6161   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6162   EVT NewVT = getExtensionTo64Bits(OrigTy);
6163
6164   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6165 }
6166
6167 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6168 /// does not do any sign/zero extension. If the original vector is less
6169 /// than 64 bits, an appropriate extension will be added after the load to
6170 /// reach a total size of 64 bits. We have to add the extension separately
6171 /// because ARM does not have a sign/zero extending load for vectors.
6172 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6173   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6174
6175   // The load already has the right type.
6176   if (ExtendedTy == LD->getMemoryVT())
6177     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6178                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6179                 LD->isNonTemporal(), LD->isInvariant(),
6180                 LD->getAlignment());
6181
6182   // We need to create a zextload/sextload. We cannot just create a load
6183   // followed by a zext/zext node because LowerMUL is also run during normal
6184   // operation legalization where we can't create illegal types.
6185   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6186                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6187                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6188                         LD->isNonTemporal(), LD->getAlignment());
6189 }
6190
6191 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6192 /// extending load, or BUILD_VECTOR with extended elements, return the
6193 /// unextended value. The unextended vector should be 64 bits so that it can
6194 /// be used as an operand to a VMULL instruction. If the original vector size
6195 /// before extension is less than 64 bits we add a an extension to resize
6196 /// the vector to 64 bits.
6197 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6198   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6199     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6200                                         N->getOperand(0)->getValueType(0),
6201                                         N->getValueType(0),
6202                                         N->getOpcode());
6203
6204   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6205     return SkipLoadExtensionForVMULL(LD, DAG);
6206
6207   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6208   // have been legalized as a BITCAST from v4i32.
6209   if (N->getOpcode() == ISD::BITCAST) {
6210     SDNode *BVN = N->getOperand(0).getNode();
6211     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6212            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6213     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6214     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6215                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6216   }
6217   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6218   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6219   EVT VT = N->getValueType(0);
6220   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6221   unsigned NumElts = VT.getVectorNumElements();
6222   MVT TruncVT = MVT::getIntegerVT(EltSize);
6223   SmallVector<SDValue, 8> Ops;
6224   SDLoc dl(N);
6225   for (unsigned i = 0; i != NumElts; ++i) {
6226     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6227     const APInt &CInt = C->getAPIntValue();
6228     // Element types smaller than 32 bits are not legal, so use i32 elements.
6229     // The values are implicitly truncated so sext vs. zext doesn't matter.
6230     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6231   }
6232   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6233                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6234 }
6235
6236 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6237   unsigned Opcode = N->getOpcode();
6238   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6239     SDNode *N0 = N->getOperand(0).getNode();
6240     SDNode *N1 = N->getOperand(1).getNode();
6241     return N0->hasOneUse() && N1->hasOneUse() &&
6242       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6243   }
6244   return false;
6245 }
6246
6247 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6248   unsigned Opcode = N->getOpcode();
6249   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6250     SDNode *N0 = N->getOperand(0).getNode();
6251     SDNode *N1 = N->getOperand(1).getNode();
6252     return N0->hasOneUse() && N1->hasOneUse() &&
6253       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6254   }
6255   return false;
6256 }
6257
6258 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6259   // Multiplications are only custom-lowered for 128-bit vectors so that
6260   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6261   EVT VT = Op.getValueType();
6262   assert(VT.is128BitVector() && VT.isInteger() &&
6263          "unexpected type for custom-lowering ISD::MUL");
6264   SDNode *N0 = Op.getOperand(0).getNode();
6265   SDNode *N1 = Op.getOperand(1).getNode();
6266   unsigned NewOpc = 0;
6267   bool isMLA = false;
6268   bool isN0SExt = isSignExtended(N0, DAG);
6269   bool isN1SExt = isSignExtended(N1, DAG);
6270   if (isN0SExt && isN1SExt)
6271     NewOpc = ARMISD::VMULLs;
6272   else {
6273     bool isN0ZExt = isZeroExtended(N0, DAG);
6274     bool isN1ZExt = isZeroExtended(N1, DAG);
6275     if (isN0ZExt && isN1ZExt)
6276       NewOpc = ARMISD::VMULLu;
6277     else if (isN1SExt || isN1ZExt) {
6278       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6279       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6280       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6281         NewOpc = ARMISD::VMULLs;
6282         isMLA = true;
6283       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6284         NewOpc = ARMISD::VMULLu;
6285         isMLA = true;
6286       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6287         std::swap(N0, N1);
6288         NewOpc = ARMISD::VMULLu;
6289         isMLA = true;
6290       }
6291     }
6292
6293     if (!NewOpc) {
6294       if (VT == MVT::v2i64)
6295         // Fall through to expand this.  It is not legal.
6296         return SDValue();
6297       else
6298         // Other vector multiplications are legal.
6299         return Op;
6300     }
6301   }
6302
6303   // Legalize to a VMULL instruction.
6304   SDLoc DL(Op);
6305   SDValue Op0;
6306   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6307   if (!isMLA) {
6308     Op0 = SkipExtensionForVMULL(N0, DAG);
6309     assert(Op0.getValueType().is64BitVector() &&
6310            Op1.getValueType().is64BitVector() &&
6311            "unexpected types for extended operands to VMULL");
6312     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6313   }
6314
6315   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6316   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6317   //   vmull q0, d4, d6
6318   //   vmlal q0, d5, d6
6319   // is faster than
6320   //   vaddl q0, d4, d5
6321   //   vmovl q1, d6
6322   //   vmul  q0, q0, q1
6323   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6324   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6325   EVT Op1VT = Op1.getValueType();
6326   return DAG.getNode(N0->getOpcode(), DL, VT,
6327                      DAG.getNode(NewOpc, DL, VT,
6328                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6329                      DAG.getNode(NewOpc, DL, VT,
6330                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6331 }
6332
6333 static SDValue
6334 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6335   // Convert to float
6336   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6337   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6338   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6339   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6340   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6341   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6342   // Get reciprocal estimate.
6343   // float4 recip = vrecpeq_f32(yf);
6344   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6345                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6346                    Y);
6347   // Because char has a smaller range than uchar, we can actually get away
6348   // without any newton steps.  This requires that we use a weird bias
6349   // of 0xb000, however (again, this has been exhaustively tested).
6350   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6351   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6352   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6353   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6354   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6355   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6356   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6357   // Convert back to short.
6358   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6359   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6360   return X;
6361 }
6362
6363 static SDValue
6364 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6365   SDValue N2;
6366   // Convert to float.
6367   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6368   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6369   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6370   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6371   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6372   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6373
6374   // Use reciprocal estimate and one refinement step.
6375   // float4 recip = vrecpeq_f32(yf);
6376   // recip *= vrecpsq_f32(yf, recip);
6377   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6378                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6379                    N1);
6380   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6381                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6382                    N1, N2);
6383   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6384   // Because short has a smaller range than ushort, we can actually get away
6385   // with only a single newton step.  This requires that we use a weird bias
6386   // of 89, however (again, this has been exhaustively tested).
6387   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6388   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6389   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6390   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6391   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6392   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6393   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6394   // Convert back to integer and return.
6395   // return vmovn_s32(vcvt_s32_f32(result));
6396   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6397   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6398   return N0;
6399 }
6400
6401 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6402   EVT VT = Op.getValueType();
6403   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6404          "unexpected type for custom-lowering ISD::SDIV");
6405
6406   SDLoc dl(Op);
6407   SDValue N0 = Op.getOperand(0);
6408   SDValue N1 = Op.getOperand(1);
6409   SDValue N2, N3;
6410
6411   if (VT == MVT::v8i8) {
6412     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6413     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6414
6415     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6416                      DAG.getIntPtrConstant(4, dl));
6417     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6418                      DAG.getIntPtrConstant(4, dl));
6419     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6420                      DAG.getIntPtrConstant(0, dl));
6421     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6422                      DAG.getIntPtrConstant(0, dl));
6423
6424     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6425     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6426
6427     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6428     N0 = LowerCONCAT_VECTORS(N0, DAG);
6429
6430     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6431     return N0;
6432   }
6433   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6434 }
6435
6436 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6437   EVT VT = Op.getValueType();
6438   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6439          "unexpected type for custom-lowering ISD::UDIV");
6440
6441   SDLoc dl(Op);
6442   SDValue N0 = Op.getOperand(0);
6443   SDValue N1 = Op.getOperand(1);
6444   SDValue N2, N3;
6445
6446   if (VT == MVT::v8i8) {
6447     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6448     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6449
6450     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6451                      DAG.getIntPtrConstant(4, dl));
6452     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6453                      DAG.getIntPtrConstant(4, dl));
6454     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6455                      DAG.getIntPtrConstant(0, dl));
6456     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6457                      DAG.getIntPtrConstant(0, dl));
6458
6459     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6460     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6461
6462     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6463     N0 = LowerCONCAT_VECTORS(N0, DAG);
6464
6465     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6466                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6467                                      MVT::i32),
6468                      N0);
6469     return N0;
6470   }
6471
6472   // v4i16 sdiv ... Convert to float.
6473   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6474   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6475   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6476   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6477   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6478   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6479
6480   // Use reciprocal estimate and two refinement steps.
6481   // float4 recip = vrecpeq_f32(yf);
6482   // recip *= vrecpsq_f32(yf, recip);
6483   // recip *= vrecpsq_f32(yf, recip);
6484   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6485                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6486                    BN1);
6487   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6488                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6489                    BN1, N2);
6490   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6491   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6492                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6493                    BN1, N2);
6494   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6495   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6496   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6497   // and that it will never cause us to return an answer too large).
6498   // float4 result = as_float4(as_int4(xf*recip) + 2);
6499   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6500   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6501   N1 = DAG.getConstant(2, dl, MVT::i32);
6502   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6503   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6504   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6505   // Convert back to integer and return.
6506   // return vmovn_u32(vcvt_s32_f32(result));
6507   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6508   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6509   return N0;
6510 }
6511
6512 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6513   EVT VT = Op.getNode()->getValueType(0);
6514   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6515
6516   unsigned Opc;
6517   bool ExtraOp = false;
6518   switch (Op.getOpcode()) {
6519   default: llvm_unreachable("Invalid code");
6520   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6521   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6522   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6523   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6524   }
6525
6526   if (!ExtraOp)
6527     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6528                        Op.getOperand(1));
6529   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6530                      Op.getOperand(1), Op.getOperand(2));
6531 }
6532
6533 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6534   assert(Subtarget->isTargetDarwin());
6535
6536   // For iOS, we want to call an alternative entry point: __sincos_stret,
6537   // return values are passed via sret.
6538   SDLoc dl(Op);
6539   SDValue Arg = Op.getOperand(0);
6540   EVT ArgVT = Arg.getValueType();
6541   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6542   auto PtrVT = getPointerTy(DAG.getDataLayout());
6543
6544   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6545
6546   // Pair of floats / doubles used to pass the result.
6547   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6548
6549   // Create stack object for sret.
6550   auto &DL = DAG.getDataLayout();
6551   const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6552   const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6553   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6554   SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6555
6556   ArgListTy Args;
6557   ArgListEntry Entry;
6558
6559   Entry.Node = SRet;
6560   Entry.Ty = RetTy->getPointerTo();
6561   Entry.isSExt = false;
6562   Entry.isZExt = false;
6563   Entry.isSRet = true;
6564   Args.push_back(Entry);
6565
6566   Entry.Node = Arg;
6567   Entry.Ty = ArgTy;
6568   Entry.isSExt = false;
6569   Entry.isZExt = false;
6570   Args.push_back(Entry);
6571
6572   const char *LibcallName  = (ArgVT == MVT::f64)
6573   ? "__sincos_stret" : "__sincosf_stret";
6574   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6575
6576   TargetLowering::CallLoweringInfo CLI(DAG);
6577   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6578     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6579                std::move(Args), 0)
6580     .setDiscardResult();
6581
6582   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6583
6584   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6585                                 MachinePointerInfo(), false, false, false, 0);
6586
6587   // Address of cos field.
6588   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6589                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6590   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6591                                 MachinePointerInfo(), false, false, false, 0);
6592
6593   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6594   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6595                      LoadSin.getValue(0), LoadCos.getValue(0));
6596 }
6597
6598 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6599   // Monotonic load/store is legal for all targets
6600   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6601     return Op;
6602
6603   // Acquire/Release load/store is not legal for targets without a
6604   // dmb or equivalent available.
6605   return SDValue();
6606 }
6607
6608 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6609                                     SmallVectorImpl<SDValue> &Results,
6610                                     SelectionDAG &DAG,
6611                                     const ARMSubtarget *Subtarget) {
6612   SDLoc DL(N);
6613   SDValue Cycles32, OutChain;
6614
6615   if (Subtarget->hasPerfMon()) {
6616     // Under Power Management extensions, the cycle-count is:
6617     //    mrc p15, #0, <Rt>, c9, c13, #0
6618     SDValue Ops[] = { N->getOperand(0), // Chain
6619                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6620                       DAG.getConstant(15, DL, MVT::i32),
6621                       DAG.getConstant(0, DL, MVT::i32),
6622                       DAG.getConstant(9, DL, MVT::i32),
6623                       DAG.getConstant(13, DL, MVT::i32),
6624                       DAG.getConstant(0, DL, MVT::i32)
6625     };
6626
6627     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6628                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6629     OutChain = Cycles32.getValue(1);
6630   } else {
6631     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6632     // there are older ARM CPUs that have implementation-specific ways of
6633     // obtaining this information (FIXME!).
6634     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6635     OutChain = DAG.getEntryNode();
6636   }
6637
6638
6639   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6640                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6641   Results.push_back(Cycles64);
6642   Results.push_back(OutChain);
6643 }
6644
6645 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6646   switch (Op.getOpcode()) {
6647   default: llvm_unreachable("Don't know how to custom lower this!");
6648   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6649   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6650   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6651   case ISD::GlobalAddress:
6652     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6653     default: llvm_unreachable("unknown object format");
6654     case Triple::COFF:
6655       return LowerGlobalAddressWindows(Op, DAG);
6656     case Triple::ELF:
6657       return LowerGlobalAddressELF(Op, DAG);
6658     case Triple::MachO:
6659       return LowerGlobalAddressDarwin(Op, DAG);
6660     }
6661   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6662   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6663   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6664   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6665   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6666   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6667   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6668   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6669   case ISD::SINT_TO_FP:
6670   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6671   case ISD::FP_TO_SINT:
6672   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6673   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6674   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6675   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6676   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6677   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6678   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6679   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6680   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6681                                                                Subtarget);
6682   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6683   case ISD::SHL:
6684   case ISD::SRL:
6685   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6686   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6687   case ISD::SRL_PARTS:
6688   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6689   case ISD::CTTZ:
6690   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6691   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6692   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6693   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6694   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6695   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6696   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6697   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6698   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6699   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6700   case ISD::MUL:           return LowerMUL(Op, DAG);
6701   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6702   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6703   case ISD::ADDC:
6704   case ISD::ADDE:
6705   case ISD::SUBC:
6706   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6707   case ISD::SADDO:
6708   case ISD::UADDO:
6709   case ISD::SSUBO:
6710   case ISD::USUBO:
6711     return LowerXALUO(Op, DAG);
6712   case ISD::ATOMIC_LOAD:
6713   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6714   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6715   case ISD::SDIVREM:
6716   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6717   case ISD::DYNAMIC_STACKALLOC:
6718     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6719       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6720     llvm_unreachable("Don't know how to custom lower this!");
6721   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6722   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6723   }
6724 }
6725
6726 /// ReplaceNodeResults - Replace the results of node with an illegal result
6727 /// type with new values built out of custom code.
6728 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6729                                            SmallVectorImpl<SDValue>&Results,
6730                                            SelectionDAG &DAG) const {
6731   SDValue Res;
6732   switch (N->getOpcode()) {
6733   default:
6734     llvm_unreachable("Don't know how to custom expand this!");
6735   case ISD::READ_REGISTER:
6736     ExpandREAD_REGISTER(N, Results, DAG);
6737     break;
6738   case ISD::BITCAST:
6739     Res = ExpandBITCAST(N, DAG);
6740     break;
6741   case ISD::SRL:
6742   case ISD::SRA:
6743     Res = Expand64BitShift(N, DAG, Subtarget);
6744     break;
6745   case ISD::READCYCLECOUNTER:
6746     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6747     return;
6748   }
6749   if (Res.getNode())
6750     Results.push_back(Res);
6751 }
6752
6753 //===----------------------------------------------------------------------===//
6754 //                           ARM Scheduler Hooks
6755 //===----------------------------------------------------------------------===//
6756
6757 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6758 /// registers the function context.
6759 void ARMTargetLowering::
6760 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6761                        MachineBasicBlock *DispatchBB, int FI) const {
6762   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6763   DebugLoc dl = MI->getDebugLoc();
6764   MachineFunction *MF = MBB->getParent();
6765   MachineRegisterInfo *MRI = &MF->getRegInfo();
6766   MachineConstantPool *MCP = MF->getConstantPool();
6767   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6768   const Function *F = MF->getFunction();
6769
6770   bool isThumb = Subtarget->isThumb();
6771   bool isThumb2 = Subtarget->isThumb2();
6772
6773   unsigned PCLabelId = AFI->createPICLabelUId();
6774   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6775   ARMConstantPoolValue *CPV =
6776     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6777   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6778
6779   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6780                                            : &ARM::GPRRegClass;
6781
6782   // Grab constant pool and fixed stack memory operands.
6783   MachineMemOperand *CPMMO =
6784     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6785                              MachineMemOperand::MOLoad, 4, 4);
6786
6787   MachineMemOperand *FIMMOSt =
6788     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6789                              MachineMemOperand::MOStore, 4, 4);
6790
6791   // Load the address of the dispatch MBB into the jump buffer.
6792   if (isThumb2) {
6793     // Incoming value: jbuf
6794     //   ldr.n  r5, LCPI1_1
6795     //   orr    r5, r5, #1
6796     //   add    r5, pc
6797     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6798     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6799     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6800                    .addConstantPoolIndex(CPI)
6801                    .addMemOperand(CPMMO));
6802     // Set the low bit because of thumb mode.
6803     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6804     AddDefaultCC(
6805       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6806                      .addReg(NewVReg1, RegState::Kill)
6807                      .addImm(0x01)));
6808     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6809     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6810       .addReg(NewVReg2, RegState::Kill)
6811       .addImm(PCLabelId);
6812     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6813                    .addReg(NewVReg3, RegState::Kill)
6814                    .addFrameIndex(FI)
6815                    .addImm(36)  // &jbuf[1] :: pc
6816                    .addMemOperand(FIMMOSt));
6817   } else if (isThumb) {
6818     // Incoming value: jbuf
6819     //   ldr.n  r1, LCPI1_4
6820     //   add    r1, pc
6821     //   mov    r2, #1
6822     //   orrs   r1, r2
6823     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6824     //   str    r1, [r2]
6825     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6826     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6827                    .addConstantPoolIndex(CPI)
6828                    .addMemOperand(CPMMO));
6829     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6830     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6831       .addReg(NewVReg1, RegState::Kill)
6832       .addImm(PCLabelId);
6833     // Set the low bit because of thumb mode.
6834     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6835     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6836                    .addReg(ARM::CPSR, RegState::Define)
6837                    .addImm(1));
6838     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6839     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6840                    .addReg(ARM::CPSR, RegState::Define)
6841                    .addReg(NewVReg2, RegState::Kill)
6842                    .addReg(NewVReg3, RegState::Kill));
6843     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6844     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6845             .addFrameIndex(FI)
6846             .addImm(36); // &jbuf[1] :: pc
6847     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6848                    .addReg(NewVReg4, RegState::Kill)
6849                    .addReg(NewVReg5, RegState::Kill)
6850                    .addImm(0)
6851                    .addMemOperand(FIMMOSt));
6852   } else {
6853     // Incoming value: jbuf
6854     //   ldr  r1, LCPI1_1
6855     //   add  r1, pc, r1
6856     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6857     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6858     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6859                    .addConstantPoolIndex(CPI)
6860                    .addImm(0)
6861                    .addMemOperand(CPMMO));
6862     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6863     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6864                    .addReg(NewVReg1, RegState::Kill)
6865                    .addImm(PCLabelId));
6866     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6867                    .addReg(NewVReg2, RegState::Kill)
6868                    .addFrameIndex(FI)
6869                    .addImm(36)  // &jbuf[1] :: pc
6870                    .addMemOperand(FIMMOSt));
6871   }
6872 }
6873
6874 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6875                                               MachineBasicBlock *MBB) const {
6876   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6877   DebugLoc dl = MI->getDebugLoc();
6878   MachineFunction *MF = MBB->getParent();
6879   MachineRegisterInfo *MRI = &MF->getRegInfo();
6880   MachineFrameInfo *MFI = MF->getFrameInfo();
6881   int FI = MFI->getFunctionContextIndex();
6882
6883   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6884                                                         : &ARM::GPRnopcRegClass;
6885
6886   // Get a mapping of the call site numbers to all of the landing pads they're
6887   // associated with.
6888   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6889   unsigned MaxCSNum = 0;
6890   MachineModuleInfo &MMI = MF->getMMI();
6891   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6892        ++BB) {
6893     if (!BB->isLandingPad()) continue;
6894
6895     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6896     // pad.
6897     for (MachineBasicBlock::iterator
6898            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6899       if (!II->isEHLabel()) continue;
6900
6901       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6902       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6903
6904       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6905       for (SmallVectorImpl<unsigned>::iterator
6906              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6907            CSI != CSE; ++CSI) {
6908         CallSiteNumToLPad[*CSI].push_back(BB);
6909         MaxCSNum = std::max(MaxCSNum, *CSI);
6910       }
6911       break;
6912     }
6913   }
6914
6915   // Get an ordered list of the machine basic blocks for the jump table.
6916   std::vector<MachineBasicBlock*> LPadList;
6917   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6918   LPadList.reserve(CallSiteNumToLPad.size());
6919   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6920     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6921     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6922            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6923       LPadList.push_back(*II);
6924       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6925     }
6926   }
6927
6928   assert(!LPadList.empty() &&
6929          "No landing pad destinations for the dispatch jump table!");
6930
6931   // Create the jump table and associated information.
6932   MachineJumpTableInfo *JTI =
6933     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6934   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6935   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6936
6937   // Create the MBBs for the dispatch code.
6938
6939   // Shove the dispatch's address into the return slot in the function context.
6940   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6941   DispatchBB->setIsLandingPad();
6942
6943   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6944   unsigned trap_opcode;
6945   if (Subtarget->isThumb())
6946     trap_opcode = ARM::tTRAP;
6947   else
6948     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6949
6950   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6951   DispatchBB->addSuccessor(TrapBB);
6952
6953   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6954   DispatchBB->addSuccessor(DispContBB);
6955
6956   // Insert and MBBs.
6957   MF->insert(MF->end(), DispatchBB);
6958   MF->insert(MF->end(), DispContBB);
6959   MF->insert(MF->end(), TrapBB);
6960
6961   // Insert code into the entry block that creates and registers the function
6962   // context.
6963   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6964
6965   MachineMemOperand *FIMMOLd =
6966     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6967                              MachineMemOperand::MOLoad |
6968                              MachineMemOperand::MOVolatile, 4, 4);
6969
6970   MachineInstrBuilder MIB;
6971   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6972
6973   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6974   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6975
6976   // Add a register mask with no preserved registers.  This results in all
6977   // registers being marked as clobbered.
6978   MIB.addRegMask(RI.getNoPreservedMask());
6979
6980   unsigned NumLPads = LPadList.size();
6981   if (Subtarget->isThumb2()) {
6982     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6983     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6984                    .addFrameIndex(FI)
6985                    .addImm(4)
6986                    .addMemOperand(FIMMOLd));
6987
6988     if (NumLPads < 256) {
6989       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6990                      .addReg(NewVReg1)
6991                      .addImm(LPadList.size()));
6992     } else {
6993       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6994       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6995                      .addImm(NumLPads & 0xFFFF));
6996
6997       unsigned VReg2 = VReg1;
6998       if ((NumLPads & 0xFFFF0000) != 0) {
6999         VReg2 = MRI->createVirtualRegister(TRC);
7000         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7001                        .addReg(VReg1)
7002                        .addImm(NumLPads >> 16));
7003       }
7004
7005       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7006                      .addReg(NewVReg1)
7007                      .addReg(VReg2));
7008     }
7009
7010     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7011       .addMBB(TrapBB)
7012       .addImm(ARMCC::HI)
7013       .addReg(ARM::CPSR);
7014
7015     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7016     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7017                    .addJumpTableIndex(MJTI));
7018
7019     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7020     AddDefaultCC(
7021       AddDefaultPred(
7022         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7023         .addReg(NewVReg3, RegState::Kill)
7024         .addReg(NewVReg1)
7025         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7026
7027     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7028       .addReg(NewVReg4, RegState::Kill)
7029       .addReg(NewVReg1)
7030       .addJumpTableIndex(MJTI);
7031   } else if (Subtarget->isThumb()) {
7032     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7033     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7034                    .addFrameIndex(FI)
7035                    .addImm(1)
7036                    .addMemOperand(FIMMOLd));
7037
7038     if (NumLPads < 256) {
7039       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7040                      .addReg(NewVReg1)
7041                      .addImm(NumLPads));
7042     } else {
7043       MachineConstantPool *ConstantPool = MF->getConstantPool();
7044       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7045       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7046
7047       // MachineConstantPool wants an explicit alignment.
7048       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7049       if (Align == 0)
7050         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7051       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7052
7053       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7054       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7055                      .addReg(VReg1, RegState::Define)
7056                      .addConstantPoolIndex(Idx));
7057       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7058                      .addReg(NewVReg1)
7059                      .addReg(VReg1));
7060     }
7061
7062     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7063       .addMBB(TrapBB)
7064       .addImm(ARMCC::HI)
7065       .addReg(ARM::CPSR);
7066
7067     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7068     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7069                    .addReg(ARM::CPSR, RegState::Define)
7070                    .addReg(NewVReg1)
7071                    .addImm(2));
7072
7073     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7074     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7075                    .addJumpTableIndex(MJTI));
7076
7077     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7078     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7079                    .addReg(ARM::CPSR, RegState::Define)
7080                    .addReg(NewVReg2, RegState::Kill)
7081                    .addReg(NewVReg3));
7082
7083     MachineMemOperand *JTMMOLd =
7084       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7085                                MachineMemOperand::MOLoad, 4, 4);
7086
7087     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7088     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7089                    .addReg(NewVReg4, RegState::Kill)
7090                    .addImm(0)
7091                    .addMemOperand(JTMMOLd));
7092
7093     unsigned NewVReg6 = NewVReg5;
7094     if (RelocM == Reloc::PIC_) {
7095       NewVReg6 = MRI->createVirtualRegister(TRC);
7096       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7097                      .addReg(ARM::CPSR, RegState::Define)
7098                      .addReg(NewVReg5, RegState::Kill)
7099                      .addReg(NewVReg3));
7100     }
7101
7102     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7103       .addReg(NewVReg6, RegState::Kill)
7104       .addJumpTableIndex(MJTI);
7105   } else {
7106     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7107     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7108                    .addFrameIndex(FI)
7109                    .addImm(4)
7110                    .addMemOperand(FIMMOLd));
7111
7112     if (NumLPads < 256) {
7113       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7114                      .addReg(NewVReg1)
7115                      .addImm(NumLPads));
7116     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7117       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7118       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7119                      .addImm(NumLPads & 0xFFFF));
7120
7121       unsigned VReg2 = VReg1;
7122       if ((NumLPads & 0xFFFF0000) != 0) {
7123         VReg2 = MRI->createVirtualRegister(TRC);
7124         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7125                        .addReg(VReg1)
7126                        .addImm(NumLPads >> 16));
7127       }
7128
7129       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7130                      .addReg(NewVReg1)
7131                      .addReg(VReg2));
7132     } else {
7133       MachineConstantPool *ConstantPool = MF->getConstantPool();
7134       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7135       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7136
7137       // MachineConstantPool wants an explicit alignment.
7138       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7139       if (Align == 0)
7140         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7141       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7142
7143       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7144       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7145                      .addReg(VReg1, RegState::Define)
7146                      .addConstantPoolIndex(Idx)
7147                      .addImm(0));
7148       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7149                      .addReg(NewVReg1)
7150                      .addReg(VReg1, RegState::Kill));
7151     }
7152
7153     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7154       .addMBB(TrapBB)
7155       .addImm(ARMCC::HI)
7156       .addReg(ARM::CPSR);
7157
7158     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7159     AddDefaultCC(
7160       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7161                      .addReg(NewVReg1)
7162                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7163     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7164     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7165                    .addJumpTableIndex(MJTI));
7166
7167     MachineMemOperand *JTMMOLd =
7168       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7169                                MachineMemOperand::MOLoad, 4, 4);
7170     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7171     AddDefaultPred(
7172       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7173       .addReg(NewVReg3, RegState::Kill)
7174       .addReg(NewVReg4)
7175       .addImm(0)
7176       .addMemOperand(JTMMOLd));
7177
7178     if (RelocM == Reloc::PIC_) {
7179       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7180         .addReg(NewVReg5, RegState::Kill)
7181         .addReg(NewVReg4)
7182         .addJumpTableIndex(MJTI);
7183     } else {
7184       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7185         .addReg(NewVReg5, RegState::Kill)
7186         .addJumpTableIndex(MJTI);
7187     }
7188   }
7189
7190   // Add the jump table entries as successors to the MBB.
7191   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7192   for (std::vector<MachineBasicBlock*>::iterator
7193          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7194     MachineBasicBlock *CurMBB = *I;
7195     if (SeenMBBs.insert(CurMBB).second)
7196       DispContBB->addSuccessor(CurMBB);
7197   }
7198
7199   // N.B. the order the invoke BBs are processed in doesn't matter here.
7200   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7201   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7202   for (MachineBasicBlock *BB : InvokeBBs) {
7203
7204     // Remove the landing pad successor from the invoke block and replace it
7205     // with the new dispatch block.
7206     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7207                                                   BB->succ_end());
7208     while (!Successors.empty()) {
7209       MachineBasicBlock *SMBB = Successors.pop_back_val();
7210       if (SMBB->isLandingPad()) {
7211         BB->removeSuccessor(SMBB);
7212         MBBLPads.push_back(SMBB);
7213       }
7214     }
7215
7216     BB->addSuccessor(DispatchBB);
7217
7218     // Find the invoke call and mark all of the callee-saved registers as
7219     // 'implicit defined' so that they're spilled. This prevents code from
7220     // moving instructions to before the EH block, where they will never be
7221     // executed.
7222     for (MachineBasicBlock::reverse_iterator
7223            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7224       if (!II->isCall()) continue;
7225
7226       DenseMap<unsigned, bool> DefRegs;
7227       for (MachineInstr::mop_iterator
7228              OI = II->operands_begin(), OE = II->operands_end();
7229            OI != OE; ++OI) {
7230         if (!OI->isReg()) continue;
7231         DefRegs[OI->getReg()] = true;
7232       }
7233
7234       MachineInstrBuilder MIB(*MF, &*II);
7235
7236       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7237         unsigned Reg = SavedRegs[i];
7238         if (Subtarget->isThumb2() &&
7239             !ARM::tGPRRegClass.contains(Reg) &&
7240             !ARM::hGPRRegClass.contains(Reg))
7241           continue;
7242         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7243           continue;
7244         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7245           continue;
7246         if (!DefRegs[Reg])
7247           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7248       }
7249
7250       break;
7251     }
7252   }
7253
7254   // Mark all former landing pads as non-landing pads. The dispatch is the only
7255   // landing pad now.
7256   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7257          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7258     (*I)->setIsLandingPad(false);
7259
7260   // The instruction is gone now.
7261   MI->eraseFromParent();
7262 }
7263
7264 static
7265 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7266   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7267        E = MBB->succ_end(); I != E; ++I)
7268     if (*I != Succ)
7269       return *I;
7270   llvm_unreachable("Expecting a BB with two successors!");
7271 }
7272
7273 /// Return the load opcode for a given load size. If load size >= 8,
7274 /// neon opcode will be returned.
7275 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7276   if (LdSize >= 8)
7277     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7278                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7279   if (IsThumb1)
7280     return LdSize == 4 ? ARM::tLDRi
7281                        : LdSize == 2 ? ARM::tLDRHi
7282                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7283   if (IsThumb2)
7284     return LdSize == 4 ? ARM::t2LDR_POST
7285                        : LdSize == 2 ? ARM::t2LDRH_POST
7286                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7287   return LdSize == 4 ? ARM::LDR_POST_IMM
7288                      : LdSize == 2 ? ARM::LDRH_POST
7289                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7290 }
7291
7292 /// Return the store opcode for a given store size. If store size >= 8,
7293 /// neon opcode will be returned.
7294 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7295   if (StSize >= 8)
7296     return StSize == 16 ? ARM::VST1q32wb_fixed
7297                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7298   if (IsThumb1)
7299     return StSize == 4 ? ARM::tSTRi
7300                        : StSize == 2 ? ARM::tSTRHi
7301                                      : StSize == 1 ? ARM::tSTRBi : 0;
7302   if (IsThumb2)
7303     return StSize == 4 ? ARM::t2STR_POST
7304                        : StSize == 2 ? ARM::t2STRH_POST
7305                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7306   return StSize == 4 ? ARM::STR_POST_IMM
7307                      : StSize == 2 ? ARM::STRH_POST
7308                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7309 }
7310
7311 /// Emit a post-increment load operation with given size. The instructions
7312 /// will be added to BB at Pos.
7313 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7314                        const TargetInstrInfo *TII, DebugLoc dl,
7315                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7316                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7317   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7318   assert(LdOpc != 0 && "Should have a load opcode");
7319   if (LdSize >= 8) {
7320     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7321                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7322                        .addImm(0));
7323   } else if (IsThumb1) {
7324     // load + update AddrIn
7325     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7326                        .addReg(AddrIn).addImm(0));
7327     MachineInstrBuilder MIB =
7328         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7329     MIB = AddDefaultT1CC(MIB);
7330     MIB.addReg(AddrIn).addImm(LdSize);
7331     AddDefaultPred(MIB);
7332   } else if (IsThumb2) {
7333     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7334                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7335                        .addImm(LdSize));
7336   } else { // arm
7337     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7338                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7339                        .addReg(0).addImm(LdSize));
7340   }
7341 }
7342
7343 /// Emit a post-increment store operation with given size. The instructions
7344 /// will be added to BB at Pos.
7345 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7346                        const TargetInstrInfo *TII, DebugLoc dl,
7347                        unsigned StSize, unsigned Data, unsigned AddrIn,
7348                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7349   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7350   assert(StOpc != 0 && "Should have a store opcode");
7351   if (StSize >= 8) {
7352     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7353                        .addReg(AddrIn).addImm(0).addReg(Data));
7354   } else if (IsThumb1) {
7355     // store + update AddrIn
7356     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7357                        .addReg(AddrIn).addImm(0));
7358     MachineInstrBuilder MIB =
7359         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7360     MIB = AddDefaultT1CC(MIB);
7361     MIB.addReg(AddrIn).addImm(StSize);
7362     AddDefaultPred(MIB);
7363   } else if (IsThumb2) {
7364     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7365                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7366   } else { // arm
7367     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7368                        .addReg(Data).addReg(AddrIn).addReg(0)
7369                        .addImm(StSize));
7370   }
7371 }
7372
7373 MachineBasicBlock *
7374 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7375                                    MachineBasicBlock *BB) const {
7376   // This pseudo instruction has 3 operands: dst, src, size
7377   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7378   // Otherwise, we will generate unrolled scalar copies.
7379   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7380   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7381   MachineFunction::iterator It = BB;
7382   ++It;
7383
7384   unsigned dest = MI->getOperand(0).getReg();
7385   unsigned src = MI->getOperand(1).getReg();
7386   unsigned SizeVal = MI->getOperand(2).getImm();
7387   unsigned Align = MI->getOperand(3).getImm();
7388   DebugLoc dl = MI->getDebugLoc();
7389
7390   MachineFunction *MF = BB->getParent();
7391   MachineRegisterInfo &MRI = MF->getRegInfo();
7392   unsigned UnitSize = 0;
7393   const TargetRegisterClass *TRC = nullptr;
7394   const TargetRegisterClass *VecTRC = nullptr;
7395
7396   bool IsThumb1 = Subtarget->isThumb1Only();
7397   bool IsThumb2 = Subtarget->isThumb2();
7398
7399   if (Align & 1) {
7400     UnitSize = 1;
7401   } else if (Align & 2) {
7402     UnitSize = 2;
7403   } else {
7404     // Check whether we can use NEON instructions.
7405     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7406         Subtarget->hasNEON()) {
7407       if ((Align % 16 == 0) && SizeVal >= 16)
7408         UnitSize = 16;
7409       else if ((Align % 8 == 0) && SizeVal >= 8)
7410         UnitSize = 8;
7411     }
7412     // Can't use NEON instructions.
7413     if (UnitSize == 0)
7414       UnitSize = 4;
7415   }
7416
7417   // Select the correct opcode and register class for unit size load/store
7418   bool IsNeon = UnitSize >= 8;
7419   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7420   if (IsNeon)
7421     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7422                             : UnitSize == 8 ? &ARM::DPRRegClass
7423                                             : nullptr;
7424
7425   unsigned BytesLeft = SizeVal % UnitSize;
7426   unsigned LoopSize = SizeVal - BytesLeft;
7427
7428   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7429     // Use LDR and STR to copy.
7430     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7431     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7432     unsigned srcIn = src;
7433     unsigned destIn = dest;
7434     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7435       unsigned srcOut = MRI.createVirtualRegister(TRC);
7436       unsigned destOut = MRI.createVirtualRegister(TRC);
7437       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7438       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7439                  IsThumb1, IsThumb2);
7440       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7441                  IsThumb1, IsThumb2);
7442       srcIn = srcOut;
7443       destIn = destOut;
7444     }
7445
7446     // Handle the leftover bytes with LDRB and STRB.
7447     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7448     // [destOut] = STRB_POST(scratch, destIn, 1)
7449     for (unsigned i = 0; i < BytesLeft; i++) {
7450       unsigned srcOut = MRI.createVirtualRegister(TRC);
7451       unsigned destOut = MRI.createVirtualRegister(TRC);
7452       unsigned scratch = MRI.createVirtualRegister(TRC);
7453       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7454                  IsThumb1, IsThumb2);
7455       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7456                  IsThumb1, IsThumb2);
7457       srcIn = srcOut;
7458       destIn = destOut;
7459     }
7460     MI->eraseFromParent();   // The instruction is gone now.
7461     return BB;
7462   }
7463
7464   // Expand the pseudo op to a loop.
7465   // thisMBB:
7466   //   ...
7467   //   movw varEnd, # --> with thumb2
7468   //   movt varEnd, #
7469   //   ldrcp varEnd, idx --> without thumb2
7470   //   fallthrough --> loopMBB
7471   // loopMBB:
7472   //   PHI varPhi, varEnd, varLoop
7473   //   PHI srcPhi, src, srcLoop
7474   //   PHI destPhi, dst, destLoop
7475   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7476   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7477   //   subs varLoop, varPhi, #UnitSize
7478   //   bne loopMBB
7479   //   fallthrough --> exitMBB
7480   // exitMBB:
7481   //   epilogue to handle left-over bytes
7482   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7483   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7484   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7485   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7486   MF->insert(It, loopMBB);
7487   MF->insert(It, exitMBB);
7488
7489   // Transfer the remainder of BB and its successor edges to exitMBB.
7490   exitMBB->splice(exitMBB->begin(), BB,
7491                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7492   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7493
7494   // Load an immediate to varEnd.
7495   unsigned varEnd = MRI.createVirtualRegister(TRC);
7496   if (Subtarget->useMovt(*MF)) {
7497     unsigned Vtmp = varEnd;
7498     if ((LoopSize & 0xFFFF0000) != 0)
7499       Vtmp = MRI.createVirtualRegister(TRC);
7500     AddDefaultPred(BuildMI(BB, dl,
7501                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7502                            Vtmp).addImm(LoopSize & 0xFFFF));
7503
7504     if ((LoopSize & 0xFFFF0000) != 0)
7505       AddDefaultPred(BuildMI(BB, dl,
7506                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7507                              varEnd)
7508                          .addReg(Vtmp)
7509                          .addImm(LoopSize >> 16));
7510   } else {
7511     MachineConstantPool *ConstantPool = MF->getConstantPool();
7512     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7513     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7514
7515     // MachineConstantPool wants an explicit alignment.
7516     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7517     if (Align == 0)
7518       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7519     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7520
7521     if (IsThumb1)
7522       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7523           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7524     else
7525       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7526           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7527   }
7528   BB->addSuccessor(loopMBB);
7529
7530   // Generate the loop body:
7531   //   varPhi = PHI(varLoop, varEnd)
7532   //   srcPhi = PHI(srcLoop, src)
7533   //   destPhi = PHI(destLoop, dst)
7534   MachineBasicBlock *entryBB = BB;
7535   BB = loopMBB;
7536   unsigned varLoop = MRI.createVirtualRegister(TRC);
7537   unsigned varPhi = MRI.createVirtualRegister(TRC);
7538   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7539   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7540   unsigned destLoop = MRI.createVirtualRegister(TRC);
7541   unsigned destPhi = MRI.createVirtualRegister(TRC);
7542
7543   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7544     .addReg(varLoop).addMBB(loopMBB)
7545     .addReg(varEnd).addMBB(entryBB);
7546   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7547     .addReg(srcLoop).addMBB(loopMBB)
7548     .addReg(src).addMBB(entryBB);
7549   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7550     .addReg(destLoop).addMBB(loopMBB)
7551     .addReg(dest).addMBB(entryBB);
7552
7553   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7554   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7555   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7556   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7557              IsThumb1, IsThumb2);
7558   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7559              IsThumb1, IsThumb2);
7560
7561   // Decrement loop variable by UnitSize.
7562   if (IsThumb1) {
7563     MachineInstrBuilder MIB =
7564         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7565     MIB = AddDefaultT1CC(MIB);
7566     MIB.addReg(varPhi).addImm(UnitSize);
7567     AddDefaultPred(MIB);
7568   } else {
7569     MachineInstrBuilder MIB =
7570         BuildMI(*BB, BB->end(), dl,
7571                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7572     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7573     MIB->getOperand(5).setReg(ARM::CPSR);
7574     MIB->getOperand(5).setIsDef(true);
7575   }
7576   BuildMI(*BB, BB->end(), dl,
7577           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7578       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7579
7580   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7581   BB->addSuccessor(loopMBB);
7582   BB->addSuccessor(exitMBB);
7583
7584   // Add epilogue to handle BytesLeft.
7585   BB = exitMBB;
7586   MachineInstr *StartOfExit = exitMBB->begin();
7587
7588   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7589   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7590   unsigned srcIn = srcLoop;
7591   unsigned destIn = destLoop;
7592   for (unsigned i = 0; i < BytesLeft; i++) {
7593     unsigned srcOut = MRI.createVirtualRegister(TRC);
7594     unsigned destOut = MRI.createVirtualRegister(TRC);
7595     unsigned scratch = MRI.createVirtualRegister(TRC);
7596     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7597                IsThumb1, IsThumb2);
7598     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7599                IsThumb1, IsThumb2);
7600     srcIn = srcOut;
7601     destIn = destOut;
7602   }
7603
7604   MI->eraseFromParent();   // The instruction is gone now.
7605   return BB;
7606 }
7607
7608 MachineBasicBlock *
7609 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7610                                        MachineBasicBlock *MBB) const {
7611   const TargetMachine &TM = getTargetMachine();
7612   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7613   DebugLoc DL = MI->getDebugLoc();
7614
7615   assert(Subtarget->isTargetWindows() &&
7616          "__chkstk is only supported on Windows");
7617   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7618
7619   // __chkstk takes the number of words to allocate on the stack in R4, and
7620   // returns the stack adjustment in number of bytes in R4.  This will not
7621   // clober any other registers (other than the obvious lr).
7622   //
7623   // Although, technically, IP should be considered a register which may be
7624   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7625   // thumb-2 environment, so there is no interworking required.  As a result, we
7626   // do not expect a veneer to be emitted by the linker, clobbering IP.
7627   //
7628   // Each module receives its own copy of __chkstk, so no import thunk is
7629   // required, again, ensuring that IP is not clobbered.
7630   //
7631   // Finally, although some linkers may theoretically provide a trampoline for
7632   // out of range calls (which is quite common due to a 32M range limitation of
7633   // branches for Thumb), we can generate the long-call version via
7634   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7635   // IP.
7636
7637   switch (TM.getCodeModel()) {
7638   case CodeModel::Small:
7639   case CodeModel::Medium:
7640   case CodeModel::Default:
7641   case CodeModel::Kernel:
7642     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7643       .addImm((unsigned)ARMCC::AL).addReg(0)
7644       .addExternalSymbol("__chkstk")
7645       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7646       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7647       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7648     break;
7649   case CodeModel::Large:
7650   case CodeModel::JITDefault: {
7651     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7652     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7653
7654     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7655       .addExternalSymbol("__chkstk");
7656     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7657       .addImm((unsigned)ARMCC::AL).addReg(0)
7658       .addReg(Reg, RegState::Kill)
7659       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7660       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7661       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7662     break;
7663   }
7664   }
7665
7666   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7667                                       ARM::SP)
7668                               .addReg(ARM::SP).addReg(ARM::R4)));
7669
7670   MI->eraseFromParent();
7671   return MBB;
7672 }
7673
7674 MachineBasicBlock *
7675 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7676                                                MachineBasicBlock *BB) const {
7677   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7678   DebugLoc dl = MI->getDebugLoc();
7679   bool isThumb2 = Subtarget->isThumb2();
7680   switch (MI->getOpcode()) {
7681   default: {
7682     MI->dump();
7683     llvm_unreachable("Unexpected instr type to insert");
7684   }
7685   // The Thumb2 pre-indexed stores have the same MI operands, they just
7686   // define them differently in the .td files from the isel patterns, so
7687   // they need pseudos.
7688   case ARM::t2STR_preidx:
7689     MI->setDesc(TII->get(ARM::t2STR_PRE));
7690     return BB;
7691   case ARM::t2STRB_preidx:
7692     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7693     return BB;
7694   case ARM::t2STRH_preidx:
7695     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7696     return BB;
7697
7698   case ARM::STRi_preidx:
7699   case ARM::STRBi_preidx: {
7700     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7701       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7702     // Decode the offset.
7703     unsigned Offset = MI->getOperand(4).getImm();
7704     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7705     Offset = ARM_AM::getAM2Offset(Offset);
7706     if (isSub)
7707       Offset = -Offset;
7708
7709     MachineMemOperand *MMO = *MI->memoperands_begin();
7710     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7711       .addOperand(MI->getOperand(0))  // Rn_wb
7712       .addOperand(MI->getOperand(1))  // Rt
7713       .addOperand(MI->getOperand(2))  // Rn
7714       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7715       .addOperand(MI->getOperand(5))  // pred
7716       .addOperand(MI->getOperand(6))
7717       .addMemOperand(MMO);
7718     MI->eraseFromParent();
7719     return BB;
7720   }
7721   case ARM::STRr_preidx:
7722   case ARM::STRBr_preidx:
7723   case ARM::STRH_preidx: {
7724     unsigned NewOpc;
7725     switch (MI->getOpcode()) {
7726     default: llvm_unreachable("unexpected opcode!");
7727     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7728     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7729     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7730     }
7731     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7732     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7733       MIB.addOperand(MI->getOperand(i));
7734     MI->eraseFromParent();
7735     return BB;
7736   }
7737
7738   case ARM::tMOVCCr_pseudo: {
7739     // To "insert" a SELECT_CC instruction, we actually have to insert the
7740     // diamond control-flow pattern.  The incoming instruction knows the
7741     // destination vreg to set, the condition code register to branch on, the
7742     // true/false values to select between, and a branch opcode to use.
7743     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7744     MachineFunction::iterator It = BB;
7745     ++It;
7746
7747     //  thisMBB:
7748     //  ...
7749     //   TrueVal = ...
7750     //   cmpTY ccX, r1, r2
7751     //   bCC copy1MBB
7752     //   fallthrough --> copy0MBB
7753     MachineBasicBlock *thisMBB  = BB;
7754     MachineFunction *F = BB->getParent();
7755     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7756     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7757     F->insert(It, copy0MBB);
7758     F->insert(It, sinkMBB);
7759
7760     // Transfer the remainder of BB and its successor edges to sinkMBB.
7761     sinkMBB->splice(sinkMBB->begin(), BB,
7762                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7763     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7764
7765     BB->addSuccessor(copy0MBB);
7766     BB->addSuccessor(sinkMBB);
7767
7768     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7769       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7770
7771     //  copy0MBB:
7772     //   %FalseValue = ...
7773     //   # fallthrough to sinkMBB
7774     BB = copy0MBB;
7775
7776     // Update machine-CFG edges
7777     BB->addSuccessor(sinkMBB);
7778
7779     //  sinkMBB:
7780     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7781     //  ...
7782     BB = sinkMBB;
7783     BuildMI(*BB, BB->begin(), dl,
7784             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7785       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7786       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7787
7788     MI->eraseFromParent();   // The pseudo instruction is gone now.
7789     return BB;
7790   }
7791
7792   case ARM::BCCi64:
7793   case ARM::BCCZi64: {
7794     // If there is an unconditional branch to the other successor, remove it.
7795     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7796
7797     // Compare both parts that make up the double comparison separately for
7798     // equality.
7799     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7800
7801     unsigned LHS1 = MI->getOperand(1).getReg();
7802     unsigned LHS2 = MI->getOperand(2).getReg();
7803     if (RHSisZero) {
7804       AddDefaultPred(BuildMI(BB, dl,
7805                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7806                      .addReg(LHS1).addImm(0));
7807       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7808         .addReg(LHS2).addImm(0)
7809         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7810     } else {
7811       unsigned RHS1 = MI->getOperand(3).getReg();
7812       unsigned RHS2 = MI->getOperand(4).getReg();
7813       AddDefaultPred(BuildMI(BB, dl,
7814                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7815                      .addReg(LHS1).addReg(RHS1));
7816       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7817         .addReg(LHS2).addReg(RHS2)
7818         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7819     }
7820
7821     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7822     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7823     if (MI->getOperand(0).getImm() == ARMCC::NE)
7824       std::swap(destMBB, exitMBB);
7825
7826     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7827       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7828     if (isThumb2)
7829       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7830     else
7831       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7832
7833     MI->eraseFromParent();   // The pseudo instruction is gone now.
7834     return BB;
7835   }
7836
7837   case ARM::Int_eh_sjlj_setjmp:
7838   case ARM::Int_eh_sjlj_setjmp_nofp:
7839   case ARM::tInt_eh_sjlj_setjmp:
7840   case ARM::t2Int_eh_sjlj_setjmp:
7841   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7842     return BB;
7843
7844   case ARM::Int_eh_sjlj_setup_dispatch:
7845     EmitSjLjDispatchBlock(MI, BB);
7846     return BB;
7847
7848   case ARM::ABS:
7849   case ARM::t2ABS: {
7850     // To insert an ABS instruction, we have to insert the
7851     // diamond control-flow pattern.  The incoming instruction knows the
7852     // source vreg to test against 0, the destination vreg to set,
7853     // the condition code register to branch on, the
7854     // true/false values to select between, and a branch opcode to use.
7855     // It transforms
7856     //     V1 = ABS V0
7857     // into
7858     //     V2 = MOVS V0
7859     //     BCC                      (branch to SinkBB if V0 >= 0)
7860     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7861     //     SinkBB: V1 = PHI(V2, V3)
7862     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7863     MachineFunction::iterator BBI = BB;
7864     ++BBI;
7865     MachineFunction *Fn = BB->getParent();
7866     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7867     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7868     Fn->insert(BBI, RSBBB);
7869     Fn->insert(BBI, SinkBB);
7870
7871     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7872     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7873     bool ABSSrcKIll = MI->getOperand(1).isKill();
7874     bool isThumb2 = Subtarget->isThumb2();
7875     MachineRegisterInfo &MRI = Fn->getRegInfo();
7876     // In Thumb mode S must not be specified if source register is the SP or
7877     // PC and if destination register is the SP, so restrict register class
7878     unsigned NewRsbDstReg =
7879       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7880
7881     // Transfer the remainder of BB and its successor edges to sinkMBB.
7882     SinkBB->splice(SinkBB->begin(), BB,
7883                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7884     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7885
7886     BB->addSuccessor(RSBBB);
7887     BB->addSuccessor(SinkBB);
7888
7889     // fall through to SinkMBB
7890     RSBBB->addSuccessor(SinkBB);
7891
7892     // insert a cmp at the end of BB
7893     AddDefaultPred(BuildMI(BB, dl,
7894                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7895                    .addReg(ABSSrcReg).addImm(0));
7896
7897     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7898     BuildMI(BB, dl,
7899       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7900       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7901
7902     // insert rsbri in RSBBB
7903     // Note: BCC and rsbri will be converted into predicated rsbmi
7904     // by if-conversion pass
7905     BuildMI(*RSBBB, RSBBB->begin(), dl,
7906       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7907       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7908       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7909
7910     // insert PHI in SinkBB,
7911     // reuse ABSDstReg to not change uses of ABS instruction
7912     BuildMI(*SinkBB, SinkBB->begin(), dl,
7913       TII->get(ARM::PHI), ABSDstReg)
7914       .addReg(NewRsbDstReg).addMBB(RSBBB)
7915       .addReg(ABSSrcReg).addMBB(BB);
7916
7917     // remove ABS instruction
7918     MI->eraseFromParent();
7919
7920     // return last added BB
7921     return SinkBB;
7922   }
7923   case ARM::COPY_STRUCT_BYVAL_I32:
7924     ++NumLoopByVals;
7925     return EmitStructByval(MI, BB);
7926   case ARM::WIN__CHKSTK:
7927     return EmitLowered__chkstk(MI, BB);
7928   }
7929 }
7930
7931 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7932                                                       SDNode *Node) const {
7933   const MCInstrDesc *MCID = &MI->getDesc();
7934   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7935   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7936   // operand is still set to noreg. If needed, set the optional operand's
7937   // register to CPSR, and remove the redundant implicit def.
7938   //
7939   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7940
7941   // Rename pseudo opcodes.
7942   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7943   if (NewOpc) {
7944     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7945     MCID = &TII->get(NewOpc);
7946
7947     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7948            "converted opcode should be the same except for cc_out");
7949
7950     MI->setDesc(*MCID);
7951
7952     // Add the optional cc_out operand
7953     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7954   }
7955   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7956
7957   // Any ARM instruction that sets the 's' bit should specify an optional
7958   // "cc_out" operand in the last operand position.
7959   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7960     assert(!NewOpc && "Optional cc_out operand required");
7961     return;
7962   }
7963   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7964   // since we already have an optional CPSR def.
7965   bool definesCPSR = false;
7966   bool deadCPSR = false;
7967   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7968        i != e; ++i) {
7969     const MachineOperand &MO = MI->getOperand(i);
7970     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7971       definesCPSR = true;
7972       if (MO.isDead())
7973         deadCPSR = true;
7974       MI->RemoveOperand(i);
7975       break;
7976     }
7977   }
7978   if (!definesCPSR) {
7979     assert(!NewOpc && "Optional cc_out operand required");
7980     return;
7981   }
7982   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7983   if (deadCPSR) {
7984     assert(!MI->getOperand(ccOutIdx).getReg() &&
7985            "expect uninitialized optional cc_out operand");
7986     return;
7987   }
7988
7989   // If this instruction was defined with an optional CPSR def and its dag node
7990   // had a live implicit CPSR def, then activate the optional CPSR def.
7991   MachineOperand &MO = MI->getOperand(ccOutIdx);
7992   MO.setReg(ARM::CPSR);
7993   MO.setIsDef(true);
7994 }
7995
7996 //===----------------------------------------------------------------------===//
7997 //                           ARM Optimization Hooks
7998 //===----------------------------------------------------------------------===//
7999
8000 // Helper function that checks if N is a null or all ones constant.
8001 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8002   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8003   if (!C)
8004     return false;
8005   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8006 }
8007
8008 // Return true if N is conditionally 0 or all ones.
8009 // Detects these expressions where cc is an i1 value:
8010 //
8011 //   (select cc 0, y)   [AllOnes=0]
8012 //   (select cc y, 0)   [AllOnes=0]
8013 //   (zext cc)          [AllOnes=0]
8014 //   (sext cc)          [AllOnes=0/1]
8015 //   (select cc -1, y)  [AllOnes=1]
8016 //   (select cc y, -1)  [AllOnes=1]
8017 //
8018 // Invert is set when N is the null/all ones constant when CC is false.
8019 // OtherOp is set to the alternative value of N.
8020 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8021                                        SDValue &CC, bool &Invert,
8022                                        SDValue &OtherOp,
8023                                        SelectionDAG &DAG) {
8024   switch (N->getOpcode()) {
8025   default: return false;
8026   case ISD::SELECT: {
8027     CC = N->getOperand(0);
8028     SDValue N1 = N->getOperand(1);
8029     SDValue N2 = N->getOperand(2);
8030     if (isZeroOrAllOnes(N1, AllOnes)) {
8031       Invert = false;
8032       OtherOp = N2;
8033       return true;
8034     }
8035     if (isZeroOrAllOnes(N2, AllOnes)) {
8036       Invert = true;
8037       OtherOp = N1;
8038       return true;
8039     }
8040     return false;
8041   }
8042   case ISD::ZERO_EXTEND:
8043     // (zext cc) can never be the all ones value.
8044     if (AllOnes)
8045       return false;
8046     // Fall through.
8047   case ISD::SIGN_EXTEND: {
8048     SDLoc dl(N);
8049     EVT VT = N->getValueType(0);
8050     CC = N->getOperand(0);
8051     if (CC.getValueType() != MVT::i1)
8052       return false;
8053     Invert = !AllOnes;
8054     if (AllOnes)
8055       // When looking for an AllOnes constant, N is an sext, and the 'other'
8056       // value is 0.
8057       OtherOp = DAG.getConstant(0, dl, VT);
8058     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8059       // When looking for a 0 constant, N can be zext or sext.
8060       OtherOp = DAG.getConstant(1, dl, VT);
8061     else
8062       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8063                                 VT);
8064     return true;
8065   }
8066   }
8067 }
8068
8069 // Combine a constant select operand into its use:
8070 //
8071 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8072 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8073 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8074 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8075 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8076 //
8077 // The transform is rejected if the select doesn't have a constant operand that
8078 // is null, or all ones when AllOnes is set.
8079 //
8080 // Also recognize sext/zext from i1:
8081 //
8082 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8083 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8084 //
8085 // These transformations eventually create predicated instructions.
8086 //
8087 // @param N       The node to transform.
8088 // @param Slct    The N operand that is a select.
8089 // @param OtherOp The other N operand (x above).
8090 // @param DCI     Context.
8091 // @param AllOnes Require the select constant to be all ones instead of null.
8092 // @returns The new node, or SDValue() on failure.
8093 static
8094 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8095                             TargetLowering::DAGCombinerInfo &DCI,
8096                             bool AllOnes = false) {
8097   SelectionDAG &DAG = DCI.DAG;
8098   EVT VT = N->getValueType(0);
8099   SDValue NonConstantVal;
8100   SDValue CCOp;
8101   bool SwapSelectOps;
8102   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8103                                   NonConstantVal, DAG))
8104     return SDValue();
8105
8106   // Slct is now know to be the desired identity constant when CC is true.
8107   SDValue TrueVal = OtherOp;
8108   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8109                                  OtherOp, NonConstantVal);
8110   // Unless SwapSelectOps says CC should be false.
8111   if (SwapSelectOps)
8112     std::swap(TrueVal, FalseVal);
8113
8114   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8115                      CCOp, TrueVal, FalseVal);
8116 }
8117
8118 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8119 static
8120 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8121                                        TargetLowering::DAGCombinerInfo &DCI) {
8122   SDValue N0 = N->getOperand(0);
8123   SDValue N1 = N->getOperand(1);
8124   if (N0.getNode()->hasOneUse()) {
8125     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8126     if (Result.getNode())
8127       return Result;
8128   }
8129   if (N1.getNode()->hasOneUse()) {
8130     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8131     if (Result.getNode())
8132       return Result;
8133   }
8134   return SDValue();
8135 }
8136
8137 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8138 // (only after legalization).
8139 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8140                                  TargetLowering::DAGCombinerInfo &DCI,
8141                                  const ARMSubtarget *Subtarget) {
8142
8143   // Only perform optimization if after legalize, and if NEON is available. We
8144   // also expected both operands to be BUILD_VECTORs.
8145   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8146       || N0.getOpcode() != ISD::BUILD_VECTOR
8147       || N1.getOpcode() != ISD::BUILD_VECTOR)
8148     return SDValue();
8149
8150   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8151   EVT VT = N->getValueType(0);
8152   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8153     return SDValue();
8154
8155   // Check that the vector operands are of the right form.
8156   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8157   // operands, where N is the size of the formed vector.
8158   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8159   // index such that we have a pair wise add pattern.
8160
8161   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8162   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8163     return SDValue();
8164   SDValue Vec = N0->getOperand(0)->getOperand(0);
8165   SDNode *V = Vec.getNode();
8166   unsigned nextIndex = 0;
8167
8168   // For each operands to the ADD which are BUILD_VECTORs,
8169   // check to see if each of their operands are an EXTRACT_VECTOR with
8170   // the same vector and appropriate index.
8171   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8172     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8173         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8174
8175       SDValue ExtVec0 = N0->getOperand(i);
8176       SDValue ExtVec1 = N1->getOperand(i);
8177
8178       // First operand is the vector, verify its the same.
8179       if (V != ExtVec0->getOperand(0).getNode() ||
8180           V != ExtVec1->getOperand(0).getNode())
8181         return SDValue();
8182
8183       // Second is the constant, verify its correct.
8184       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8185       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8186
8187       // For the constant, we want to see all the even or all the odd.
8188       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8189           || C1->getZExtValue() != nextIndex+1)
8190         return SDValue();
8191
8192       // Increment index.
8193       nextIndex+=2;
8194     } else
8195       return SDValue();
8196   }
8197
8198   // Create VPADDL node.
8199   SelectionDAG &DAG = DCI.DAG;
8200   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8201
8202   SDLoc dl(N);
8203
8204   // Build operand list.
8205   SmallVector<SDValue, 8> Ops;
8206   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8207                                 TLI.getPointerTy(DAG.getDataLayout())));
8208
8209   // Input is the vector.
8210   Ops.push_back(Vec);
8211
8212   // Get widened type and narrowed type.
8213   MVT widenType;
8214   unsigned numElem = VT.getVectorNumElements();
8215   
8216   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8217   switch (inputLaneType.getSimpleVT().SimpleTy) {
8218     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8219     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8220     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8221     default:
8222       llvm_unreachable("Invalid vector element type for padd optimization.");
8223   }
8224
8225   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8226   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8227   return DAG.getNode(ExtOp, dl, VT, tmp);
8228 }
8229
8230 static SDValue findMUL_LOHI(SDValue V) {
8231   if (V->getOpcode() == ISD::UMUL_LOHI ||
8232       V->getOpcode() == ISD::SMUL_LOHI)
8233     return V;
8234   return SDValue();
8235 }
8236
8237 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8238                                      TargetLowering::DAGCombinerInfo &DCI,
8239                                      const ARMSubtarget *Subtarget) {
8240
8241   if (Subtarget->isThumb1Only()) return SDValue();
8242
8243   // Only perform the checks after legalize when the pattern is available.
8244   if (DCI.isBeforeLegalize()) return SDValue();
8245
8246   // Look for multiply add opportunities.
8247   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8248   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8249   // a glue link from the first add to the second add.
8250   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8251   // a S/UMLAL instruction.
8252   //                  UMUL_LOHI
8253   //                 / :lo    \ :hi
8254   //                /          \          [no multiline comment]
8255   //    loAdd ->  ADDE         |
8256   //                 \ :glue  /
8257   //                  \      /
8258   //                    ADDC   <- hiAdd
8259   //
8260   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8261   SDValue AddcOp0 = AddcNode->getOperand(0);
8262   SDValue AddcOp1 = AddcNode->getOperand(1);
8263
8264   // Check if the two operands are from the same mul_lohi node.
8265   if (AddcOp0.getNode() == AddcOp1.getNode())
8266     return SDValue();
8267
8268   assert(AddcNode->getNumValues() == 2 &&
8269          AddcNode->getValueType(0) == MVT::i32 &&
8270          "Expect ADDC with two result values. First: i32");
8271
8272   // Check that we have a glued ADDC node.
8273   if (AddcNode->getValueType(1) != MVT::Glue)
8274     return SDValue();
8275
8276   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8277   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8278       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8279       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8280       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8281     return SDValue();
8282
8283   // Look for the glued ADDE.
8284   SDNode* AddeNode = AddcNode->getGluedUser();
8285   if (!AddeNode)
8286     return SDValue();
8287
8288   // Make sure it is really an ADDE.
8289   if (AddeNode->getOpcode() != ISD::ADDE)
8290     return SDValue();
8291
8292   assert(AddeNode->getNumOperands() == 3 &&
8293          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8294          "ADDE node has the wrong inputs");
8295
8296   // Check for the triangle shape.
8297   SDValue AddeOp0 = AddeNode->getOperand(0);
8298   SDValue AddeOp1 = AddeNode->getOperand(1);
8299
8300   // Make sure that the ADDE operands are not coming from the same node.
8301   if (AddeOp0.getNode() == AddeOp1.getNode())
8302     return SDValue();
8303
8304   // Find the MUL_LOHI node walking up ADDE's operands.
8305   bool IsLeftOperandMUL = false;
8306   SDValue MULOp = findMUL_LOHI(AddeOp0);
8307   if (MULOp == SDValue())
8308    MULOp = findMUL_LOHI(AddeOp1);
8309   else
8310     IsLeftOperandMUL = true;
8311   if (MULOp == SDValue())
8312     return SDValue();
8313
8314   // Figure out the right opcode.
8315   unsigned Opc = MULOp->getOpcode();
8316   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8317
8318   // Figure out the high and low input values to the MLAL node.
8319   SDValue* HiAdd = nullptr;
8320   SDValue* LoMul = nullptr;
8321   SDValue* LowAdd = nullptr;
8322
8323   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8324   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8325     return SDValue();
8326
8327   if (IsLeftOperandMUL)
8328     HiAdd = &AddeOp1;
8329   else
8330     HiAdd = &AddeOp0;
8331
8332
8333   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8334   // whose low result is fed to the ADDC we are checking.
8335
8336   if (AddcOp0 == MULOp.getValue(0)) {
8337     LoMul = &AddcOp0;
8338     LowAdd = &AddcOp1;
8339   }
8340   if (AddcOp1 == MULOp.getValue(0)) {
8341     LoMul = &AddcOp1;
8342     LowAdd = &AddcOp0;
8343   }
8344
8345   if (!LoMul)
8346     return SDValue();
8347
8348   // Create the merged node.
8349   SelectionDAG &DAG = DCI.DAG;
8350
8351   // Build operand list.
8352   SmallVector<SDValue, 8> Ops;
8353   Ops.push_back(LoMul->getOperand(0));
8354   Ops.push_back(LoMul->getOperand(1));
8355   Ops.push_back(*LowAdd);
8356   Ops.push_back(*HiAdd);
8357
8358   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8359                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8360
8361   // Replace the ADDs' nodes uses by the MLA node's values.
8362   SDValue HiMLALResult(MLALNode.getNode(), 1);
8363   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8364
8365   SDValue LoMLALResult(MLALNode.getNode(), 0);
8366   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8367
8368   // Return original node to notify the driver to stop replacing.
8369   SDValue resNode(AddcNode, 0);
8370   return resNode;
8371 }
8372
8373 /// PerformADDCCombine - Target-specific dag combine transform from
8374 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8375 static SDValue PerformADDCCombine(SDNode *N,
8376                                  TargetLowering::DAGCombinerInfo &DCI,
8377                                  const ARMSubtarget *Subtarget) {
8378
8379   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8380
8381 }
8382
8383 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8384 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8385 /// called with the default operands, and if that fails, with commuted
8386 /// operands.
8387 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8388                                           TargetLowering::DAGCombinerInfo &DCI,
8389                                           const ARMSubtarget *Subtarget){
8390
8391   // Attempt to create vpaddl for this add.
8392   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8393   if (Result.getNode())
8394     return Result;
8395
8396   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8397   if (N0.getNode()->hasOneUse()) {
8398     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8399     if (Result.getNode()) return Result;
8400   }
8401   return SDValue();
8402 }
8403
8404 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8405 ///
8406 static SDValue PerformADDCombine(SDNode *N,
8407                                  TargetLowering::DAGCombinerInfo &DCI,
8408                                  const ARMSubtarget *Subtarget) {
8409   SDValue N0 = N->getOperand(0);
8410   SDValue N1 = N->getOperand(1);
8411
8412   // First try with the default operand order.
8413   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8414   if (Result.getNode())
8415     return Result;
8416
8417   // If that didn't work, try again with the operands commuted.
8418   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8419 }
8420
8421 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8422 ///
8423 static SDValue PerformSUBCombine(SDNode *N,
8424                                  TargetLowering::DAGCombinerInfo &DCI) {
8425   SDValue N0 = N->getOperand(0);
8426   SDValue N1 = N->getOperand(1);
8427
8428   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8429   if (N1.getNode()->hasOneUse()) {
8430     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8431     if (Result.getNode()) return Result;
8432   }
8433
8434   return SDValue();
8435 }
8436
8437 /// PerformVMULCombine
8438 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8439 /// special multiplier accumulator forwarding.
8440 ///   vmul d3, d0, d2
8441 ///   vmla d3, d1, d2
8442 /// is faster than
8443 ///   vadd d3, d0, d1
8444 ///   vmul d3, d3, d2
8445 //  However, for (A + B) * (A + B),
8446 //    vadd d2, d0, d1
8447 //    vmul d3, d0, d2
8448 //    vmla d3, d1, d2
8449 //  is slower than
8450 //    vadd d2, d0, d1
8451 //    vmul d3, d2, d2
8452 static SDValue PerformVMULCombine(SDNode *N,
8453                                   TargetLowering::DAGCombinerInfo &DCI,
8454                                   const ARMSubtarget *Subtarget) {
8455   if (!Subtarget->hasVMLxForwarding())
8456     return SDValue();
8457
8458   SelectionDAG &DAG = DCI.DAG;
8459   SDValue N0 = N->getOperand(0);
8460   SDValue N1 = N->getOperand(1);
8461   unsigned Opcode = N0.getOpcode();
8462   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8463       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8464     Opcode = N1.getOpcode();
8465     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8466         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8467       return SDValue();
8468     std::swap(N0, N1);
8469   }
8470
8471   if (N0 == N1)
8472     return SDValue();
8473
8474   EVT VT = N->getValueType(0);
8475   SDLoc DL(N);
8476   SDValue N00 = N0->getOperand(0);
8477   SDValue N01 = N0->getOperand(1);
8478   return DAG.getNode(Opcode, DL, VT,
8479                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8480                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8481 }
8482
8483 static SDValue PerformMULCombine(SDNode *N,
8484                                  TargetLowering::DAGCombinerInfo &DCI,
8485                                  const ARMSubtarget *Subtarget) {
8486   SelectionDAG &DAG = DCI.DAG;
8487
8488   if (Subtarget->isThumb1Only())
8489     return SDValue();
8490
8491   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8492     return SDValue();
8493
8494   EVT VT = N->getValueType(0);
8495   if (VT.is64BitVector() || VT.is128BitVector())
8496     return PerformVMULCombine(N, DCI, Subtarget);
8497   if (VT != MVT::i32)
8498     return SDValue();
8499
8500   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8501   if (!C)
8502     return SDValue();
8503
8504   int64_t MulAmt = C->getSExtValue();
8505   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8506
8507   ShiftAmt = ShiftAmt & (32 - 1);
8508   SDValue V = N->getOperand(0);
8509   SDLoc DL(N);
8510
8511   SDValue Res;
8512   MulAmt >>= ShiftAmt;
8513
8514   if (MulAmt >= 0) {
8515     if (isPowerOf2_32(MulAmt - 1)) {
8516       // (mul x, 2^N + 1) => (add (shl x, N), x)
8517       Res = DAG.getNode(ISD::ADD, DL, VT,
8518                         V,
8519                         DAG.getNode(ISD::SHL, DL, VT,
8520                                     V,
8521                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8522                                                     MVT::i32)));
8523     } else if (isPowerOf2_32(MulAmt + 1)) {
8524       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8525       Res = DAG.getNode(ISD::SUB, DL, VT,
8526                         DAG.getNode(ISD::SHL, DL, VT,
8527                                     V,
8528                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8529                                                     MVT::i32)),
8530                         V);
8531     } else
8532       return SDValue();
8533   } else {
8534     uint64_t MulAmtAbs = -MulAmt;
8535     if (isPowerOf2_32(MulAmtAbs + 1)) {
8536       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8537       Res = DAG.getNode(ISD::SUB, DL, VT,
8538                         V,
8539                         DAG.getNode(ISD::SHL, DL, VT,
8540                                     V,
8541                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8542                                                     MVT::i32)));
8543     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8544       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8545       Res = DAG.getNode(ISD::ADD, DL, VT,
8546                         V,
8547                         DAG.getNode(ISD::SHL, DL, VT,
8548                                     V,
8549                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8550                                                     MVT::i32)));
8551       Res = DAG.getNode(ISD::SUB, DL, VT,
8552                         DAG.getConstant(0, DL, MVT::i32), Res);
8553
8554     } else
8555       return SDValue();
8556   }
8557
8558   if (ShiftAmt != 0)
8559     Res = DAG.getNode(ISD::SHL, DL, VT,
8560                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8561
8562   // Do not add new nodes to DAG combiner worklist.
8563   DCI.CombineTo(N, Res, false);
8564   return SDValue();
8565 }
8566
8567 static SDValue PerformANDCombine(SDNode *N,
8568                                  TargetLowering::DAGCombinerInfo &DCI,
8569                                  const ARMSubtarget *Subtarget) {
8570
8571   // Attempt to use immediate-form VBIC
8572   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8573   SDLoc dl(N);
8574   EVT VT = N->getValueType(0);
8575   SelectionDAG &DAG = DCI.DAG;
8576
8577   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8578     return SDValue();
8579
8580   APInt SplatBits, SplatUndef;
8581   unsigned SplatBitSize;
8582   bool HasAnyUndefs;
8583   if (BVN &&
8584       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8585     if (SplatBitSize <= 64) {
8586       EVT VbicVT;
8587       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8588                                       SplatUndef.getZExtValue(), SplatBitSize,
8589                                       DAG, dl, VbicVT, VT.is128BitVector(),
8590                                       OtherModImm);
8591       if (Val.getNode()) {
8592         SDValue Input =
8593           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8594         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8595         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8596       }
8597     }
8598   }
8599
8600   if (!Subtarget->isThumb1Only()) {
8601     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8602     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8603     if (Result.getNode())
8604       return Result;
8605   }
8606
8607   return SDValue();
8608 }
8609
8610 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8611 static SDValue PerformORCombine(SDNode *N,
8612                                 TargetLowering::DAGCombinerInfo &DCI,
8613                                 const ARMSubtarget *Subtarget) {
8614   // Attempt to use immediate-form VORR
8615   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8616   SDLoc dl(N);
8617   EVT VT = N->getValueType(0);
8618   SelectionDAG &DAG = DCI.DAG;
8619
8620   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8621     return SDValue();
8622
8623   APInt SplatBits, SplatUndef;
8624   unsigned SplatBitSize;
8625   bool HasAnyUndefs;
8626   if (BVN && Subtarget->hasNEON() &&
8627       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8628     if (SplatBitSize <= 64) {
8629       EVT VorrVT;
8630       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8631                                       SplatUndef.getZExtValue(), SplatBitSize,
8632                                       DAG, dl, VorrVT, VT.is128BitVector(),
8633                                       OtherModImm);
8634       if (Val.getNode()) {
8635         SDValue Input =
8636           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8637         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8638         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8639       }
8640     }
8641   }
8642
8643   if (!Subtarget->isThumb1Only()) {
8644     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8645     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8646     if (Result.getNode())
8647       return Result;
8648   }
8649
8650   // The code below optimizes (or (and X, Y), Z).
8651   // The AND operand needs to have a single user to make these optimizations
8652   // profitable.
8653   SDValue N0 = N->getOperand(0);
8654   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8655     return SDValue();
8656   SDValue N1 = N->getOperand(1);
8657
8658   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8659   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8660       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8661     APInt SplatUndef;
8662     unsigned SplatBitSize;
8663     bool HasAnyUndefs;
8664
8665     APInt SplatBits0, SplatBits1;
8666     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8667     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8668     // Ensure that the second operand of both ands are constants
8669     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8670                                       HasAnyUndefs) && !HasAnyUndefs) {
8671         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8672                                           HasAnyUndefs) && !HasAnyUndefs) {
8673             // Ensure that the bit width of the constants are the same and that
8674             // the splat arguments are logical inverses as per the pattern we
8675             // are trying to simplify.
8676             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8677                 SplatBits0 == ~SplatBits1) {
8678                 // Canonicalize the vector type to make instruction selection
8679                 // simpler.
8680                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8681                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8682                                              N0->getOperand(1),
8683                                              N0->getOperand(0),
8684                                              N1->getOperand(0));
8685                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8686             }
8687         }
8688     }
8689   }
8690
8691   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8692   // reasonable.
8693
8694   // BFI is only available on V6T2+
8695   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8696     return SDValue();
8697
8698   SDLoc DL(N);
8699   // 1) or (and A, mask), val => ARMbfi A, val, mask
8700   //      iff (val & mask) == val
8701   //
8702   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8703   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8704   //          && mask == ~mask2
8705   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8706   //          && ~mask == mask2
8707   //  (i.e., copy a bitfield value into another bitfield of the same width)
8708
8709   if (VT != MVT::i32)
8710     return SDValue();
8711
8712   SDValue N00 = N0.getOperand(0);
8713
8714   // The value and the mask need to be constants so we can verify this is
8715   // actually a bitfield set. If the mask is 0xffff, we can do better
8716   // via a movt instruction, so don't use BFI in that case.
8717   SDValue MaskOp = N0.getOperand(1);
8718   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8719   if (!MaskC)
8720     return SDValue();
8721   unsigned Mask = MaskC->getZExtValue();
8722   if (Mask == 0xffff)
8723     return SDValue();
8724   SDValue Res;
8725   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8726   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8727   if (N1C) {
8728     unsigned Val = N1C->getZExtValue();
8729     if ((Val & ~Mask) != Val)
8730       return SDValue();
8731
8732     if (ARM::isBitFieldInvertedMask(Mask)) {
8733       Val >>= countTrailingZeros(~Mask);
8734
8735       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8736                         DAG.getConstant(Val, DL, MVT::i32),
8737                         DAG.getConstant(Mask, DL, MVT::i32));
8738
8739       // Do not add new nodes to DAG combiner worklist.
8740       DCI.CombineTo(N, Res, false);
8741       return SDValue();
8742     }
8743   } else if (N1.getOpcode() == ISD::AND) {
8744     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8745     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8746     if (!N11C)
8747       return SDValue();
8748     unsigned Mask2 = N11C->getZExtValue();
8749
8750     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8751     // as is to match.
8752     if (ARM::isBitFieldInvertedMask(Mask) &&
8753         (Mask == ~Mask2)) {
8754       // The pack halfword instruction works better for masks that fit it,
8755       // so use that when it's available.
8756       if (Subtarget->hasT2ExtractPack() &&
8757           (Mask == 0xffff || Mask == 0xffff0000))
8758         return SDValue();
8759       // 2a
8760       unsigned amt = countTrailingZeros(Mask2);
8761       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8762                         DAG.getConstant(amt, DL, MVT::i32));
8763       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8764                         DAG.getConstant(Mask, DL, MVT::i32));
8765       // Do not add new nodes to DAG combiner worklist.
8766       DCI.CombineTo(N, Res, false);
8767       return SDValue();
8768     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8769                (~Mask == Mask2)) {
8770       // The pack halfword instruction works better for masks that fit it,
8771       // so use that when it's available.
8772       if (Subtarget->hasT2ExtractPack() &&
8773           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8774         return SDValue();
8775       // 2b
8776       unsigned lsb = countTrailingZeros(Mask);
8777       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8778                         DAG.getConstant(lsb, DL, MVT::i32));
8779       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8780                         DAG.getConstant(Mask2, DL, MVT::i32));
8781       // Do not add new nodes to DAG combiner worklist.
8782       DCI.CombineTo(N, Res, false);
8783       return SDValue();
8784     }
8785   }
8786
8787   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8788       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8789       ARM::isBitFieldInvertedMask(~Mask)) {
8790     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8791     // where lsb(mask) == #shamt and masked bits of B are known zero.
8792     SDValue ShAmt = N00.getOperand(1);
8793     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8794     unsigned LSB = countTrailingZeros(Mask);
8795     if (ShAmtC != LSB)
8796       return SDValue();
8797
8798     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8799                       DAG.getConstant(~Mask, DL, MVT::i32));
8800
8801     // Do not add new nodes to DAG combiner worklist.
8802     DCI.CombineTo(N, Res, false);
8803   }
8804
8805   return SDValue();
8806 }
8807
8808 static SDValue PerformXORCombine(SDNode *N,
8809                                  TargetLowering::DAGCombinerInfo &DCI,
8810                                  const ARMSubtarget *Subtarget) {
8811   EVT VT = N->getValueType(0);
8812   SelectionDAG &DAG = DCI.DAG;
8813
8814   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8815     return SDValue();
8816
8817   if (!Subtarget->isThumb1Only()) {
8818     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8819     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8820     if (Result.getNode())
8821       return Result;
8822   }
8823
8824   return SDValue();
8825 }
8826
8827 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8828 /// the bits being cleared by the AND are not demanded by the BFI.
8829 static SDValue PerformBFICombine(SDNode *N,
8830                                  TargetLowering::DAGCombinerInfo &DCI) {
8831   SDValue N1 = N->getOperand(1);
8832   if (N1.getOpcode() == ISD::AND) {
8833     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8834     if (!N11C)
8835       return SDValue();
8836     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8837     unsigned LSB = countTrailingZeros(~InvMask);
8838     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8839     assert(Width <
8840                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8841            "undefined behavior");
8842     unsigned Mask = (1u << Width) - 1;
8843     unsigned Mask2 = N11C->getZExtValue();
8844     if ((Mask & (~Mask2)) == 0)
8845       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8846                              N->getOperand(0), N1.getOperand(0),
8847                              N->getOperand(2));
8848   }
8849   return SDValue();
8850 }
8851
8852 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8853 /// ARMISD::VMOVRRD.
8854 static SDValue PerformVMOVRRDCombine(SDNode *N,
8855                                      TargetLowering::DAGCombinerInfo &DCI,
8856                                      const ARMSubtarget *Subtarget) {
8857   // vmovrrd(vmovdrr x, y) -> x,y
8858   SDValue InDouble = N->getOperand(0);
8859   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8860     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8861
8862   // vmovrrd(load f64) -> (load i32), (load i32)
8863   SDNode *InNode = InDouble.getNode();
8864   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8865       InNode->getValueType(0) == MVT::f64 &&
8866       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8867       !cast<LoadSDNode>(InNode)->isVolatile()) {
8868     // TODO: Should this be done for non-FrameIndex operands?
8869     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8870
8871     SelectionDAG &DAG = DCI.DAG;
8872     SDLoc DL(LD);
8873     SDValue BasePtr = LD->getBasePtr();
8874     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8875                                  LD->getPointerInfo(), LD->isVolatile(),
8876                                  LD->isNonTemporal(), LD->isInvariant(),
8877                                  LD->getAlignment());
8878
8879     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8880                                     DAG.getConstant(4, DL, MVT::i32));
8881     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8882                                  LD->getPointerInfo(), LD->isVolatile(),
8883                                  LD->isNonTemporal(), LD->isInvariant(),
8884                                  std::min(4U, LD->getAlignment() / 2));
8885
8886     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8887     if (DCI.DAG.getDataLayout().isBigEndian())
8888       std::swap (NewLD1, NewLD2);
8889     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8890     return Result;
8891   }
8892
8893   return SDValue();
8894 }
8895
8896 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8897 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8898 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8899   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8900   SDValue Op0 = N->getOperand(0);
8901   SDValue Op1 = N->getOperand(1);
8902   if (Op0.getOpcode() == ISD::BITCAST)
8903     Op0 = Op0.getOperand(0);
8904   if (Op1.getOpcode() == ISD::BITCAST)
8905     Op1 = Op1.getOperand(0);
8906   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8907       Op0.getNode() == Op1.getNode() &&
8908       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8909     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8910                        N->getValueType(0), Op0.getOperand(0));
8911   return SDValue();
8912 }
8913
8914 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8915 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8916 /// i64 vector to have f64 elements, since the value can then be loaded
8917 /// directly into a VFP register.
8918 static bool hasNormalLoadOperand(SDNode *N) {
8919   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8920   for (unsigned i = 0; i < NumElts; ++i) {
8921     SDNode *Elt = N->getOperand(i).getNode();
8922     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8923       return true;
8924   }
8925   return false;
8926 }
8927
8928 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8929 /// ISD::BUILD_VECTOR.
8930 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8931                                           TargetLowering::DAGCombinerInfo &DCI,
8932                                           const ARMSubtarget *Subtarget) {
8933   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8934   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8935   // into a pair of GPRs, which is fine when the value is used as a scalar,
8936   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8937   SelectionDAG &DAG = DCI.DAG;
8938   if (N->getNumOperands() == 2) {
8939     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8940     if (RV.getNode())
8941       return RV;
8942   }
8943
8944   // Load i64 elements as f64 values so that type legalization does not split
8945   // them up into i32 values.
8946   EVT VT = N->getValueType(0);
8947   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8948     return SDValue();
8949   SDLoc dl(N);
8950   SmallVector<SDValue, 8> Ops;
8951   unsigned NumElts = VT.getVectorNumElements();
8952   for (unsigned i = 0; i < NumElts; ++i) {
8953     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8954     Ops.push_back(V);
8955     // Make the DAGCombiner fold the bitcast.
8956     DCI.AddToWorklist(V.getNode());
8957   }
8958   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8959   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8960   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8961 }
8962
8963 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8964 static SDValue
8965 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8966   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8967   // At that time, we may have inserted bitcasts from integer to float.
8968   // If these bitcasts have survived DAGCombine, change the lowering of this
8969   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8970   // force to use floating point types.
8971
8972   // Make sure we can change the type of the vector.
8973   // This is possible iff:
8974   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8975   //    1.1. Vector is used only once.
8976   //    1.2. Use is a bit convert to an integer type.
8977   // 2. The size of its operands are 32-bits (64-bits are not legal).
8978   EVT VT = N->getValueType(0);
8979   EVT EltVT = VT.getVectorElementType();
8980
8981   // Check 1.1. and 2.
8982   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8983     return SDValue();
8984
8985   // By construction, the input type must be float.
8986   assert(EltVT == MVT::f32 && "Unexpected type!");
8987
8988   // Check 1.2.
8989   SDNode *Use = *N->use_begin();
8990   if (Use->getOpcode() != ISD::BITCAST ||
8991       Use->getValueType(0).isFloatingPoint())
8992     return SDValue();
8993
8994   // Check profitability.
8995   // Model is, if more than half of the relevant operands are bitcast from
8996   // i32, turn the build_vector into a sequence of insert_vector_elt.
8997   // Relevant operands are everything that is not statically
8998   // (i.e., at compile time) bitcasted.
8999   unsigned NumOfBitCastedElts = 0;
9000   unsigned NumElts = VT.getVectorNumElements();
9001   unsigned NumOfRelevantElts = NumElts;
9002   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9003     SDValue Elt = N->getOperand(Idx);
9004     if (Elt->getOpcode() == ISD::BITCAST) {
9005       // Assume only bit cast to i32 will go away.
9006       if (Elt->getOperand(0).getValueType() == MVT::i32)
9007         ++NumOfBitCastedElts;
9008     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9009       // Constants are statically casted, thus do not count them as
9010       // relevant operands.
9011       --NumOfRelevantElts;
9012   }
9013
9014   // Check if more than half of the elements require a non-free bitcast.
9015   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9016     return SDValue();
9017
9018   SelectionDAG &DAG = DCI.DAG;
9019   // Create the new vector type.
9020   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9021   // Check if the type is legal.
9022   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9023   if (!TLI.isTypeLegal(VecVT))
9024     return SDValue();
9025
9026   // Combine:
9027   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9028   // => BITCAST INSERT_VECTOR_ELT
9029   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9030   //                      (BITCAST EN), N.
9031   SDValue Vec = DAG.getUNDEF(VecVT);
9032   SDLoc dl(N);
9033   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9034     SDValue V = N->getOperand(Idx);
9035     if (V.getOpcode() == ISD::UNDEF)
9036       continue;
9037     if (V.getOpcode() == ISD::BITCAST &&
9038         V->getOperand(0).getValueType() == MVT::i32)
9039       // Fold obvious case.
9040       V = V.getOperand(0);
9041     else {
9042       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9043       // Make the DAGCombiner fold the bitcasts.
9044       DCI.AddToWorklist(V.getNode());
9045     }
9046     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9047     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9048   }
9049   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9050   // Make the DAGCombiner fold the bitcasts.
9051   DCI.AddToWorklist(Vec.getNode());
9052   return Vec;
9053 }
9054
9055 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9056 /// ISD::INSERT_VECTOR_ELT.
9057 static SDValue PerformInsertEltCombine(SDNode *N,
9058                                        TargetLowering::DAGCombinerInfo &DCI) {
9059   // Bitcast an i64 load inserted into a vector to f64.
9060   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9061   EVT VT = N->getValueType(0);
9062   SDNode *Elt = N->getOperand(1).getNode();
9063   if (VT.getVectorElementType() != MVT::i64 ||
9064       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9065     return SDValue();
9066
9067   SelectionDAG &DAG = DCI.DAG;
9068   SDLoc dl(N);
9069   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9070                                  VT.getVectorNumElements());
9071   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9072   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9073   // Make the DAGCombiner fold the bitcasts.
9074   DCI.AddToWorklist(Vec.getNode());
9075   DCI.AddToWorklist(V.getNode());
9076   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9077                                Vec, V, N->getOperand(2));
9078   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9079 }
9080
9081 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9082 /// ISD::VECTOR_SHUFFLE.
9083 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9084   // The LLVM shufflevector instruction does not require the shuffle mask
9085   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9086   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9087   // operands do not match the mask length, they are extended by concatenating
9088   // them with undef vectors.  That is probably the right thing for other
9089   // targets, but for NEON it is better to concatenate two double-register
9090   // size vector operands into a single quad-register size vector.  Do that
9091   // transformation here:
9092   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9093   //   shuffle(concat(v1, v2), undef)
9094   SDValue Op0 = N->getOperand(0);
9095   SDValue Op1 = N->getOperand(1);
9096   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9097       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9098       Op0.getNumOperands() != 2 ||
9099       Op1.getNumOperands() != 2)
9100     return SDValue();
9101   SDValue Concat0Op1 = Op0.getOperand(1);
9102   SDValue Concat1Op1 = Op1.getOperand(1);
9103   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9104       Concat1Op1.getOpcode() != ISD::UNDEF)
9105     return SDValue();
9106   // Skip the transformation if any of the types are illegal.
9107   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9108   EVT VT = N->getValueType(0);
9109   if (!TLI.isTypeLegal(VT) ||
9110       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9111       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9112     return SDValue();
9113
9114   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9115                                   Op0.getOperand(0), Op1.getOperand(0));
9116   // Translate the shuffle mask.
9117   SmallVector<int, 16> NewMask;
9118   unsigned NumElts = VT.getVectorNumElements();
9119   unsigned HalfElts = NumElts/2;
9120   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9121   for (unsigned n = 0; n < NumElts; ++n) {
9122     int MaskElt = SVN->getMaskElt(n);
9123     int NewElt = -1;
9124     if (MaskElt < (int)HalfElts)
9125       NewElt = MaskElt;
9126     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9127       NewElt = HalfElts + MaskElt - NumElts;
9128     NewMask.push_back(NewElt);
9129   }
9130   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9131                               DAG.getUNDEF(VT), NewMask.data());
9132 }
9133
9134 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9135 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9136 /// base address updates.
9137 /// For generic load/stores, the memory type is assumed to be a vector.
9138 /// The caller is assumed to have checked legality.
9139 static SDValue CombineBaseUpdate(SDNode *N,
9140                                  TargetLowering::DAGCombinerInfo &DCI) {
9141   SelectionDAG &DAG = DCI.DAG;
9142   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9143                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9144   const bool isStore = N->getOpcode() == ISD::STORE;
9145   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9146   SDValue Addr = N->getOperand(AddrOpIdx);
9147   MemSDNode *MemN = cast<MemSDNode>(N);
9148   SDLoc dl(N);
9149
9150   // Search for a use of the address operand that is an increment.
9151   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9152          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9153     SDNode *User = *UI;
9154     if (User->getOpcode() != ISD::ADD ||
9155         UI.getUse().getResNo() != Addr.getResNo())
9156       continue;
9157
9158     // Check that the add is independent of the load/store.  Otherwise, folding
9159     // it would create a cycle.
9160     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9161       continue;
9162
9163     // Find the new opcode for the updating load/store.
9164     bool isLoadOp = true;
9165     bool isLaneOp = false;
9166     unsigned NewOpc = 0;
9167     unsigned NumVecs = 0;
9168     if (isIntrinsic) {
9169       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9170       switch (IntNo) {
9171       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9172       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9173         NumVecs = 1; break;
9174       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9175         NumVecs = 2; break;
9176       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9177         NumVecs = 3; break;
9178       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9179         NumVecs = 4; break;
9180       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9181         NumVecs = 2; isLaneOp = true; break;
9182       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9183         NumVecs = 3; isLaneOp = true; break;
9184       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9185         NumVecs = 4; isLaneOp = true; break;
9186       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9187         NumVecs = 1; isLoadOp = false; break;
9188       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9189         NumVecs = 2; isLoadOp = false; break;
9190       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9191         NumVecs = 3; isLoadOp = false; break;
9192       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9193         NumVecs = 4; isLoadOp = false; break;
9194       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9195         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9196       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9197         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9198       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9199         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9200       }
9201     } else {
9202       isLaneOp = true;
9203       switch (N->getOpcode()) {
9204       default: llvm_unreachable("unexpected opcode for Neon base update");
9205       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9206       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9207       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9208       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9209         NumVecs = 1; isLaneOp = false; break;
9210       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9211         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9212       }
9213     }
9214
9215     // Find the size of memory referenced by the load/store.
9216     EVT VecTy;
9217     if (isLoadOp) {
9218       VecTy = N->getValueType(0);
9219     } else if (isIntrinsic) {
9220       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9221     } else {
9222       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9223       VecTy = N->getOperand(1).getValueType();
9224     }
9225
9226     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9227     if (isLaneOp)
9228       NumBytes /= VecTy.getVectorNumElements();
9229
9230     // If the increment is a constant, it must match the memory ref size.
9231     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9232     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9233       uint64_t IncVal = CInc->getZExtValue();
9234       if (IncVal != NumBytes)
9235         continue;
9236     } else if (NumBytes >= 3 * 16) {
9237       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9238       // separate instructions that make it harder to use a non-constant update.
9239       continue;
9240     }
9241
9242     // OK, we found an ADD we can fold into the base update.
9243     // Now, create a _UPD node, taking care of not breaking alignment.
9244
9245     EVT AlignedVecTy = VecTy;
9246     unsigned Alignment = MemN->getAlignment();
9247
9248     // If this is a less-than-standard-aligned load/store, change the type to
9249     // match the standard alignment.
9250     // The alignment is overlooked when selecting _UPD variants; and it's
9251     // easier to introduce bitcasts here than fix that.
9252     // There are 3 ways to get to this base-update combine:
9253     // - intrinsics: they are assumed to be properly aligned (to the standard
9254     //   alignment of the memory type), so we don't need to do anything.
9255     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9256     //   intrinsics, so, likewise, there's nothing to do.
9257     // - generic load/store instructions: the alignment is specified as an
9258     //   explicit operand, rather than implicitly as the standard alignment
9259     //   of the memory type (like the intrisics).  We need to change the
9260     //   memory type to match the explicit alignment.  That way, we don't
9261     //   generate non-standard-aligned ARMISD::VLDx nodes.
9262     if (isa<LSBaseSDNode>(N)) {
9263       if (Alignment == 0)
9264         Alignment = 1;
9265       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9266         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9267         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9268         assert(!isLaneOp && "Unexpected generic load/store lane.");
9269         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9270         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9271       }
9272       // Don't set an explicit alignment on regular load/stores that we want
9273       // to transform to VLD/VST 1_UPD nodes.
9274       // This matches the behavior of regular load/stores, which only get an
9275       // explicit alignment if the MMO alignment is larger than the standard
9276       // alignment of the memory type.
9277       // Intrinsics, however, always get an explicit alignment, set to the
9278       // alignment of the MMO.
9279       Alignment = 1;
9280     }
9281
9282     // Create the new updating load/store node.
9283     // First, create an SDVTList for the new updating node's results.
9284     EVT Tys[6];
9285     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9286     unsigned n;
9287     for (n = 0; n < NumResultVecs; ++n)
9288       Tys[n] = AlignedVecTy;
9289     Tys[n++] = MVT::i32;
9290     Tys[n] = MVT::Other;
9291     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9292
9293     // Then, gather the new node's operands.
9294     SmallVector<SDValue, 8> Ops;
9295     Ops.push_back(N->getOperand(0)); // incoming chain
9296     Ops.push_back(N->getOperand(AddrOpIdx));
9297     Ops.push_back(Inc);
9298
9299     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9300       // Try to match the intrinsic's signature
9301       Ops.push_back(StN->getValue());
9302     } else {
9303       // Loads (and of course intrinsics) match the intrinsics' signature,
9304       // so just add all but the alignment operand.
9305       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9306         Ops.push_back(N->getOperand(i));
9307     }
9308
9309     // For all node types, the alignment operand is always the last one.
9310     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9311
9312     // If this is a non-standard-aligned STORE, the penultimate operand is the
9313     // stored value.  Bitcast it to the aligned type.
9314     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9315       SDValue &StVal = Ops[Ops.size()-2];
9316       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9317     }
9318
9319     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9320                                            Ops, AlignedVecTy,
9321                                            MemN->getMemOperand());
9322
9323     // Update the uses.
9324     SmallVector<SDValue, 5> NewResults;
9325     for (unsigned i = 0; i < NumResultVecs; ++i)
9326       NewResults.push_back(SDValue(UpdN.getNode(), i));
9327
9328     // If this is an non-standard-aligned LOAD, the first result is the loaded
9329     // value.  Bitcast it to the expected result type.
9330     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9331       SDValue &LdVal = NewResults[0];
9332       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9333     }
9334
9335     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9336     DCI.CombineTo(N, NewResults);
9337     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9338
9339     break;
9340   }
9341   return SDValue();
9342 }
9343
9344 static SDValue PerformVLDCombine(SDNode *N,
9345                                  TargetLowering::DAGCombinerInfo &DCI) {
9346   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9347     return SDValue();
9348
9349   return CombineBaseUpdate(N, DCI);
9350 }
9351
9352 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9353 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9354 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9355 /// return true.
9356 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9357   SelectionDAG &DAG = DCI.DAG;
9358   EVT VT = N->getValueType(0);
9359   // vldN-dup instructions only support 64-bit vectors for N > 1.
9360   if (!VT.is64BitVector())
9361     return false;
9362
9363   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9364   SDNode *VLD = N->getOperand(0).getNode();
9365   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9366     return false;
9367   unsigned NumVecs = 0;
9368   unsigned NewOpc = 0;
9369   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9370   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9371     NumVecs = 2;
9372     NewOpc = ARMISD::VLD2DUP;
9373   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9374     NumVecs = 3;
9375     NewOpc = ARMISD::VLD3DUP;
9376   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9377     NumVecs = 4;
9378     NewOpc = ARMISD::VLD4DUP;
9379   } else {
9380     return false;
9381   }
9382
9383   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9384   // numbers match the load.
9385   unsigned VLDLaneNo =
9386     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9387   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9388        UI != UE; ++UI) {
9389     // Ignore uses of the chain result.
9390     if (UI.getUse().getResNo() == NumVecs)
9391       continue;
9392     SDNode *User = *UI;
9393     if (User->getOpcode() != ARMISD::VDUPLANE ||
9394         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9395       return false;
9396   }
9397
9398   // Create the vldN-dup node.
9399   EVT Tys[5];
9400   unsigned n;
9401   for (n = 0; n < NumVecs; ++n)
9402     Tys[n] = VT;
9403   Tys[n] = MVT::Other;
9404   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9405   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9406   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9407   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9408                                            Ops, VLDMemInt->getMemoryVT(),
9409                                            VLDMemInt->getMemOperand());
9410
9411   // Update the uses.
9412   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9413        UI != UE; ++UI) {
9414     unsigned ResNo = UI.getUse().getResNo();
9415     // Ignore uses of the chain result.
9416     if (ResNo == NumVecs)
9417       continue;
9418     SDNode *User = *UI;
9419     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9420   }
9421
9422   // Now the vldN-lane intrinsic is dead except for its chain result.
9423   // Update uses of the chain.
9424   std::vector<SDValue> VLDDupResults;
9425   for (unsigned n = 0; n < NumVecs; ++n)
9426     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9427   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9428   DCI.CombineTo(VLD, VLDDupResults);
9429
9430   return true;
9431 }
9432
9433 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9434 /// ARMISD::VDUPLANE.
9435 static SDValue PerformVDUPLANECombine(SDNode *N,
9436                                       TargetLowering::DAGCombinerInfo &DCI) {
9437   SDValue Op = N->getOperand(0);
9438
9439   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9440   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9441   if (CombineVLDDUP(N, DCI))
9442     return SDValue(N, 0);
9443
9444   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9445   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9446   while (Op.getOpcode() == ISD::BITCAST)
9447     Op = Op.getOperand(0);
9448   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9449     return SDValue();
9450
9451   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9452   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9453   // The canonical VMOV for a zero vector uses a 32-bit element size.
9454   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9455   unsigned EltBits;
9456   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9457     EltSize = 8;
9458   EVT VT = N->getValueType(0);
9459   if (EltSize > VT.getVectorElementType().getSizeInBits())
9460     return SDValue();
9461
9462   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9463 }
9464
9465 static SDValue PerformLOADCombine(SDNode *N,
9466                                   TargetLowering::DAGCombinerInfo &DCI) {
9467   EVT VT = N->getValueType(0);
9468
9469   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9470   if (ISD::isNormalLoad(N) && VT.isVector() &&
9471       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9472     return CombineBaseUpdate(N, DCI);
9473
9474   return SDValue();
9475 }
9476
9477 /// PerformSTORECombine - Target-specific dag combine xforms for
9478 /// ISD::STORE.
9479 static SDValue PerformSTORECombine(SDNode *N,
9480                                    TargetLowering::DAGCombinerInfo &DCI) {
9481   StoreSDNode *St = cast<StoreSDNode>(N);
9482   if (St->isVolatile())
9483     return SDValue();
9484
9485   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9486   // pack all of the elements in one place.  Next, store to memory in fewer
9487   // chunks.
9488   SDValue StVal = St->getValue();
9489   EVT VT = StVal.getValueType();
9490   if (St->isTruncatingStore() && VT.isVector()) {
9491     SelectionDAG &DAG = DCI.DAG;
9492     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9493     EVT StVT = St->getMemoryVT();
9494     unsigned NumElems = VT.getVectorNumElements();
9495     assert(StVT != VT && "Cannot truncate to the same type");
9496     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9497     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9498
9499     // From, To sizes and ElemCount must be pow of two
9500     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9501
9502     // We are going to use the original vector elt for storing.
9503     // Accumulated smaller vector elements must be a multiple of the store size.
9504     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9505
9506     unsigned SizeRatio  = FromEltSz / ToEltSz;
9507     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9508
9509     // Create a type on which we perform the shuffle.
9510     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9511                                      NumElems*SizeRatio);
9512     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9513
9514     SDLoc DL(St);
9515     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9516     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9517     for (unsigned i = 0; i < NumElems; ++i)
9518       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9519                           ? (i + 1) * SizeRatio - 1
9520                           : i * SizeRatio;
9521
9522     // Can't shuffle using an illegal type.
9523     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9524
9525     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9526                                 DAG.getUNDEF(WideVec.getValueType()),
9527                                 ShuffleVec.data());
9528     // At this point all of the data is stored at the bottom of the
9529     // register. We now need to save it to mem.
9530
9531     // Find the largest store unit
9532     MVT StoreType = MVT::i8;
9533     for (MVT Tp : MVT::integer_valuetypes()) {
9534       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9535         StoreType = Tp;
9536     }
9537     // Didn't find a legal store type.
9538     if (!TLI.isTypeLegal(StoreType))
9539       return SDValue();
9540
9541     // Bitcast the original vector into a vector of store-size units
9542     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9543             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9544     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9545     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9546     SmallVector<SDValue, 8> Chains;
9547     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9548                                         TLI.getPointerTy(DAG.getDataLayout()));
9549     SDValue BasePtr = St->getBasePtr();
9550
9551     // Perform one or more big stores into memory.
9552     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9553     for (unsigned I = 0; I < E; I++) {
9554       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9555                                    StoreType, ShuffWide,
9556                                    DAG.getIntPtrConstant(I, DL));
9557       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9558                                 St->getPointerInfo(), St->isVolatile(),
9559                                 St->isNonTemporal(), St->getAlignment());
9560       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9561                             Increment);
9562       Chains.push_back(Ch);
9563     }
9564     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9565   }
9566
9567   if (!ISD::isNormalStore(St))
9568     return SDValue();
9569
9570   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9571   // ARM stores of arguments in the same cache line.
9572   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9573       StVal.getNode()->hasOneUse()) {
9574     SelectionDAG  &DAG = DCI.DAG;
9575     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9576     SDLoc DL(St);
9577     SDValue BasePtr = St->getBasePtr();
9578     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9579                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9580                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9581                                   St->isNonTemporal(), St->getAlignment());
9582
9583     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9584                                     DAG.getConstant(4, DL, MVT::i32));
9585     return DAG.getStore(NewST1.getValue(0), DL,
9586                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9587                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9588                         St->isNonTemporal(),
9589                         std::min(4U, St->getAlignment() / 2));
9590   }
9591
9592   if (StVal.getValueType() == MVT::i64 &&
9593       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9594
9595     // Bitcast an i64 store extracted from a vector to f64.
9596     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9597     SelectionDAG &DAG = DCI.DAG;
9598     SDLoc dl(StVal);
9599     SDValue IntVec = StVal.getOperand(0);
9600     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9601                                    IntVec.getValueType().getVectorNumElements());
9602     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9603     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9604                                  Vec, StVal.getOperand(1));
9605     dl = SDLoc(N);
9606     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9607     // Make the DAGCombiner fold the bitcasts.
9608     DCI.AddToWorklist(Vec.getNode());
9609     DCI.AddToWorklist(ExtElt.getNode());
9610     DCI.AddToWorklist(V.getNode());
9611     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9612                         St->getPointerInfo(), St->isVolatile(),
9613                         St->isNonTemporal(), St->getAlignment(),
9614                         St->getAAInfo());
9615   }
9616
9617   // If this is a legal vector store, try to combine it into a VST1_UPD.
9618   if (ISD::isNormalStore(N) && VT.isVector() &&
9619       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9620     return CombineBaseUpdate(N, DCI);
9621
9622   return SDValue();
9623 }
9624
9625 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9626 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9627 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9628 {
9629   integerPart cN;
9630   integerPart c0 = 0;
9631   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9632        I != E; I++) {
9633     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9634     if (!C)
9635       return false;
9636
9637     bool isExact;
9638     APFloat APF = C->getValueAPF();
9639     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9640         != APFloat::opOK || !isExact)
9641       return false;
9642
9643     c0 = (I == 0) ? cN : c0;
9644     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9645       return false;
9646   }
9647   C = c0;
9648   return true;
9649 }
9650
9651 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9652 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9653 /// when the VMUL has a constant operand that is a power of 2.
9654 ///
9655 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9656 ///  vmul.f32        d16, d17, d16
9657 ///  vcvt.s32.f32    d16, d16
9658 /// becomes:
9659 ///  vcvt.s32.f32    d16, d16, #3
9660 static SDValue PerformVCVTCombine(SDNode *N,
9661                                   TargetLowering::DAGCombinerInfo &DCI,
9662                                   const ARMSubtarget *Subtarget) {
9663   SelectionDAG &DAG = DCI.DAG;
9664   SDValue Op = N->getOperand(0);
9665
9666   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9667       Op.getOpcode() != ISD::FMUL)
9668     return SDValue();
9669
9670   uint64_t C;
9671   SDValue N0 = Op->getOperand(0);
9672   SDValue ConstVec = Op->getOperand(1);
9673   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9674
9675   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9676       !isConstVecPow2(ConstVec, isSigned, C))
9677     return SDValue();
9678
9679   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9680   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9681   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9682   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9683       NumLanes > 4) {
9684     // These instructions only exist converting from f32 to i32. We can handle
9685     // smaller integers by generating an extra truncate, but larger ones would
9686     // be lossy. We also can't handle more then 4 lanes, since these intructions
9687     // only support v2i32/v4i32 types.
9688     return SDValue();
9689   }
9690
9691   SDLoc dl(N);
9692   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9693     Intrinsic::arm_neon_vcvtfp2fxu;
9694   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9695                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9696                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9697                                  N0,
9698                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9699
9700   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9701     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9702
9703   return FixConv;
9704 }
9705
9706 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9707 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9708 /// when the VDIV has a constant operand that is a power of 2.
9709 ///
9710 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9711 ///  vcvt.f32.s32    d16, d16
9712 ///  vdiv.f32        d16, d17, d16
9713 /// becomes:
9714 ///  vcvt.f32.s32    d16, d16, #3
9715 static SDValue PerformVDIVCombine(SDNode *N,
9716                                   TargetLowering::DAGCombinerInfo &DCI,
9717                                   const ARMSubtarget *Subtarget) {
9718   SelectionDAG &DAG = DCI.DAG;
9719   SDValue Op = N->getOperand(0);
9720   unsigned OpOpcode = Op.getNode()->getOpcode();
9721
9722   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9723       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9724     return SDValue();
9725
9726   uint64_t C;
9727   SDValue ConstVec = N->getOperand(1);
9728   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9729
9730   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9731       !isConstVecPow2(ConstVec, isSigned, C))
9732     return SDValue();
9733
9734   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9735   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9736   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9737     // These instructions only exist converting from i32 to f32. We can handle
9738     // smaller integers by generating an extra extend, but larger ones would
9739     // be lossy.
9740     return SDValue();
9741   }
9742
9743   SDLoc dl(N);
9744   SDValue ConvInput = Op.getOperand(0);
9745   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9746   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9747     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9748                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9749                             ConvInput);
9750
9751   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9752     Intrinsic::arm_neon_vcvtfxu2fp;
9753   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9754                      Op.getValueType(),
9755                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9756                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9757 }
9758
9759 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9760 /// operand of a vector shift operation, where all the elements of the
9761 /// build_vector must have the same constant integer value.
9762 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9763   // Ignore bit_converts.
9764   while (Op.getOpcode() == ISD::BITCAST)
9765     Op = Op.getOperand(0);
9766   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9767   APInt SplatBits, SplatUndef;
9768   unsigned SplatBitSize;
9769   bool HasAnyUndefs;
9770   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9771                                       HasAnyUndefs, ElementBits) ||
9772       SplatBitSize > ElementBits)
9773     return false;
9774   Cnt = SplatBits.getSExtValue();
9775   return true;
9776 }
9777
9778 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9779 /// operand of a vector shift left operation.  That value must be in the range:
9780 ///   0 <= Value < ElementBits for a left shift; or
9781 ///   0 <= Value <= ElementBits for a long left shift.
9782 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9783   assert(VT.isVector() && "vector shift count is not a vector type");
9784   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9785   if (! getVShiftImm(Op, ElementBits, Cnt))
9786     return false;
9787   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9788 }
9789
9790 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9791 /// operand of a vector shift right operation.  For a shift opcode, the value
9792 /// is positive, but for an intrinsic the value count must be negative. The
9793 /// absolute value must be in the range:
9794 ///   1 <= |Value| <= ElementBits for a right shift; or
9795 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9796 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9797                          int64_t &Cnt) {
9798   assert(VT.isVector() && "vector shift count is not a vector type");
9799   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9800   if (! getVShiftImm(Op, ElementBits, Cnt))
9801     return false;
9802   if (!isIntrinsic)
9803     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9804   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9805     Cnt = -Cnt;
9806     return true;
9807   }
9808   return false;
9809 }
9810
9811 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9812 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9813   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9814   switch (IntNo) {
9815   default:
9816     // Don't do anything for most intrinsics.
9817     break;
9818
9819   case Intrinsic::arm_neon_vabds:
9820     if (!N->getValueType(0).isInteger())
9821       return SDValue();
9822     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9823                        N->getOperand(1), N->getOperand(2));
9824   case Intrinsic::arm_neon_vabdu:
9825     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9826                        N->getOperand(1), N->getOperand(2));
9827
9828   // Vector shifts: check for immediate versions and lower them.
9829   // Note: This is done during DAG combining instead of DAG legalizing because
9830   // the build_vectors for 64-bit vector element shift counts are generally
9831   // not legal, and it is hard to see their values after they get legalized to
9832   // loads from a constant pool.
9833   case Intrinsic::arm_neon_vshifts:
9834   case Intrinsic::arm_neon_vshiftu:
9835   case Intrinsic::arm_neon_vrshifts:
9836   case Intrinsic::arm_neon_vrshiftu:
9837   case Intrinsic::arm_neon_vrshiftn:
9838   case Intrinsic::arm_neon_vqshifts:
9839   case Intrinsic::arm_neon_vqshiftu:
9840   case Intrinsic::arm_neon_vqshiftsu:
9841   case Intrinsic::arm_neon_vqshiftns:
9842   case Intrinsic::arm_neon_vqshiftnu:
9843   case Intrinsic::arm_neon_vqshiftnsu:
9844   case Intrinsic::arm_neon_vqrshiftns:
9845   case Intrinsic::arm_neon_vqrshiftnu:
9846   case Intrinsic::arm_neon_vqrshiftnsu: {
9847     EVT VT = N->getOperand(1).getValueType();
9848     int64_t Cnt;
9849     unsigned VShiftOpc = 0;
9850
9851     switch (IntNo) {
9852     case Intrinsic::arm_neon_vshifts:
9853     case Intrinsic::arm_neon_vshiftu:
9854       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9855         VShiftOpc = ARMISD::VSHL;
9856         break;
9857       }
9858       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9859         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9860                      ARMISD::VSHRs : ARMISD::VSHRu);
9861         break;
9862       }
9863       return SDValue();
9864
9865     case Intrinsic::arm_neon_vrshifts:
9866     case Intrinsic::arm_neon_vrshiftu:
9867       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9868         break;
9869       return SDValue();
9870
9871     case Intrinsic::arm_neon_vqshifts:
9872     case Intrinsic::arm_neon_vqshiftu:
9873       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9874         break;
9875       return SDValue();
9876
9877     case Intrinsic::arm_neon_vqshiftsu:
9878       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9879         break;
9880       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9881
9882     case Intrinsic::arm_neon_vrshiftn:
9883     case Intrinsic::arm_neon_vqshiftns:
9884     case Intrinsic::arm_neon_vqshiftnu:
9885     case Intrinsic::arm_neon_vqshiftnsu:
9886     case Intrinsic::arm_neon_vqrshiftns:
9887     case Intrinsic::arm_neon_vqrshiftnu:
9888     case Intrinsic::arm_neon_vqrshiftnsu:
9889       // Narrowing shifts require an immediate right shift.
9890       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9891         break;
9892       llvm_unreachable("invalid shift count for narrowing vector shift "
9893                        "intrinsic");
9894
9895     default:
9896       llvm_unreachable("unhandled vector shift");
9897     }
9898
9899     switch (IntNo) {
9900     case Intrinsic::arm_neon_vshifts:
9901     case Intrinsic::arm_neon_vshiftu:
9902       // Opcode already set above.
9903       break;
9904     case Intrinsic::arm_neon_vrshifts:
9905       VShiftOpc = ARMISD::VRSHRs; break;
9906     case Intrinsic::arm_neon_vrshiftu:
9907       VShiftOpc = ARMISD::VRSHRu; break;
9908     case Intrinsic::arm_neon_vrshiftn:
9909       VShiftOpc = ARMISD::VRSHRN; break;
9910     case Intrinsic::arm_neon_vqshifts:
9911       VShiftOpc = ARMISD::VQSHLs; break;
9912     case Intrinsic::arm_neon_vqshiftu:
9913       VShiftOpc = ARMISD::VQSHLu; break;
9914     case Intrinsic::arm_neon_vqshiftsu:
9915       VShiftOpc = ARMISD::VQSHLsu; break;
9916     case Intrinsic::arm_neon_vqshiftns:
9917       VShiftOpc = ARMISD::VQSHRNs; break;
9918     case Intrinsic::arm_neon_vqshiftnu:
9919       VShiftOpc = ARMISD::VQSHRNu; break;
9920     case Intrinsic::arm_neon_vqshiftnsu:
9921       VShiftOpc = ARMISD::VQSHRNsu; break;
9922     case Intrinsic::arm_neon_vqrshiftns:
9923       VShiftOpc = ARMISD::VQRSHRNs; break;
9924     case Intrinsic::arm_neon_vqrshiftnu:
9925       VShiftOpc = ARMISD::VQRSHRNu; break;
9926     case Intrinsic::arm_neon_vqrshiftnsu:
9927       VShiftOpc = ARMISD::VQRSHRNsu; break;
9928     }
9929
9930     SDLoc dl(N);
9931     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9932                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9933   }
9934
9935   case Intrinsic::arm_neon_vshiftins: {
9936     EVT VT = N->getOperand(1).getValueType();
9937     int64_t Cnt;
9938     unsigned VShiftOpc = 0;
9939
9940     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9941       VShiftOpc = ARMISD::VSLI;
9942     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9943       VShiftOpc = ARMISD::VSRI;
9944     else {
9945       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9946     }
9947
9948     SDLoc dl(N);
9949     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9950                        N->getOperand(1), N->getOperand(2),
9951                        DAG.getConstant(Cnt, dl, MVT::i32));
9952   }
9953
9954   case Intrinsic::arm_neon_vqrshifts:
9955   case Intrinsic::arm_neon_vqrshiftu:
9956     // No immediate versions of these to check for.
9957     break;
9958   }
9959
9960   return SDValue();
9961 }
9962
9963 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9964 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9965 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9966 /// vector element shift counts are generally not legal, and it is hard to see
9967 /// their values after they get legalized to loads from a constant pool.
9968 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9969                                    const ARMSubtarget *ST) {
9970   EVT VT = N->getValueType(0);
9971   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9972     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9973     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9974     SDValue N1 = N->getOperand(1);
9975     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9976       SDValue N0 = N->getOperand(0);
9977       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9978           DAG.MaskedValueIsZero(N0.getOperand(0),
9979                                 APInt::getHighBitsSet(32, 16)))
9980         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9981     }
9982   }
9983
9984   // Nothing to be done for scalar shifts.
9985   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9986   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9987     return SDValue();
9988
9989   assert(ST->hasNEON() && "unexpected vector shift");
9990   int64_t Cnt;
9991
9992   switch (N->getOpcode()) {
9993   default: llvm_unreachable("unexpected shift opcode");
9994
9995   case ISD::SHL:
9996     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
9997       SDLoc dl(N);
9998       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
9999                          DAG.getConstant(Cnt, dl, MVT::i32));
10000     }
10001     break;
10002
10003   case ISD::SRA:
10004   case ISD::SRL:
10005     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10006       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10007                             ARMISD::VSHRs : ARMISD::VSHRu);
10008       SDLoc dl(N);
10009       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10010                          DAG.getConstant(Cnt, dl, MVT::i32));
10011     }
10012   }
10013   return SDValue();
10014 }
10015
10016 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10017 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10018 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10019                                     const ARMSubtarget *ST) {
10020   SDValue N0 = N->getOperand(0);
10021
10022   // Check for sign- and zero-extensions of vector extract operations of 8-
10023   // and 16-bit vector elements.  NEON supports these directly.  They are
10024   // handled during DAG combining because type legalization will promote them
10025   // to 32-bit types and it is messy to recognize the operations after that.
10026   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10027     SDValue Vec = N0.getOperand(0);
10028     SDValue Lane = N0.getOperand(1);
10029     EVT VT = N->getValueType(0);
10030     EVT EltVT = N0.getValueType();
10031     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10032
10033     if (VT == MVT::i32 &&
10034         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10035         TLI.isTypeLegal(Vec.getValueType()) &&
10036         isa<ConstantSDNode>(Lane)) {
10037
10038       unsigned Opc = 0;
10039       switch (N->getOpcode()) {
10040       default: llvm_unreachable("unexpected opcode");
10041       case ISD::SIGN_EXTEND:
10042         Opc = ARMISD::VGETLANEs;
10043         break;
10044       case ISD::ZERO_EXTEND:
10045       case ISD::ANY_EXTEND:
10046         Opc = ARMISD::VGETLANEu;
10047         break;
10048       }
10049       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10050     }
10051   }
10052
10053   return SDValue();
10054 }
10055
10056 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
10057 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
10058 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
10059                                        const ARMSubtarget *ST) {
10060   // If the target supports NEON, try to use vmax/vmin instructions for f32
10061   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
10062   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
10063   // a NaN; only do the transformation when it matches that behavior.
10064
10065   // For now only do this when using NEON for FP operations; if using VFP, it
10066   // is not obvious that the benefit outweighs the cost of switching to the
10067   // NEON pipeline.
10068   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
10069       N->getValueType(0) != MVT::f32)
10070     return SDValue();
10071
10072   SDValue CondLHS = N->getOperand(0);
10073   SDValue CondRHS = N->getOperand(1);
10074   SDValue LHS = N->getOperand(2);
10075   SDValue RHS = N->getOperand(3);
10076   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
10077
10078   unsigned Opcode = 0;
10079   bool IsReversed;
10080   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
10081     IsReversed = false; // x CC y ? x : y
10082   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
10083     IsReversed = true ; // x CC y ? y : x
10084   } else {
10085     return SDValue();
10086   }
10087
10088   bool IsUnordered;
10089   switch (CC) {
10090   default: break;
10091   case ISD::SETOLT:
10092   case ISD::SETOLE:
10093   case ISD::SETLT:
10094   case ISD::SETLE:
10095   case ISD::SETULT:
10096   case ISD::SETULE:
10097     // If LHS is NaN, an ordered comparison will be false and the result will
10098     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
10099     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10100     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10101     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10102       break;
10103     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10104     // will return -0, so vmin can only be used for unsafe math or if one of
10105     // the operands is known to be nonzero.
10106     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10107         !DAG.getTarget().Options.UnsafeFPMath &&
10108         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10109       break;
10110     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10111     break;
10112
10113   case ISD::SETOGT:
10114   case ISD::SETOGE:
10115   case ISD::SETGT:
10116   case ISD::SETGE:
10117   case ISD::SETUGT:
10118   case ISD::SETUGE:
10119     // If LHS is NaN, an ordered comparison will be false and the result will
10120     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
10121     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10122     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10123     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10124       break;
10125     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10126     // will return +0, so vmax can only be used for unsafe math or if one of
10127     // the operands is known to be nonzero.
10128     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10129         !DAG.getTarget().Options.UnsafeFPMath &&
10130         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10131       break;
10132     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10133     break;
10134   }
10135
10136   if (!Opcode)
10137     return SDValue();
10138   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10139 }
10140
10141 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10142 SDValue
10143 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10144   SDValue Cmp = N->getOperand(4);
10145   if (Cmp.getOpcode() != ARMISD::CMPZ)
10146     // Only looking at EQ and NE cases.
10147     return SDValue();
10148
10149   EVT VT = N->getValueType(0);
10150   SDLoc dl(N);
10151   SDValue LHS = Cmp.getOperand(0);
10152   SDValue RHS = Cmp.getOperand(1);
10153   SDValue FalseVal = N->getOperand(0);
10154   SDValue TrueVal = N->getOperand(1);
10155   SDValue ARMcc = N->getOperand(2);
10156   ARMCC::CondCodes CC =
10157     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10158
10159   // Simplify
10160   //   mov     r1, r0
10161   //   cmp     r1, x
10162   //   mov     r0, y
10163   //   moveq   r0, x
10164   // to
10165   //   cmp     r0, x
10166   //   movne   r0, y
10167   //
10168   //   mov     r1, r0
10169   //   cmp     r1, x
10170   //   mov     r0, x
10171   //   movne   r0, y
10172   // to
10173   //   cmp     r0, x
10174   //   movne   r0, y
10175   /// FIXME: Turn this into a target neutral optimization?
10176   SDValue Res;
10177   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10178     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10179                       N->getOperand(3), Cmp);
10180   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10181     SDValue ARMcc;
10182     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10183     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10184                       N->getOperand(3), NewCmp);
10185   }
10186
10187   if (Res.getNode()) {
10188     APInt KnownZero, KnownOne;
10189     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10190     // Capture demanded bits information that would be otherwise lost.
10191     if (KnownZero == 0xfffffffe)
10192       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10193                         DAG.getValueType(MVT::i1));
10194     else if (KnownZero == 0xffffff00)
10195       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10196                         DAG.getValueType(MVT::i8));
10197     else if (KnownZero == 0xffff0000)
10198       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10199                         DAG.getValueType(MVT::i16));
10200   }
10201
10202   return Res;
10203 }
10204
10205 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10206                                              DAGCombinerInfo &DCI) const {
10207   switch (N->getOpcode()) {
10208   default: break;
10209   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10210   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10211   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10212   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10213   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10214   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10215   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10216   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10217   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10218   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10219   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10220   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10221   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10222   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10223   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10224   case ISD::FP_TO_SINT:
10225   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10226   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10227   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10228   case ISD::SHL:
10229   case ISD::SRA:
10230   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10231   case ISD::SIGN_EXTEND:
10232   case ISD::ZERO_EXTEND:
10233   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10234   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10235   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10236   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10237   case ARMISD::VLD2DUP:
10238   case ARMISD::VLD3DUP:
10239   case ARMISD::VLD4DUP:
10240     return PerformVLDCombine(N, DCI);
10241   case ARMISD::BUILD_VECTOR:
10242     return PerformARMBUILD_VECTORCombine(N, DCI);
10243   case ISD::INTRINSIC_VOID:
10244   case ISD::INTRINSIC_W_CHAIN:
10245     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10246     case Intrinsic::arm_neon_vld1:
10247     case Intrinsic::arm_neon_vld2:
10248     case Intrinsic::arm_neon_vld3:
10249     case Intrinsic::arm_neon_vld4:
10250     case Intrinsic::arm_neon_vld2lane:
10251     case Intrinsic::arm_neon_vld3lane:
10252     case Intrinsic::arm_neon_vld4lane:
10253     case Intrinsic::arm_neon_vst1:
10254     case Intrinsic::arm_neon_vst2:
10255     case Intrinsic::arm_neon_vst3:
10256     case Intrinsic::arm_neon_vst4:
10257     case Intrinsic::arm_neon_vst2lane:
10258     case Intrinsic::arm_neon_vst3lane:
10259     case Intrinsic::arm_neon_vst4lane:
10260       return PerformVLDCombine(N, DCI);
10261     default: break;
10262     }
10263     break;
10264   }
10265   return SDValue();
10266 }
10267
10268 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10269                                                           EVT VT) const {
10270   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10271 }
10272
10273 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10274                                                        unsigned,
10275                                                        unsigned,
10276                                                        bool *Fast) const {
10277   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10278   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10279
10280   switch (VT.getSimpleVT().SimpleTy) {
10281   default:
10282     return false;
10283   case MVT::i8:
10284   case MVT::i16:
10285   case MVT::i32: {
10286     // Unaligned access can use (for example) LRDB, LRDH, LDR
10287     if (AllowsUnaligned) {
10288       if (Fast)
10289         *Fast = Subtarget->hasV7Ops();
10290       return true;
10291     }
10292     return false;
10293   }
10294   case MVT::f64:
10295   case MVT::v2f64: {
10296     // For any little-endian targets with neon, we can support unaligned ld/st
10297     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10298     // A big-endian target may also explicitly support unaligned accesses
10299     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10300       if (Fast)
10301         *Fast = true;
10302       return true;
10303     }
10304     return false;
10305   }
10306   }
10307 }
10308
10309 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10310                        unsigned AlignCheck) {
10311   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10312           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10313 }
10314
10315 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10316                                            unsigned DstAlign, unsigned SrcAlign,
10317                                            bool IsMemset, bool ZeroMemset,
10318                                            bool MemcpyStrSrc,
10319                                            MachineFunction &MF) const {
10320   const Function *F = MF.getFunction();
10321
10322   // See if we can use NEON instructions for this...
10323   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10324       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10325     bool Fast;
10326     if (Size >= 16 &&
10327         (memOpAlign(SrcAlign, DstAlign, 16) ||
10328          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10329       return MVT::v2f64;
10330     } else if (Size >= 8 &&
10331                (memOpAlign(SrcAlign, DstAlign, 8) ||
10332                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10333                  Fast))) {
10334       return MVT::f64;
10335     }
10336   }
10337
10338   // Lowering to i32/i16 if the size permits.
10339   if (Size >= 4)
10340     return MVT::i32;
10341   else if (Size >= 2)
10342     return MVT::i16;
10343
10344   // Let the target-independent logic figure it out.
10345   return MVT::Other;
10346 }
10347
10348 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10349   if (Val.getOpcode() != ISD::LOAD)
10350     return false;
10351
10352   EVT VT1 = Val.getValueType();
10353   if (!VT1.isSimple() || !VT1.isInteger() ||
10354       !VT2.isSimple() || !VT2.isInteger())
10355     return false;
10356
10357   switch (VT1.getSimpleVT().SimpleTy) {
10358   default: break;
10359   case MVT::i1:
10360   case MVT::i8:
10361   case MVT::i16:
10362     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10363     return true;
10364   }
10365
10366   return false;
10367 }
10368
10369 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10370   EVT VT = ExtVal.getValueType();
10371
10372   if (!isTypeLegal(VT))
10373     return false;
10374
10375   // Don't create a loadext if we can fold the extension into a wide/long
10376   // instruction.
10377   // If there's more than one user instruction, the loadext is desirable no
10378   // matter what.  There can be two uses by the same instruction.
10379   if (ExtVal->use_empty() ||
10380       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10381     return true;
10382
10383   SDNode *U = *ExtVal->use_begin();
10384   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10385        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10386     return false;
10387
10388   return true;
10389 }
10390
10391 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10392   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10393     return false;
10394
10395   if (!isTypeLegal(EVT::getEVT(Ty1)))
10396     return false;
10397
10398   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10399
10400   // Assuming the caller doesn't have a zeroext or signext return parameter,
10401   // truncation all the way down to i1 is valid.
10402   return true;
10403 }
10404
10405
10406 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10407   if (V < 0)
10408     return false;
10409
10410   unsigned Scale = 1;
10411   switch (VT.getSimpleVT().SimpleTy) {
10412   default: return false;
10413   case MVT::i1:
10414   case MVT::i8:
10415     // Scale == 1;
10416     break;
10417   case MVT::i16:
10418     // Scale == 2;
10419     Scale = 2;
10420     break;
10421   case MVT::i32:
10422     // Scale == 4;
10423     Scale = 4;
10424     break;
10425   }
10426
10427   if ((V & (Scale - 1)) != 0)
10428     return false;
10429   V /= Scale;
10430   return V == (V & ((1LL << 5) - 1));
10431 }
10432
10433 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10434                                       const ARMSubtarget *Subtarget) {
10435   bool isNeg = false;
10436   if (V < 0) {
10437     isNeg = true;
10438     V = - V;
10439   }
10440
10441   switch (VT.getSimpleVT().SimpleTy) {
10442   default: return false;
10443   case MVT::i1:
10444   case MVT::i8:
10445   case MVT::i16:
10446   case MVT::i32:
10447     // + imm12 or - imm8
10448     if (isNeg)
10449       return V == (V & ((1LL << 8) - 1));
10450     return V == (V & ((1LL << 12) - 1));
10451   case MVT::f32:
10452   case MVT::f64:
10453     // Same as ARM mode. FIXME: NEON?
10454     if (!Subtarget->hasVFP2())
10455       return false;
10456     if ((V & 3) != 0)
10457       return false;
10458     V >>= 2;
10459     return V == (V & ((1LL << 8) - 1));
10460   }
10461 }
10462
10463 /// isLegalAddressImmediate - Return true if the integer value can be used
10464 /// as the offset of the target addressing mode for load / store of the
10465 /// given type.
10466 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10467                                     const ARMSubtarget *Subtarget) {
10468   if (V == 0)
10469     return true;
10470
10471   if (!VT.isSimple())
10472     return false;
10473
10474   if (Subtarget->isThumb1Only())
10475     return isLegalT1AddressImmediate(V, VT);
10476   else if (Subtarget->isThumb2())
10477     return isLegalT2AddressImmediate(V, VT, Subtarget);
10478
10479   // ARM mode.
10480   if (V < 0)
10481     V = - V;
10482   switch (VT.getSimpleVT().SimpleTy) {
10483   default: return false;
10484   case MVT::i1:
10485   case MVT::i8:
10486   case MVT::i32:
10487     // +- imm12
10488     return V == (V & ((1LL << 12) - 1));
10489   case MVT::i16:
10490     // +- imm8
10491     return V == (V & ((1LL << 8) - 1));
10492   case MVT::f32:
10493   case MVT::f64:
10494     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10495       return false;
10496     if ((V & 3) != 0)
10497       return false;
10498     V >>= 2;
10499     return V == (V & ((1LL << 8) - 1));
10500   }
10501 }
10502
10503 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10504                                                       EVT VT) const {
10505   int Scale = AM.Scale;
10506   if (Scale < 0)
10507     return false;
10508
10509   switch (VT.getSimpleVT().SimpleTy) {
10510   default: return false;
10511   case MVT::i1:
10512   case MVT::i8:
10513   case MVT::i16:
10514   case MVT::i32:
10515     if (Scale == 1)
10516       return true;
10517     // r + r << imm
10518     Scale = Scale & ~1;
10519     return Scale == 2 || Scale == 4 || Scale == 8;
10520   case MVT::i64:
10521     // r + r
10522     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10523       return true;
10524     return false;
10525   case MVT::isVoid:
10526     // Note, we allow "void" uses (basically, uses that aren't loads or
10527     // stores), because arm allows folding a scale into many arithmetic
10528     // operations.  This should be made more precise and revisited later.
10529
10530     // Allow r << imm, but the imm has to be a multiple of two.
10531     if (Scale & 1) return false;
10532     return isPowerOf2_32(Scale);
10533   }
10534 }
10535
10536 /// isLegalAddressingMode - Return true if the addressing mode represented
10537 /// by AM is legal for this target, for a load/store of the specified type.
10538 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10539                                               const AddrMode &AM, Type *Ty,
10540                                               unsigned AS) const {
10541   EVT VT = getValueType(DL, Ty, true);
10542   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10543     return false;
10544
10545   // Can never fold addr of global into load/store.
10546   if (AM.BaseGV)
10547     return false;
10548
10549   switch (AM.Scale) {
10550   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10551     break;
10552   case 1:
10553     if (Subtarget->isThumb1Only())
10554       return false;
10555     // FALL THROUGH.
10556   default:
10557     // ARM doesn't support any R+R*scale+imm addr modes.
10558     if (AM.BaseOffs)
10559       return false;
10560
10561     if (!VT.isSimple())
10562       return false;
10563
10564     if (Subtarget->isThumb2())
10565       return isLegalT2ScaledAddressingMode(AM, VT);
10566
10567     int Scale = AM.Scale;
10568     switch (VT.getSimpleVT().SimpleTy) {
10569     default: return false;
10570     case MVT::i1:
10571     case MVT::i8:
10572     case MVT::i32:
10573       if (Scale < 0) Scale = -Scale;
10574       if (Scale == 1)
10575         return true;
10576       // r + r << imm
10577       return isPowerOf2_32(Scale & ~1);
10578     case MVT::i16:
10579     case MVT::i64:
10580       // r + r
10581       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10582         return true;
10583       return false;
10584
10585     case MVT::isVoid:
10586       // Note, we allow "void" uses (basically, uses that aren't loads or
10587       // stores), because arm allows folding a scale into many arithmetic
10588       // operations.  This should be made more precise and revisited later.
10589
10590       // Allow r << imm, but the imm has to be a multiple of two.
10591       if (Scale & 1) return false;
10592       return isPowerOf2_32(Scale);
10593     }
10594   }
10595   return true;
10596 }
10597
10598 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10599 /// icmp immediate, that is the target has icmp instructions which can compare
10600 /// a register against the immediate without having to materialize the
10601 /// immediate into a register.
10602 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10603   // Thumb2 and ARM modes can use cmn for negative immediates.
10604   if (!Subtarget->isThumb())
10605     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10606   if (Subtarget->isThumb2())
10607     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10608   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10609   return Imm >= 0 && Imm <= 255;
10610 }
10611
10612 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10613 /// *or sub* immediate, that is the target has add or sub instructions which can
10614 /// add a register with the immediate without having to materialize the
10615 /// immediate into a register.
10616 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10617   // Same encoding for add/sub, just flip the sign.
10618   int64_t AbsImm = std::abs(Imm);
10619   if (!Subtarget->isThumb())
10620     return ARM_AM::getSOImmVal(AbsImm) != -1;
10621   if (Subtarget->isThumb2())
10622     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10623   // Thumb1 only has 8-bit unsigned immediate.
10624   return AbsImm >= 0 && AbsImm <= 255;
10625 }
10626
10627 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10628                                       bool isSEXTLoad, SDValue &Base,
10629                                       SDValue &Offset, bool &isInc,
10630                                       SelectionDAG &DAG) {
10631   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10632     return false;
10633
10634   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10635     // AddressingMode 3
10636     Base = Ptr->getOperand(0);
10637     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10638       int RHSC = (int)RHS->getZExtValue();
10639       if (RHSC < 0 && RHSC > -256) {
10640         assert(Ptr->getOpcode() == ISD::ADD);
10641         isInc = false;
10642         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10643         return true;
10644       }
10645     }
10646     isInc = (Ptr->getOpcode() == ISD::ADD);
10647     Offset = Ptr->getOperand(1);
10648     return true;
10649   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10650     // AddressingMode 2
10651     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10652       int RHSC = (int)RHS->getZExtValue();
10653       if (RHSC < 0 && RHSC > -0x1000) {
10654         assert(Ptr->getOpcode() == ISD::ADD);
10655         isInc = false;
10656         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10657         Base = Ptr->getOperand(0);
10658         return true;
10659       }
10660     }
10661
10662     if (Ptr->getOpcode() == ISD::ADD) {
10663       isInc = true;
10664       ARM_AM::ShiftOpc ShOpcVal=
10665         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10666       if (ShOpcVal != ARM_AM::no_shift) {
10667         Base = Ptr->getOperand(1);
10668         Offset = Ptr->getOperand(0);
10669       } else {
10670         Base = Ptr->getOperand(0);
10671         Offset = Ptr->getOperand(1);
10672       }
10673       return true;
10674     }
10675
10676     isInc = (Ptr->getOpcode() == ISD::ADD);
10677     Base = Ptr->getOperand(0);
10678     Offset = Ptr->getOperand(1);
10679     return true;
10680   }
10681
10682   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10683   return false;
10684 }
10685
10686 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10687                                      bool isSEXTLoad, SDValue &Base,
10688                                      SDValue &Offset, bool &isInc,
10689                                      SelectionDAG &DAG) {
10690   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10691     return false;
10692
10693   Base = Ptr->getOperand(0);
10694   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10695     int RHSC = (int)RHS->getZExtValue();
10696     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10697       assert(Ptr->getOpcode() == ISD::ADD);
10698       isInc = false;
10699       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10700       return true;
10701     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10702       isInc = Ptr->getOpcode() == ISD::ADD;
10703       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10704       return true;
10705     }
10706   }
10707
10708   return false;
10709 }
10710
10711 /// getPreIndexedAddressParts - returns true by value, base pointer and
10712 /// offset pointer and addressing mode by reference if the node's address
10713 /// can be legally represented as pre-indexed load / store address.
10714 bool
10715 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10716                                              SDValue &Offset,
10717                                              ISD::MemIndexedMode &AM,
10718                                              SelectionDAG &DAG) const {
10719   if (Subtarget->isThumb1Only())
10720     return false;
10721
10722   EVT VT;
10723   SDValue Ptr;
10724   bool isSEXTLoad = false;
10725   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10726     Ptr = LD->getBasePtr();
10727     VT  = LD->getMemoryVT();
10728     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10729   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10730     Ptr = ST->getBasePtr();
10731     VT  = ST->getMemoryVT();
10732   } else
10733     return false;
10734
10735   bool isInc;
10736   bool isLegal = false;
10737   if (Subtarget->isThumb2())
10738     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10739                                        Offset, isInc, DAG);
10740   else
10741     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10742                                         Offset, isInc, DAG);
10743   if (!isLegal)
10744     return false;
10745
10746   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10747   return true;
10748 }
10749
10750 /// getPostIndexedAddressParts - returns true by value, base pointer and
10751 /// offset pointer and addressing mode by reference if this node can be
10752 /// combined with a load / store to form a post-indexed load / store.
10753 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10754                                                    SDValue &Base,
10755                                                    SDValue &Offset,
10756                                                    ISD::MemIndexedMode &AM,
10757                                                    SelectionDAG &DAG) const {
10758   if (Subtarget->isThumb1Only())
10759     return false;
10760
10761   EVT VT;
10762   SDValue Ptr;
10763   bool isSEXTLoad = false;
10764   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10765     VT  = LD->getMemoryVT();
10766     Ptr = LD->getBasePtr();
10767     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10768   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10769     VT  = ST->getMemoryVT();
10770     Ptr = ST->getBasePtr();
10771   } else
10772     return false;
10773
10774   bool isInc;
10775   bool isLegal = false;
10776   if (Subtarget->isThumb2())
10777     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10778                                        isInc, DAG);
10779   else
10780     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10781                                         isInc, DAG);
10782   if (!isLegal)
10783     return false;
10784
10785   if (Ptr != Base) {
10786     // Swap base ptr and offset to catch more post-index load / store when
10787     // it's legal. In Thumb2 mode, offset must be an immediate.
10788     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10789         !Subtarget->isThumb2())
10790       std::swap(Base, Offset);
10791
10792     // Post-indexed load / store update the base pointer.
10793     if (Ptr != Base)
10794       return false;
10795   }
10796
10797   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10798   return true;
10799 }
10800
10801 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10802                                                       APInt &KnownZero,
10803                                                       APInt &KnownOne,
10804                                                       const SelectionDAG &DAG,
10805                                                       unsigned Depth) const {
10806   unsigned BitWidth = KnownOne.getBitWidth();
10807   KnownZero = KnownOne = APInt(BitWidth, 0);
10808   switch (Op.getOpcode()) {
10809   default: break;
10810   case ARMISD::ADDC:
10811   case ARMISD::ADDE:
10812   case ARMISD::SUBC:
10813   case ARMISD::SUBE:
10814     // These nodes' second result is a boolean
10815     if (Op.getResNo() == 0)
10816       break;
10817     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10818     break;
10819   case ARMISD::CMOV: {
10820     // Bits are known zero/one if known on the LHS and RHS.
10821     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10822     if (KnownZero == 0 && KnownOne == 0) return;
10823
10824     APInt KnownZeroRHS, KnownOneRHS;
10825     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10826     KnownZero &= KnownZeroRHS;
10827     KnownOne  &= KnownOneRHS;
10828     return;
10829   }
10830   case ISD::INTRINSIC_W_CHAIN: {
10831     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10832     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10833     switch (IntID) {
10834     default: return;
10835     case Intrinsic::arm_ldaex:
10836     case Intrinsic::arm_ldrex: {
10837       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10838       unsigned MemBits = VT.getScalarType().getSizeInBits();
10839       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10840       return;
10841     }
10842     }
10843   }
10844   }
10845 }
10846
10847 //===----------------------------------------------------------------------===//
10848 //                           ARM Inline Assembly Support
10849 //===----------------------------------------------------------------------===//
10850
10851 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10852   // Looking for "rev" which is V6+.
10853   if (!Subtarget->hasV6Ops())
10854     return false;
10855
10856   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10857   std::string AsmStr = IA->getAsmString();
10858   SmallVector<StringRef, 4> AsmPieces;
10859   SplitString(AsmStr, AsmPieces, ";\n");
10860
10861   switch (AsmPieces.size()) {
10862   default: return false;
10863   case 1:
10864     AsmStr = AsmPieces[0];
10865     AsmPieces.clear();
10866     SplitString(AsmStr, AsmPieces, " \t,");
10867
10868     // rev $0, $1
10869     if (AsmPieces.size() == 3 &&
10870         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10871         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10872       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10873       if (Ty && Ty->getBitWidth() == 32)
10874         return IntrinsicLowering::LowerToByteSwap(CI);
10875     }
10876     break;
10877   }
10878
10879   return false;
10880 }
10881
10882 /// getConstraintType - Given a constraint letter, return the type of
10883 /// constraint it is for this target.
10884 ARMTargetLowering::ConstraintType
10885 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10886   if (Constraint.size() == 1) {
10887     switch (Constraint[0]) {
10888     default:  break;
10889     case 'l': return C_RegisterClass;
10890     case 'w': return C_RegisterClass;
10891     case 'h': return C_RegisterClass;
10892     case 'x': return C_RegisterClass;
10893     case 't': return C_RegisterClass;
10894     case 'j': return C_Other; // Constant for movw.
10895       // An address with a single base register. Due to the way we
10896       // currently handle addresses it is the same as an 'r' memory constraint.
10897     case 'Q': return C_Memory;
10898     }
10899   } else if (Constraint.size() == 2) {
10900     switch (Constraint[0]) {
10901     default: break;
10902     // All 'U+' constraints are addresses.
10903     case 'U': return C_Memory;
10904     }
10905   }
10906   return TargetLowering::getConstraintType(Constraint);
10907 }
10908
10909 /// Examine constraint type and operand type and determine a weight value.
10910 /// This object must already have been set up with the operand type
10911 /// and the current alternative constraint selected.
10912 TargetLowering::ConstraintWeight
10913 ARMTargetLowering::getSingleConstraintMatchWeight(
10914     AsmOperandInfo &info, const char *constraint) const {
10915   ConstraintWeight weight = CW_Invalid;
10916   Value *CallOperandVal = info.CallOperandVal;
10917     // If we don't have a value, we can't do a match,
10918     // but allow it at the lowest weight.
10919   if (!CallOperandVal)
10920     return CW_Default;
10921   Type *type = CallOperandVal->getType();
10922   // Look at the constraint type.
10923   switch (*constraint) {
10924   default:
10925     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10926     break;
10927   case 'l':
10928     if (type->isIntegerTy()) {
10929       if (Subtarget->isThumb())
10930         weight = CW_SpecificReg;
10931       else
10932         weight = CW_Register;
10933     }
10934     break;
10935   case 'w':
10936     if (type->isFloatingPointTy())
10937       weight = CW_Register;
10938     break;
10939   }
10940   return weight;
10941 }
10942
10943 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10944 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
10945     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
10946   if (Constraint.size() == 1) {
10947     // GCC ARM Constraint Letters
10948     switch (Constraint[0]) {
10949     case 'l': // Low regs or general regs.
10950       if (Subtarget->isThumb())
10951         return RCPair(0U, &ARM::tGPRRegClass);
10952       return RCPair(0U, &ARM::GPRRegClass);
10953     case 'h': // High regs or no regs.
10954       if (Subtarget->isThumb())
10955         return RCPair(0U, &ARM::hGPRRegClass);
10956       break;
10957     case 'r':
10958       if (Subtarget->isThumb1Only())
10959         return RCPair(0U, &ARM::tGPRRegClass);
10960       return RCPair(0U, &ARM::GPRRegClass);
10961     case 'w':
10962       if (VT == MVT::Other)
10963         break;
10964       if (VT == MVT::f32)
10965         return RCPair(0U, &ARM::SPRRegClass);
10966       if (VT.getSizeInBits() == 64)
10967         return RCPair(0U, &ARM::DPRRegClass);
10968       if (VT.getSizeInBits() == 128)
10969         return RCPair(0U, &ARM::QPRRegClass);
10970       break;
10971     case 'x':
10972       if (VT == MVT::Other)
10973         break;
10974       if (VT == MVT::f32)
10975         return RCPair(0U, &ARM::SPR_8RegClass);
10976       if (VT.getSizeInBits() == 64)
10977         return RCPair(0U, &ARM::DPR_8RegClass);
10978       if (VT.getSizeInBits() == 128)
10979         return RCPair(0U, &ARM::QPR_8RegClass);
10980       break;
10981     case 't':
10982       if (VT == MVT::f32)
10983         return RCPair(0U, &ARM::SPRRegClass);
10984       break;
10985     }
10986   }
10987   if (StringRef("{cc}").equals_lower(Constraint))
10988     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10989
10990   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10991 }
10992
10993 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10994 /// vector.  If it is invalid, don't add anything to Ops.
10995 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10996                                                      std::string &Constraint,
10997                                                      std::vector<SDValue>&Ops,
10998                                                      SelectionDAG &DAG) const {
10999   SDValue Result;
11000
11001   // Currently only support length 1 constraints.
11002   if (Constraint.length() != 1) return;
11003
11004   char ConstraintLetter = Constraint[0];
11005   switch (ConstraintLetter) {
11006   default: break;
11007   case 'j':
11008   case 'I': case 'J': case 'K': case 'L':
11009   case 'M': case 'N': case 'O':
11010     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11011     if (!C)
11012       return;
11013
11014     int64_t CVal64 = C->getSExtValue();
11015     int CVal = (int) CVal64;
11016     // None of these constraints allow values larger than 32 bits.  Check
11017     // that the value fits in an int.
11018     if (CVal != CVal64)
11019       return;
11020
11021     switch (ConstraintLetter) {
11022       case 'j':
11023         // Constant suitable for movw, must be between 0 and
11024         // 65535.
11025         if (Subtarget->hasV6T2Ops())
11026           if (CVal >= 0 && CVal <= 65535)
11027             break;
11028         return;
11029       case 'I':
11030         if (Subtarget->isThumb1Only()) {
11031           // This must be a constant between 0 and 255, for ADD
11032           // immediates.
11033           if (CVal >= 0 && CVal <= 255)
11034             break;
11035         } else if (Subtarget->isThumb2()) {
11036           // A constant that can be used as an immediate value in a
11037           // data-processing instruction.
11038           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11039             break;
11040         } else {
11041           // A constant that can be used as an immediate value in a
11042           // data-processing instruction.
11043           if (ARM_AM::getSOImmVal(CVal) != -1)
11044             break;
11045         }
11046         return;
11047
11048       case 'J':
11049         if (Subtarget->isThumb()) {  // FIXME thumb2
11050           // This must be a constant between -255 and -1, for negated ADD
11051           // immediates. This can be used in GCC with an "n" modifier that
11052           // prints the negated value, for use with SUB instructions. It is
11053           // not useful otherwise but is implemented for compatibility.
11054           if (CVal >= -255 && CVal <= -1)
11055             break;
11056         } else {
11057           // This must be a constant between -4095 and 4095. It is not clear
11058           // what this constraint is intended for. Implemented for
11059           // compatibility with GCC.
11060           if (CVal >= -4095 && CVal <= 4095)
11061             break;
11062         }
11063         return;
11064
11065       case 'K':
11066         if (Subtarget->isThumb1Only()) {
11067           // A 32-bit value where only one byte has a nonzero value. Exclude
11068           // zero to match GCC. This constraint is used by GCC internally for
11069           // constants that can be loaded with a move/shift combination.
11070           // It is not useful otherwise but is implemented for compatibility.
11071           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11072             break;
11073         } else if (Subtarget->isThumb2()) {
11074           // A constant whose bitwise inverse can be used as an immediate
11075           // value in a data-processing instruction. This can be used in GCC
11076           // with a "B" modifier that prints the inverted value, for use with
11077           // BIC and MVN instructions. It is not useful otherwise but is
11078           // implemented for compatibility.
11079           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11080             break;
11081         } else {
11082           // A constant whose bitwise inverse can be used as an immediate
11083           // value in a data-processing instruction. This can be used in GCC
11084           // with a "B" modifier that prints the inverted value, for use with
11085           // BIC and MVN instructions. It is not useful otherwise but is
11086           // implemented for compatibility.
11087           if (ARM_AM::getSOImmVal(~CVal) != -1)
11088             break;
11089         }
11090         return;
11091
11092       case 'L':
11093         if (Subtarget->isThumb1Only()) {
11094           // This must be a constant between -7 and 7,
11095           // for 3-operand ADD/SUB immediate instructions.
11096           if (CVal >= -7 && CVal < 7)
11097             break;
11098         } else if (Subtarget->isThumb2()) {
11099           // A constant whose negation can be used as an immediate value in a
11100           // data-processing instruction. This can be used in GCC with an "n"
11101           // modifier that prints the negated value, for use with SUB
11102           // instructions. It is not useful otherwise but is implemented for
11103           // compatibility.
11104           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11105             break;
11106         } else {
11107           // A constant whose negation can be used as an immediate value in a
11108           // data-processing instruction. This can be used in GCC with an "n"
11109           // modifier that prints the negated value, for use with SUB
11110           // instructions. It is not useful otherwise but is implemented for
11111           // compatibility.
11112           if (ARM_AM::getSOImmVal(-CVal) != -1)
11113             break;
11114         }
11115         return;
11116
11117       case 'M':
11118         if (Subtarget->isThumb()) { // FIXME thumb2
11119           // This must be a multiple of 4 between 0 and 1020, for
11120           // ADD sp + immediate.
11121           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11122             break;
11123         } else {
11124           // A power of two or a constant between 0 and 32.  This is used in
11125           // GCC for the shift amount on shifted register operands, but it is
11126           // useful in general for any shift amounts.
11127           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11128             break;
11129         }
11130         return;
11131
11132       case 'N':
11133         if (Subtarget->isThumb()) {  // FIXME thumb2
11134           // This must be a constant between 0 and 31, for shift amounts.
11135           if (CVal >= 0 && CVal <= 31)
11136             break;
11137         }
11138         return;
11139
11140       case 'O':
11141         if (Subtarget->isThumb()) {  // FIXME thumb2
11142           // This must be a multiple of 4 between -508 and 508, for
11143           // ADD/SUB sp = sp + immediate.
11144           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11145             break;
11146         }
11147         return;
11148     }
11149     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11150     break;
11151   }
11152
11153   if (Result.getNode()) {
11154     Ops.push_back(Result);
11155     return;
11156   }
11157   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11158 }
11159
11160 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11161   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11162          "Register-based DivRem lowering only");
11163   unsigned Opcode = Op->getOpcode();
11164   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11165          "Invalid opcode for Div/Rem lowering");
11166   bool isSigned = (Opcode == ISD::SDIVREM);
11167   EVT VT = Op->getValueType(0);
11168   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11169
11170   RTLIB::Libcall LC;
11171   switch (VT.getSimpleVT().SimpleTy) {
11172   default: llvm_unreachable("Unexpected request for libcall!");
11173   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11174   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11175   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11176   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11177   }
11178
11179   SDValue InChain = DAG.getEntryNode();
11180
11181   TargetLowering::ArgListTy Args;
11182   TargetLowering::ArgListEntry Entry;
11183   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11184     EVT ArgVT = Op->getOperand(i).getValueType();
11185     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11186     Entry.Node = Op->getOperand(i);
11187     Entry.Ty = ArgTy;
11188     Entry.isSExt = isSigned;
11189     Entry.isZExt = !isSigned;
11190     Args.push_back(Entry);
11191   }
11192
11193   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11194                                          getPointerTy(DAG.getDataLayout()));
11195
11196   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11197
11198   SDLoc dl(Op);
11199   TargetLowering::CallLoweringInfo CLI(DAG);
11200   CLI.setDebugLoc(dl).setChain(InChain)
11201     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11202     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11203
11204   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11205   return CallInfo.first;
11206 }
11207
11208 SDValue
11209 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11210   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11211   SDLoc DL(Op);
11212
11213   // Get the inputs.
11214   SDValue Chain = Op.getOperand(0);
11215   SDValue Size  = Op.getOperand(1);
11216
11217   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11218                               DAG.getConstant(2, DL, MVT::i32));
11219
11220   SDValue Flag;
11221   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11222   Flag = Chain.getValue(1);
11223
11224   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11225   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11226
11227   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11228   Chain = NewSP.getValue(1);
11229
11230   SDValue Ops[2] = { NewSP, Chain };
11231   return DAG.getMergeValues(Ops, DL);
11232 }
11233
11234 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11235   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11236          "Unexpected type for custom-lowering FP_EXTEND");
11237
11238   RTLIB::Libcall LC;
11239   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11240
11241   SDValue SrcVal = Op.getOperand(0);
11242   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11243                      /*isSigned*/ false, SDLoc(Op)).first;
11244 }
11245
11246 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11247   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11248          Subtarget->isFPOnlySP() &&
11249          "Unexpected type for custom-lowering FP_ROUND");
11250
11251   RTLIB::Libcall LC;
11252   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11253
11254   SDValue SrcVal = Op.getOperand(0);
11255   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11256                      /*isSigned*/ false, SDLoc(Op)).first;
11257 }
11258
11259 bool
11260 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11261   // The ARM target isn't yet aware of offsets.
11262   return false;
11263 }
11264
11265 bool ARM::isBitFieldInvertedMask(unsigned v) {
11266   if (v == 0xffffffff)
11267     return false;
11268
11269   // there can be 1's on either or both "outsides", all the "inside"
11270   // bits must be 0's
11271   return isShiftedMask_32(~v);
11272 }
11273
11274 /// isFPImmLegal - Returns true if the target can instruction select the
11275 /// specified FP immediate natively. If false, the legalizer will
11276 /// materialize the FP immediate as a load from a constant pool.
11277 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11278   if (!Subtarget->hasVFP3())
11279     return false;
11280   if (VT == MVT::f32)
11281     return ARM_AM::getFP32Imm(Imm) != -1;
11282   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11283     return ARM_AM::getFP64Imm(Imm) != -1;
11284   return false;
11285 }
11286
11287 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11288 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11289 /// specified in the intrinsic calls.
11290 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11291                                            const CallInst &I,
11292                                            unsigned Intrinsic) const {
11293   switch (Intrinsic) {
11294   case Intrinsic::arm_neon_vld1:
11295   case Intrinsic::arm_neon_vld2:
11296   case Intrinsic::arm_neon_vld3:
11297   case Intrinsic::arm_neon_vld4:
11298   case Intrinsic::arm_neon_vld2lane:
11299   case Intrinsic::arm_neon_vld3lane:
11300   case Intrinsic::arm_neon_vld4lane: {
11301     Info.opc = ISD::INTRINSIC_W_CHAIN;
11302     // Conservatively set memVT to the entire set of vectors loaded.
11303     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11304     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11305     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11306     Info.ptrVal = I.getArgOperand(0);
11307     Info.offset = 0;
11308     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11309     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11310     Info.vol = false; // volatile loads with NEON intrinsics not supported
11311     Info.readMem = true;
11312     Info.writeMem = false;
11313     return true;
11314   }
11315   case Intrinsic::arm_neon_vst1:
11316   case Intrinsic::arm_neon_vst2:
11317   case Intrinsic::arm_neon_vst3:
11318   case Intrinsic::arm_neon_vst4:
11319   case Intrinsic::arm_neon_vst2lane:
11320   case Intrinsic::arm_neon_vst3lane:
11321   case Intrinsic::arm_neon_vst4lane: {
11322     Info.opc = ISD::INTRINSIC_VOID;
11323     // Conservatively set memVT to the entire set of vectors stored.
11324     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11325     unsigned NumElts = 0;
11326     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11327       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11328       if (!ArgTy->isVectorTy())
11329         break;
11330       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11331     }
11332     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11333     Info.ptrVal = I.getArgOperand(0);
11334     Info.offset = 0;
11335     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11336     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11337     Info.vol = false; // volatile stores with NEON intrinsics not supported
11338     Info.readMem = false;
11339     Info.writeMem = true;
11340     return true;
11341   }
11342   case Intrinsic::arm_ldaex:
11343   case Intrinsic::arm_ldrex: {
11344     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11345     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11346     Info.opc = ISD::INTRINSIC_W_CHAIN;
11347     Info.memVT = MVT::getVT(PtrTy->getElementType());
11348     Info.ptrVal = I.getArgOperand(0);
11349     Info.offset = 0;
11350     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11351     Info.vol = true;
11352     Info.readMem = true;
11353     Info.writeMem = false;
11354     return true;
11355   }
11356   case Intrinsic::arm_stlex:
11357   case Intrinsic::arm_strex: {
11358     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11359     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11360     Info.opc = ISD::INTRINSIC_W_CHAIN;
11361     Info.memVT = MVT::getVT(PtrTy->getElementType());
11362     Info.ptrVal = I.getArgOperand(1);
11363     Info.offset = 0;
11364     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11365     Info.vol = true;
11366     Info.readMem = false;
11367     Info.writeMem = true;
11368     return true;
11369   }
11370   case Intrinsic::arm_stlexd:
11371   case Intrinsic::arm_strexd: {
11372     Info.opc = ISD::INTRINSIC_W_CHAIN;
11373     Info.memVT = MVT::i64;
11374     Info.ptrVal = I.getArgOperand(2);
11375     Info.offset = 0;
11376     Info.align = 8;
11377     Info.vol = true;
11378     Info.readMem = false;
11379     Info.writeMem = true;
11380     return true;
11381   }
11382   case Intrinsic::arm_ldaexd:
11383   case Intrinsic::arm_ldrexd: {
11384     Info.opc = ISD::INTRINSIC_W_CHAIN;
11385     Info.memVT = MVT::i64;
11386     Info.ptrVal = I.getArgOperand(0);
11387     Info.offset = 0;
11388     Info.align = 8;
11389     Info.vol = true;
11390     Info.readMem = true;
11391     Info.writeMem = false;
11392     return true;
11393   }
11394   default:
11395     break;
11396   }
11397
11398   return false;
11399 }
11400
11401 /// \brief Returns true if it is beneficial to convert a load of a constant
11402 /// to just the constant itself.
11403 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11404                                                           Type *Ty) const {
11405   assert(Ty->isIntegerTy());
11406
11407   unsigned Bits = Ty->getPrimitiveSizeInBits();
11408   if (Bits == 0 || Bits > 32)
11409     return false;
11410   return true;
11411 }
11412
11413 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11414
11415 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11416                                         ARM_MB::MemBOpt Domain) const {
11417   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11418
11419   // First, if the target has no DMB, see what fallback we can use.
11420   if (!Subtarget->hasDataBarrier()) {
11421     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11422     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11423     // here.
11424     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11425       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11426       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11427                         Builder.getInt32(0), Builder.getInt32(7),
11428                         Builder.getInt32(10), Builder.getInt32(5)};
11429       return Builder.CreateCall(MCR, args);
11430     } else {
11431       // Instead of using barriers, atomic accesses on these subtargets use
11432       // libcalls.
11433       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11434     }
11435   } else {
11436     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11437     // Only a full system barrier exists in the M-class architectures.
11438     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11439     Constant *CDomain = Builder.getInt32(Domain);
11440     return Builder.CreateCall(DMB, CDomain);
11441   }
11442 }
11443
11444 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11445 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11446                                          AtomicOrdering Ord, bool IsStore,
11447                                          bool IsLoad) const {
11448   if (!getInsertFencesForAtomic())
11449     return nullptr;
11450
11451   switch (Ord) {
11452   case NotAtomic:
11453   case Unordered:
11454     llvm_unreachable("Invalid fence: unordered/non-atomic");
11455   case Monotonic:
11456   case Acquire:
11457     return nullptr; // Nothing to do
11458   case SequentiallyConsistent:
11459     if (!IsStore)
11460       return nullptr; // Nothing to do
11461     /*FALLTHROUGH*/
11462   case Release:
11463   case AcquireRelease:
11464     if (Subtarget->isSwift())
11465       return makeDMB(Builder, ARM_MB::ISHST);
11466     // FIXME: add a comment with a link to documentation justifying this.
11467     else
11468       return makeDMB(Builder, ARM_MB::ISH);
11469   }
11470   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11471 }
11472
11473 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11474                                           AtomicOrdering Ord, bool IsStore,
11475                                           bool IsLoad) const {
11476   if (!getInsertFencesForAtomic())
11477     return nullptr;
11478
11479   switch (Ord) {
11480   case NotAtomic:
11481   case Unordered:
11482     llvm_unreachable("Invalid fence: unordered/not-atomic");
11483   case Monotonic:
11484   case Release:
11485     return nullptr; // Nothing to do
11486   case Acquire:
11487   case AcquireRelease:
11488   case SequentiallyConsistent:
11489     return makeDMB(Builder, ARM_MB::ISH);
11490   }
11491   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11492 }
11493
11494 // Loads and stores less than 64-bits are already atomic; ones above that
11495 // are doomed anyway, so defer to the default libcall and blame the OS when
11496 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11497 // anything for those.
11498 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11499   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11500   return (Size == 64) && !Subtarget->isMClass();
11501 }
11502
11503 // Loads and stores less than 64-bits are already atomic; ones above that
11504 // are doomed anyway, so defer to the default libcall and blame the OS when
11505 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11506 // anything for those.
11507 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11508 // guarantee, see DDI0406C ARM architecture reference manual,
11509 // sections A8.8.72-74 LDRD)
11510 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11511   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11512   return (Size == 64) && !Subtarget->isMClass();
11513 }
11514
11515 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11516 // and up to 64 bits on the non-M profiles
11517 TargetLoweringBase::AtomicRMWExpansionKind
11518 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11519   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11520   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11521              ? AtomicRMWExpansionKind::LLSC
11522              : AtomicRMWExpansionKind::None;
11523 }
11524
11525 // This has so far only been implemented for MachO.
11526 bool ARMTargetLowering::useLoadStackGuardNode() const {
11527   return Subtarget->isTargetMachO();
11528 }
11529
11530 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11531                                                   unsigned &Cost) const {
11532   // If we do not have NEON, vector types are not natively supported.
11533   if (!Subtarget->hasNEON())
11534     return false;
11535
11536   // Floating point values and vector values map to the same register file.
11537   // Therefore, althought we could do a store extract of a vector type, this is
11538   // better to leave at float as we have more freedom in the addressing mode for
11539   // those.
11540   if (VectorTy->isFPOrFPVectorTy())
11541     return false;
11542
11543   // If the index is unknown at compile time, this is very expensive to lower
11544   // and it is not possible to combine the store with the extract.
11545   if (!isa<ConstantInt>(Idx))
11546     return false;
11547
11548   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11549   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11550   // We can do a store + vector extract on any vector that fits perfectly in a D
11551   // or Q register.
11552   if (BitWidth == 64 || BitWidth == 128) {
11553     Cost = 0;
11554     return true;
11555   }
11556   return false;
11557 }
11558
11559 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11560                                          AtomicOrdering Ord) const {
11561   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11562   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11563   bool IsAcquire = isAtLeastAcquire(Ord);
11564
11565   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11566   // intrinsic must return {i32, i32} and we have to recombine them into a
11567   // single i64 here.
11568   if (ValTy->getPrimitiveSizeInBits() == 64) {
11569     Intrinsic::ID Int =
11570         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11571     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11572
11573     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11574     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11575
11576     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11577     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11578     if (!Subtarget->isLittle())
11579       std::swap (Lo, Hi);
11580     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11581     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11582     return Builder.CreateOr(
11583         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11584   }
11585
11586   Type *Tys[] = { Addr->getType() };
11587   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11588   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11589
11590   return Builder.CreateTruncOrBitCast(
11591       Builder.CreateCall(Ldrex, Addr),
11592       cast<PointerType>(Addr->getType())->getElementType());
11593 }
11594
11595 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11596                                                Value *Addr,
11597                                                AtomicOrdering Ord) const {
11598   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11599   bool IsRelease = isAtLeastRelease(Ord);
11600
11601   // Since the intrinsics must have legal type, the i64 intrinsics take two
11602   // parameters: "i32, i32". We must marshal Val into the appropriate form
11603   // before the call.
11604   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11605     Intrinsic::ID Int =
11606         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11607     Function *Strex = Intrinsic::getDeclaration(M, Int);
11608     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11609
11610     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11611     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11612     if (!Subtarget->isLittle())
11613       std::swap (Lo, Hi);
11614     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11615     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11616   }
11617
11618   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11619   Type *Tys[] = { Addr->getType() };
11620   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11621
11622   return Builder.CreateCall(
11623       Strex, {Builder.CreateZExtOrBitCast(
11624                   Val, Strex->getFunctionType()->getParamType(0)),
11625               Addr});
11626 }
11627
11628 /// \brief Lower an interleaved load into a vldN intrinsic.
11629 ///
11630 /// E.g. Lower an interleaved load (Factor = 2):
11631 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11632 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11633 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11634 ///
11635 ///      Into:
11636 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11637 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11638 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11639 bool ARMTargetLowering::lowerInterleavedLoad(
11640     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11641     ArrayRef<unsigned> Indices, unsigned Factor) const {
11642   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11643          "Invalid interleave factor");
11644   assert(!Shuffles.empty() && "Empty shufflevector input");
11645   assert(Shuffles.size() == Indices.size() &&
11646          "Unmatched number of shufflevectors and indices");
11647
11648   VectorType *VecTy = Shuffles[0]->getType();
11649   Type *EltTy = VecTy->getVectorElementType();
11650
11651   const DataLayout &DL = LI->getModule()->getDataLayout();
11652   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11653   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11654
11655   // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11656   // support i64/f64 element).
11657   if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11658     return false;
11659
11660   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11661   // load integer vectors first and then convert to pointer vectors.
11662   if (EltTy->isPointerTy())
11663     VecTy =
11664         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11665
11666   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11667                                             Intrinsic::arm_neon_vld3,
11668                                             Intrinsic::arm_neon_vld4};
11669
11670   Function *VldnFunc =
11671       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11672
11673   IRBuilder<> Builder(LI);
11674   SmallVector<Value *, 2> Ops;
11675
11676   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11677   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11678   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11679
11680   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11681
11682   // Replace uses of each shufflevector with the corresponding vector loaded
11683   // by ldN.
11684   for (unsigned i = 0; i < Shuffles.size(); i++) {
11685     ShuffleVectorInst *SV = Shuffles[i];
11686     unsigned Index = Indices[i];
11687
11688     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11689
11690     // Convert the integer vector to pointer vector if the element is pointer.
11691     if (EltTy->isPointerTy())
11692       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11693
11694     SV->replaceAllUsesWith(SubVec);
11695   }
11696
11697   return true;
11698 }
11699
11700 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11701 ///
11702 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11703 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11704                                    unsigned NumElts) {
11705   SmallVector<Constant *, 16> Mask;
11706   for (unsigned i = 0; i < NumElts; i++)
11707     Mask.push_back(Builder.getInt32(Start + i));
11708
11709   return ConstantVector::get(Mask);
11710 }
11711
11712 /// \brief Lower an interleaved store into a vstN intrinsic.
11713 ///
11714 /// E.g. Lower an interleaved store (Factor = 3):
11715 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11716 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11717 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11718 ///
11719 ///      Into:
11720 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11721 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11722 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11723 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11724 ///
11725 /// Note that the new shufflevectors will be removed and we'll only generate one
11726 /// vst3 instruction in CodeGen.
11727 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11728                                               ShuffleVectorInst *SVI,
11729                                               unsigned Factor) const {
11730   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11731          "Invalid interleave factor");
11732
11733   VectorType *VecTy = SVI->getType();
11734   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11735          "Invalid interleaved store");
11736
11737   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11738   Type *EltTy = VecTy->getVectorElementType();
11739   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11740
11741   const DataLayout &DL = SI->getModule()->getDataLayout();
11742   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11743   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11744
11745   // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11746   // doesn't support i64/f64 element).
11747   if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11748     return false;
11749
11750   Value *Op0 = SVI->getOperand(0);
11751   Value *Op1 = SVI->getOperand(1);
11752   IRBuilder<> Builder(SI);
11753
11754   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11755   // vectors to integer vectors.
11756   if (EltTy->isPointerTy()) {
11757     Type *IntTy = DL.getIntPtrType(EltTy);
11758
11759     // Convert to the corresponding integer vector.
11760     Type *IntVecTy =
11761         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11762     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11763     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11764
11765     SubVecTy = VectorType::get(IntTy, NumSubElts);
11766   }
11767
11768   static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11769                                        Intrinsic::arm_neon_vst3,
11770                                        Intrinsic::arm_neon_vst4};
11771   Function *VstNFunc = Intrinsic::getDeclaration(
11772       SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11773
11774   SmallVector<Value *, 6> Ops;
11775
11776   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11777   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11778
11779   // Split the shufflevector operands into sub vectors for the new vstN call.
11780   for (unsigned i = 0; i < Factor; i++)
11781     Ops.push_back(Builder.CreateShuffleVector(
11782         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11783
11784   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11785   Builder.CreateCall(VstNFunc, Ops);
11786   return true;
11787 }
11788
11789 enum HABaseType {
11790   HA_UNKNOWN = 0,
11791   HA_FLOAT,
11792   HA_DOUBLE,
11793   HA_VECT64,
11794   HA_VECT128
11795 };
11796
11797 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11798                                    uint64_t &Members) {
11799   if (auto *ST = dyn_cast<StructType>(Ty)) {
11800     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11801       uint64_t SubMembers = 0;
11802       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11803         return false;
11804       Members += SubMembers;
11805     }
11806   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11807     uint64_t SubMembers = 0;
11808     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11809       return false;
11810     Members += SubMembers * AT->getNumElements();
11811   } else if (Ty->isFloatTy()) {
11812     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11813       return false;
11814     Members = 1;
11815     Base = HA_FLOAT;
11816   } else if (Ty->isDoubleTy()) {
11817     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11818       return false;
11819     Members = 1;
11820     Base = HA_DOUBLE;
11821   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11822     Members = 1;
11823     switch (Base) {
11824     case HA_FLOAT:
11825     case HA_DOUBLE:
11826       return false;
11827     case HA_VECT64:
11828       return VT->getBitWidth() == 64;
11829     case HA_VECT128:
11830       return VT->getBitWidth() == 128;
11831     case HA_UNKNOWN:
11832       switch (VT->getBitWidth()) {
11833       case 64:
11834         Base = HA_VECT64;
11835         return true;
11836       case 128:
11837         Base = HA_VECT128;
11838         return true;
11839       default:
11840         return false;
11841       }
11842     }
11843   }
11844
11845   return (Members > 0 && Members <= 4);
11846 }
11847
11848 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11849 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11850 /// passing according to AAPCS rules.
11851 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11852     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11853   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11854       CallingConv::ARM_AAPCS_VFP)
11855     return false;
11856
11857   HABaseType Base = HA_UNKNOWN;
11858   uint64_t Members = 0;
11859   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11860   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11861
11862   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11863   return IsHA || IsIntArray;
11864 }