ARM: make -Asserts,-Werror=unused-variable build happy
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include <utility>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "arm-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
62
63 static cl::opt<bool>
64 ARMInterworking("arm-interworking", cl::Hidden,
65   cl::desc("Enable / disable ARM interworking (for debugging only)"),
66   cl::init(true));
67
68 namespace {
69   class ARMCCState : public CCState {
70   public:
71     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
73                ParmContext PC)
74         : CCState(CC, isVarArg, MF, locs, C) {
75       assert(((PC == Call) || (PC == Prologue)) &&
76              "ARMCCState users must specify whether their context is call"
77              "or prologue generation.");
78       CallOrPrologue = PC;
79     }
80   };
81 }
82
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85   ARM::R0, ARM::R1, ARM::R2, ARM::R3
86 };
87
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89                                        MVT PromotedBitwiseVT) {
90   if (VT != PromotedLdStVT) {
91     setOperationAction(ISD::LOAD, VT, Promote);
92     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
93
94     setOperationAction(ISD::STORE, VT, Promote);
95     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
96   }
97
98   MVT ElemTy = VT.getVectorElementType();
99   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100     setOperationAction(ISD::SETCC, VT, Custom);
101   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103   if (ElemTy == MVT::i32) {
104     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
108   } else {
109     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
113   }
114   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
115   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
116   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
117   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118   setOperationAction(ISD::SELECT,            VT, Expand);
119   setOperationAction(ISD::SELECT_CC,         VT, Expand);
120   setOperationAction(ISD::VSELECT,           VT, Expand);
121   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122   if (VT.isInteger()) {
123     setOperationAction(ISD::SHL, VT, Custom);
124     setOperationAction(ISD::SRA, VT, Custom);
125     setOperationAction(ISD::SRL, VT, Custom);
126   }
127
128   // Promote all bit-wise operations.
129   if (VT.isInteger() && VT != PromotedBitwiseVT) {
130     setOperationAction(ISD::AND, VT, Promote);
131     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132     setOperationAction(ISD::OR,  VT, Promote);
133     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
134     setOperationAction(ISD::XOR, VT, Promote);
135     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
136   }
137
138   // Neon does not support vector divide/remainder operations.
139   setOperationAction(ISD::SDIV, VT, Expand);
140   setOperationAction(ISD::UDIV, VT, Expand);
141   setOperationAction(ISD::FDIV, VT, Expand);
142   setOperationAction(ISD::SREM, VT, Expand);
143   setOperationAction(ISD::UREM, VT, Expand);
144   setOperationAction(ISD::FREM, VT, Expand);
145
146   if (VT.isInteger()) {
147     setOperationAction(ISD::SABSDIFF, VT, Legal);
148     setOperationAction(ISD::UABSDIFF, VT, Legal);
149   }
150   if (!VT.isFloatingPoint() &&
151       VT != MVT::v2i64 && VT != MVT::v1i64)
152     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
153       setOperationAction(Opcode, VT, Legal);
154
155 }
156
157 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::DPRRegClass);
159   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
160 }
161
162 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
163   addRegisterClass(VT, &ARM::DPairRegClass);
164   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
165 }
166
167 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
168                                      const ARMSubtarget &STI)
169     : TargetLowering(TM), Subtarget(&STI) {
170   RegInfo = Subtarget->getRegisterInfo();
171   Itins = Subtarget->getInstrItineraryData();
172
173   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174
175   if (Subtarget->isTargetMachO()) {
176     // Uses VFP for Thumb libfuncs if available.
177     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
178         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
179       static const struct {
180         const RTLIB::Libcall Op;
181         const char * const Name;
182         const ISD::CondCode Cond;
183       } LibraryCalls[] = {
184         // Single-precision floating-point arithmetic.
185         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
186         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
187         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
188         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
189
190         // Double-precision floating-point arithmetic.
191         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
192         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
193         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
194         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
195
196         // Single-precision comparisons.
197         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
198         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
199         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
200         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
201         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
202         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
203         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
204         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
205
206         // Double-precision comparisons.
207         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
208         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
209         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
210         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
211         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
212         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
213         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
214         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
215
216         // Floating-point to integer conversions.
217         // i64 conversions are done via library routines even when generating VFP
218         // instructions, so use the same ones.
219         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
220         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
221         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
222         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
223
224         // Conversions between floating types.
225         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
226         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
227
228         // Integer to floating-point conversions.
229         // i64 conversions are done via library routines even when generating VFP
230         // instructions, so use the same ones.
231         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
232         // e.g., __floatunsidf vs. __floatunssidfvfp.
233         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
234         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
235         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
236         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
237       };
238
239       for (const auto &LC : LibraryCalls) {
240         setLibcallName(LC.Op, LC.Name);
241         if (LC.Cond != ISD::SETCC_INVALID)
242           setCmpLibcallCC(LC.Op, LC.Cond);
243       }
244     }
245   }
246
247   // These libcalls are not available in 32-bit.
248   setLibcallName(RTLIB::SHL_I128, nullptr);
249   setLibcallName(RTLIB::SRL_I128, nullptr);
250   setLibcallName(RTLIB::SRA_I128, nullptr);
251
252   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
253       !Subtarget->isTargetWindows()) {
254     static const struct {
255       const RTLIB::Libcall Op;
256       const char * const Name;
257       const CallingConv::ID CC;
258       const ISD::CondCode Cond;
259     } LibraryCalls[] = {
260       // Double-precision floating-point arithmetic helper functions
261       // RTABI chapter 4.1.2, Table 2
262       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
263       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
266
267       // Double-precision floating-point comparison helper functions
268       // RTABI chapter 4.1.2, Table 3
269       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
270       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
271       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
272       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
273       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
274       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
276       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
277
278       // Single-precision floating-point arithmetic helper functions
279       // RTABI chapter 4.1.2, Table 4
280       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
281       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
284
285       // Single-precision floating-point comparison helper functions
286       // RTABI chapter 4.1.2, Table 5
287       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
288       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
289       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
290       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
291       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
292       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
294       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
295
296       // Floating-point to integer conversions.
297       // RTABI chapter 4.1.2, Table 6
298       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306
307       // Conversions between floating types.
308       // RTABI chapter 4.1.2, Table 7
309       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312
313       // Integer to floating-point conversions.
314       // RTABI chapter 4.1.2, Table 8
315       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323
324       // Long long helper functions
325       // RTABI chapter 4.2, Table 9
326       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330
331       // Integer division functions
332       // RTABI chapter 4.3.1
333       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341
342       // Memory operations
343       // RTABI chapter 4.3.4
344       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347     };
348
349     for (const auto &LC : LibraryCalls) {
350       setLibcallName(LC.Op, LC.Name);
351       setLibcallCallingConv(LC.Op, LC.CC);
352       if (LC.Cond != ISD::SETCC_INVALID)
353         setCmpLibcallCC(LC.Op, LC.Cond);
354     }
355   }
356
357   if (Subtarget->isTargetWindows()) {
358     static const struct {
359       const RTLIB::Libcall Op;
360       const char * const Name;
361       const CallingConv::ID CC;
362     } LibraryCalls[] = {
363       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
364       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
366       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
367       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
371     };
372
373     for (const auto &LC : LibraryCalls) {
374       setLibcallName(LC.Op, LC.Name);
375       setLibcallCallingConv(LC.Op, LC.CC);
376     }
377   }
378
379   // Use divmod compiler-rt calls for iOS 5.0 and later.
380   if (Subtarget->getTargetTriple().isiOS() &&
381       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
382     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
383     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
384   }
385
386   // The half <-> float conversion functions are always soft-float, but are
387   // needed for some targets which use a hard-float calling convention by
388   // default.
389   if (Subtarget->isAAPCS_ABI()) {
390     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
393   } else {
394     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
395     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
396     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
397   }
398
399   if (Subtarget->isThumb1Only())
400     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
401   else
402     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
403   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
404       !Subtarget->isThumb1Only()) {
405     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
406     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
407   }
408
409   for (MVT VT : MVT::vector_valuetypes()) {
410     for (MVT InnerVT : MVT::vector_valuetypes()) {
411       setTruncStoreAction(VT, InnerVT, Expand);
412       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
413       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
414       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
415     }
416
417     setOperationAction(ISD::MULHS, VT, Expand);
418     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
419     setOperationAction(ISD::MULHU, VT, Expand);
420     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
421
422     setOperationAction(ISD::BSWAP, VT, Expand);
423   }
424
425   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
426   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
427
428   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
429   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
430
431   if (Subtarget->hasNEON()) {
432     addDRTypeForNEON(MVT::v2f32);
433     addDRTypeForNEON(MVT::v8i8);
434     addDRTypeForNEON(MVT::v4i16);
435     addDRTypeForNEON(MVT::v2i32);
436     addDRTypeForNEON(MVT::v1i64);
437
438     addQRTypeForNEON(MVT::v4f32);
439     addQRTypeForNEON(MVT::v2f64);
440     addQRTypeForNEON(MVT::v16i8);
441     addQRTypeForNEON(MVT::v8i16);
442     addQRTypeForNEON(MVT::v4i32);
443     addQRTypeForNEON(MVT::v2i64);
444
445     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
446     // neither Neon nor VFP support any arithmetic operations on it.
447     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
448     // supported for v4f32.
449     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
450     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
451     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
452     // FIXME: Code duplication: FDIV and FREM are expanded always, see
453     // ARMTargetLowering::addTypeForNEON method for details.
454     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
455     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
456     // FIXME: Create unittest.
457     // In another words, find a way when "copysign" appears in DAG with vector
458     // operands.
459     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
460     // FIXME: Code duplication: SETCC has custom operation action, see
461     // ARMTargetLowering::addTypeForNEON method for details.
462     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
463     // FIXME: Create unittest for FNEG and for FABS.
464     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
465     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
466     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
467     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
468     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
469     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
470     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
471     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
472     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
473     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
474     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
475     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
476     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
477     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
478     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
479     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
480     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
481     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
482     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
483
484     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
485     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
486     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
487     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
488     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
489     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
490     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
491     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
492     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
493     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
494     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
495     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
496     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
497     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
498     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
499
500     // Mark v2f32 intrinsics.
501     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
502     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
503     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
504     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
505     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
506     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
507     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
508     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
509     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
510     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
511     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
512     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
513     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
514     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
515     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
516
517     // Neon does not support some operations on v1i64 and v2i64 types.
518     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
519     // Custom handling for some quad-vector types to detect VMULL.
520     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
521     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
522     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
523     // Custom handling for some vector types to avoid expensive expansions
524     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
525     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
526     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
527     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
528     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
529     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
530     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
531     // a destination type that is wider than the source, and nor does
532     // it have a FP_TO_[SU]INT instruction with a narrower destination than
533     // source.
534     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
535     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
536     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
537     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
538
539     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
540     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
541
542     // NEON does not have single instruction CTPOP for vectors with element
543     // types wider than 8-bits.  However, custom lowering can leverage the
544     // v8i8/v16i8 vcnt instruction.
545     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
546     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
547     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
548     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
549
550     // NEON does not have single instruction CTTZ for vectors.
551     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
552     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
553     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
554     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
555
556     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
557     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
558     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
559     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
560
561     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
562     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
563     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
564     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
565
566     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
567     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
568     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
569     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
570
571     // NEON only has FMA instructions as of VFP4.
572     if (!Subtarget->hasVFP4()) {
573       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
574       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
575     }
576
577     setTargetDAGCombine(ISD::INTRINSIC_VOID);
578     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
579     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
580     setTargetDAGCombine(ISD::SHL);
581     setTargetDAGCombine(ISD::SRL);
582     setTargetDAGCombine(ISD::SRA);
583     setTargetDAGCombine(ISD::SIGN_EXTEND);
584     setTargetDAGCombine(ISD::ZERO_EXTEND);
585     setTargetDAGCombine(ISD::ANY_EXTEND);
586     setTargetDAGCombine(ISD::BUILD_VECTOR);
587     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
588     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
589     setTargetDAGCombine(ISD::STORE);
590     setTargetDAGCombine(ISD::FP_TO_SINT);
591     setTargetDAGCombine(ISD::FP_TO_UINT);
592     setTargetDAGCombine(ISD::FDIV);
593     setTargetDAGCombine(ISD::LOAD);
594
595     // It is legal to extload from v4i8 to v4i16 or v4i32.
596     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
597                    MVT::v2i32}) {
598       for (MVT VT : MVT::integer_vector_valuetypes()) {
599         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
600         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
601         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
602       }
603     }
604   }
605
606   // ARM and Thumb2 support UMLAL/SMLAL.
607   if (!Subtarget->isThumb1Only())
608     setTargetDAGCombine(ISD::ADDC);
609
610   if (Subtarget->isFPOnlySP()) {
611     // When targeting a floating-point unit with only single-precision
612     // operations, f64 is legal for the few double-precision instructions which
613     // are present However, no double-precision operations other than moves,
614     // loads and stores are provided by the hardware.
615     setOperationAction(ISD::FADD,       MVT::f64, Expand);
616     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
617     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
618     setOperationAction(ISD::FMA,        MVT::f64, Expand);
619     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
620     setOperationAction(ISD::FREM,       MVT::f64, Expand);
621     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
622     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
623     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
624     setOperationAction(ISD::FABS,       MVT::f64, Expand);
625     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
626     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
627     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
628     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
629     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
630     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
631     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
632     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
633     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
634     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
635     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
636     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
637     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
638     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
639     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
640     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
641     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
642     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
643     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
644     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
645     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
646     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
647     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
648   }
649
650   computeRegisterProperties(Subtarget->getRegisterInfo());
651
652   // ARM does not have floating-point extending loads.
653   for (MVT VT : MVT::fp_valuetypes()) {
654     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
655     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
656   }
657
658   // ... or truncating stores
659   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
660   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
661   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
662
663   // ARM does not have i1 sign extending load.
664   for (MVT VT : MVT::integer_valuetypes())
665     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
666
667   // ARM supports all 4 flavors of integer indexed load / store.
668   if (!Subtarget->isThumb1Only()) {
669     for (unsigned im = (unsigned)ISD::PRE_INC;
670          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
671       setIndexedLoadAction(im,  MVT::i1,  Legal);
672       setIndexedLoadAction(im,  MVT::i8,  Legal);
673       setIndexedLoadAction(im,  MVT::i16, Legal);
674       setIndexedLoadAction(im,  MVT::i32, Legal);
675       setIndexedStoreAction(im, MVT::i1,  Legal);
676       setIndexedStoreAction(im, MVT::i8,  Legal);
677       setIndexedStoreAction(im, MVT::i16, Legal);
678       setIndexedStoreAction(im, MVT::i32, Legal);
679     }
680   }
681
682   setOperationAction(ISD::SADDO, MVT::i32, Custom);
683   setOperationAction(ISD::UADDO, MVT::i32, Custom);
684   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
685   setOperationAction(ISD::USUBO, MVT::i32, Custom);
686
687   // i64 operation support.
688   setOperationAction(ISD::MUL,     MVT::i64, Expand);
689   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
690   if (Subtarget->isThumb1Only()) {
691     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
692     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
693   }
694   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
695       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
696     setOperationAction(ISD::MULHS, MVT::i32, Expand);
697
698   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
699   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
700   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
701   setOperationAction(ISD::SRL,       MVT::i64, Custom);
702   setOperationAction(ISD::SRA,       MVT::i64, Custom);
703
704   if (!Subtarget->isThumb1Only()) {
705     // FIXME: We should do this for Thumb1 as well.
706     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
707     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
708     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
709     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
710   }
711
712   // ARM does not have ROTL.
713   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
714   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
715   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
716   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
717     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
718
719   // These just redirect to CTTZ and CTLZ on ARM.
720   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
721   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
722
723   // @llvm.readcyclecounter requires the Performance Monitors extension.
724   // Default to the 0 expansion on unsupported platforms.
725   // FIXME: Technically there are older ARM CPUs that have
726   // implementation-specific ways of obtaining this information.
727   if (Subtarget->hasPerfMon())
728     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
729
730   // Only ARMv6 has BSWAP.
731   if (!Subtarget->hasV6Ops())
732     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
733
734   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
735       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
736     // These are expanded into libcalls if the cpu doesn't have HW divider.
737     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
738     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
739   }
740
741   if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
742     setOperationAction(ISD::SDIV, MVT::i32, Custom);
743     setOperationAction(ISD::UDIV, MVT::i32, Custom);
744
745     setOperationAction(ISD::SDIV, MVT::i64, Custom);
746     setOperationAction(ISD::UDIV, MVT::i64, Custom);
747   }
748
749   setOperationAction(ISD::SREM,  MVT::i32, Expand);
750   setOperationAction(ISD::UREM,  MVT::i32, Expand);
751   // Register based DivRem for AEABI (RTABI 4.2)
752   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
753     setOperationAction(ISD::SREM, MVT::i64, Custom);
754     setOperationAction(ISD::UREM, MVT::i64, Custom);
755
756     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
757     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
758     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
759     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
760     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
761     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
762     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
763     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
764
765     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
766     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
767     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
768     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
769     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
770     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
771     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
772     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
773
774     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
775     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
776   } else {
777     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
778     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
779   }
780
781   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
782   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
783   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
784   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
785   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
786
787   setOperationAction(ISD::TRAP, MVT::Other, Legal);
788
789   // Use the default implementation.
790   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
791   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
792   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
793   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
794   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
795   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
796
797   if (!Subtarget->isTargetMachO()) {
798     // Non-MachO platforms may return values in these registers via the
799     // personality function.
800     setExceptionPointerRegister(ARM::R0);
801     setExceptionSelectorRegister(ARM::R1);
802   }
803
804   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
805     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
806   else
807     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
808
809   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
810   // the default expansion. If we are targeting a single threaded system,
811   // then set them all for expand so we can lower them later into their
812   // non-atomic form.
813   if (TM.Options.ThreadModel == ThreadModel::Single)
814     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
815   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
816     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
817     // to ldrex/strex loops already.
818     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
819
820     // On v8, we have particularly efficient implementations of atomic fences
821     // if they can be combined with nearby atomic loads and stores.
822     if (!Subtarget->hasV8Ops()) {
823       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
824       setInsertFencesForAtomic(true);
825     }
826   } else {
827     // If there's anything we can use as a barrier, go through custom lowering
828     // for ATOMIC_FENCE.
829     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
830                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
831
832     // Set them all for expansion, which will force libcalls.
833     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
834     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
835     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
836     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
837     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
838     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
839     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
840     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
841     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
842     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
843     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
844     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
845     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
846     // Unordered/Monotonic case.
847     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
848     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
849   }
850
851   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
852
853   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
854   if (!Subtarget->hasV6Ops()) {
855     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
856     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
857   }
858   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
859
860   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
861       !Subtarget->isThumb1Only()) {
862     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
863     // iff target supports vfp2.
864     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
865     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
866   }
867
868   // We want to custom lower some of our intrinsics.
869   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
870   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
871   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
872   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
873   if (Subtarget->isTargetDarwin())
874     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
875
876   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
877   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
878   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
879   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
880   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
881   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
882   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
883   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
884   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
885
886   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
887   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
888   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
889   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
890   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
891
892   // We don't support sin/cos/fmod/copysign/pow
893   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
894   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
895   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
896   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
897   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
898   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
899   setOperationAction(ISD::FREM,      MVT::f64, Expand);
900   setOperationAction(ISD::FREM,      MVT::f32, Expand);
901   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
902       !Subtarget->isThumb1Only()) {
903     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
904     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
905   }
906   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
907   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
908
909   if (!Subtarget->hasVFP4()) {
910     setOperationAction(ISD::FMA, MVT::f64, Expand);
911     setOperationAction(ISD::FMA, MVT::f32, Expand);
912   }
913
914   // Various VFP goodness
915   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
916     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
917     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
918       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
919       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
920     }
921
922     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
923     if (!Subtarget->hasFP16()) {
924       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
925       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
926     }
927   }
928
929   // Combine sin / cos into one node or libcall if possible.
930   if (Subtarget->hasSinCos()) {
931     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
932     setLibcallName(RTLIB::SINCOS_F64, "sincos");
933     if (Subtarget->getTargetTriple().isiOS()) {
934       // For iOS, we don't want to the normal expansion of a libcall to
935       // sincos. We want to issue a libcall to __sincos_stret.
936       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
937       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
938     }
939   }
940
941   // FP-ARMv8 implements a lot of rounding-like FP operations.
942   if (Subtarget->hasFPARMv8()) {
943     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
944     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
945     setOperationAction(ISD::FROUND, MVT::f32, Legal);
946     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
947     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
948     setOperationAction(ISD::FRINT, MVT::f32, Legal);
949     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
950     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
951     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
952     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
953     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
954     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
955
956     if (!Subtarget->isFPOnlySP()) {
957       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
958       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
959       setOperationAction(ISD::FROUND, MVT::f64, Legal);
960       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
961       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
962       setOperationAction(ISD::FRINT, MVT::f64, Legal);
963       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
964       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
965     }
966   }
967
968   if (Subtarget->hasNEON()) {
969     // vmin and vmax aren't available in a scalar form, so we use
970     // a NEON instruction with an undef lane instead.
971     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
972     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
973     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
974     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
975     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
976     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
977   }
978
979   // We have target-specific dag combine patterns for the following nodes:
980   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
981   setTargetDAGCombine(ISD::ADD);
982   setTargetDAGCombine(ISD::SUB);
983   setTargetDAGCombine(ISD::MUL);
984   setTargetDAGCombine(ISD::AND);
985   setTargetDAGCombine(ISD::OR);
986   setTargetDAGCombine(ISD::XOR);
987
988   if (Subtarget->hasV6Ops())
989     setTargetDAGCombine(ISD::SRL);
990
991   setStackPointerRegisterToSaveRestore(ARM::SP);
992
993   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
994       !Subtarget->hasVFP2())
995     setSchedulingPreference(Sched::RegPressure);
996   else
997     setSchedulingPreference(Sched::Hybrid);
998
999   //// temporary - rewrite interface to use type
1000   MaxStoresPerMemset = 8;
1001   MaxStoresPerMemsetOptSize = 4;
1002   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1003   MaxStoresPerMemcpyOptSize = 2;
1004   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1005   MaxStoresPerMemmoveOptSize = 2;
1006
1007   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1008   // are at least 4 bytes aligned.
1009   setMinStackArgumentAlignment(4);
1010
1011   // Prefer likely predicted branches to selects on out-of-order cores.
1012   PredictableSelectIsExpensive = Subtarget->isLikeA9();
1013
1014   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1015 }
1016
1017 bool ARMTargetLowering::useSoftFloat() const {
1018   return Subtarget->useSoftFloat();
1019 }
1020
1021 // FIXME: It might make sense to define the representative register class as the
1022 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1023 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1024 // SPR's representative would be DPR_VFP2. This should work well if register
1025 // pressure tracking were modified such that a register use would increment the
1026 // pressure of the register class's representative and all of it's super
1027 // classes' representatives transitively. We have not implemented this because
1028 // of the difficulty prior to coalescing of modeling operand register classes
1029 // due to the common occurrence of cross class copies and subregister insertions
1030 // and extractions.
1031 std::pair<const TargetRegisterClass *, uint8_t>
1032 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1033                                            MVT VT) const {
1034   const TargetRegisterClass *RRC = nullptr;
1035   uint8_t Cost = 1;
1036   switch (VT.SimpleTy) {
1037   default:
1038     return TargetLowering::findRepresentativeClass(TRI, VT);
1039   // Use DPR as representative register class for all floating point
1040   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1041   // the cost is 1 for both f32 and f64.
1042   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1043   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1044     RRC = &ARM::DPRRegClass;
1045     // When NEON is used for SP, only half of the register file is available
1046     // because operations that define both SP and DP results will be constrained
1047     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1048     // coalescing by double-counting the SP regs. See the FIXME above.
1049     if (Subtarget->useNEONForSinglePrecisionFP())
1050       Cost = 2;
1051     break;
1052   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1053   case MVT::v4f32: case MVT::v2f64:
1054     RRC = &ARM::DPRRegClass;
1055     Cost = 2;
1056     break;
1057   case MVT::v4i64:
1058     RRC = &ARM::DPRRegClass;
1059     Cost = 4;
1060     break;
1061   case MVT::v8i64:
1062     RRC = &ARM::DPRRegClass;
1063     Cost = 8;
1064     break;
1065   }
1066   return std::make_pair(RRC, Cost);
1067 }
1068
1069 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1070   switch ((ARMISD::NodeType)Opcode) {
1071   case ARMISD::FIRST_NUMBER:  break;
1072   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1073   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1074   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1075   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1076   case ARMISD::CALL:          return "ARMISD::CALL";
1077   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1078   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1079   case ARMISD::tCALL:         return "ARMISD::tCALL";
1080   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1081   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1082   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1083   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1084   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1085   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1086   case ARMISD::CMP:           return "ARMISD::CMP";
1087   case ARMISD::CMN:           return "ARMISD::CMN";
1088   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1089   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1090   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1091   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1092   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1093
1094   case ARMISD::CMOV:          return "ARMISD::CMOV";
1095
1096   case ARMISD::RBIT:          return "ARMISD::RBIT";
1097
1098   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1099   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1100   case ARMISD::RRX:           return "ARMISD::RRX";
1101
1102   case ARMISD::ADDC:          return "ARMISD::ADDC";
1103   case ARMISD::ADDE:          return "ARMISD::ADDE";
1104   case ARMISD::SUBC:          return "ARMISD::SUBC";
1105   case ARMISD::SUBE:          return "ARMISD::SUBE";
1106
1107   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1108   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1109
1110   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1111   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1112   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1113
1114   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1115
1116   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1117
1118   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1119
1120   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1121
1122   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1123
1124   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1125   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1126
1127   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1128   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1129   case ARMISD::VCGE:          return "ARMISD::VCGE";
1130   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1131   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1132   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1133   case ARMISD::VCGT:          return "ARMISD::VCGT";
1134   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1135   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1136   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1137   case ARMISD::VTST:          return "ARMISD::VTST";
1138
1139   case ARMISD::VSHL:          return "ARMISD::VSHL";
1140   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1141   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1142   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1143   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1144   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1145   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1146   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1147   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1148   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1149   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1150   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1151   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1152   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1153   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1154   case ARMISD::VSLI:          return "ARMISD::VSLI";
1155   case ARMISD::VSRI:          return "ARMISD::VSRI";
1156   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1157   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1158   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1159   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1160   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1161   case ARMISD::VDUP:          return "ARMISD::VDUP";
1162   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1163   case ARMISD::VEXT:          return "ARMISD::VEXT";
1164   case ARMISD::VREV64:        return "ARMISD::VREV64";
1165   case ARMISD::VREV32:        return "ARMISD::VREV32";
1166   case ARMISD::VREV16:        return "ARMISD::VREV16";
1167   case ARMISD::VZIP:          return "ARMISD::VZIP";
1168   case ARMISD::VUZP:          return "ARMISD::VUZP";
1169   case ARMISD::VTRN:          return "ARMISD::VTRN";
1170   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1171   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1172   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1173   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1174   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1175   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1176   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1177   case ARMISD::BFI:           return "ARMISD::BFI";
1178   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1179   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1180   case ARMISD::VBSL:          return "ARMISD::VBSL";
1181   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1182   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1183   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1184   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1185   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1186   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1187   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1188   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1189   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1190   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1191   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1192   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1193   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1194   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1195   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1196   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1197   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1198   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1199   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1200   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1201   }
1202   return nullptr;
1203 }
1204
1205 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1206                                           EVT VT) const {
1207   if (!VT.isVector())
1208     return getPointerTy(DL);
1209   return VT.changeVectorElementTypeToInteger();
1210 }
1211
1212 /// getRegClassFor - Return the register class that should be used for the
1213 /// specified value type.
1214 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1215   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1216   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1217   // load / store 4 to 8 consecutive D registers.
1218   if (Subtarget->hasNEON()) {
1219     if (VT == MVT::v4i64)
1220       return &ARM::QQPRRegClass;
1221     if (VT == MVT::v8i64)
1222       return &ARM::QQQQPRRegClass;
1223   }
1224   return TargetLowering::getRegClassFor(VT);
1225 }
1226
1227 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1228 // source/dest is aligned and the copy size is large enough. We therefore want
1229 // to align such objects passed to memory intrinsics.
1230 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1231                                                unsigned &PrefAlign) const {
1232   if (!isa<MemIntrinsic>(CI))
1233     return false;
1234   MinSize = 8;
1235   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1236   // cycle faster than 4-byte aligned LDM.
1237   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1238   return true;
1239 }
1240
1241 // Create a fast isel object.
1242 FastISel *
1243 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1244                                   const TargetLibraryInfo *libInfo) const {
1245   return ARM::createFastISel(funcInfo, libInfo);
1246 }
1247
1248 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1249   unsigned NumVals = N->getNumValues();
1250   if (!NumVals)
1251     return Sched::RegPressure;
1252
1253   for (unsigned i = 0; i != NumVals; ++i) {
1254     EVT VT = N->getValueType(i);
1255     if (VT == MVT::Glue || VT == MVT::Other)
1256       continue;
1257     if (VT.isFloatingPoint() || VT.isVector())
1258       return Sched::ILP;
1259   }
1260
1261   if (!N->isMachineOpcode())
1262     return Sched::RegPressure;
1263
1264   // Load are scheduled for latency even if there instruction itinerary
1265   // is not available.
1266   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1267   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1268
1269   if (MCID.getNumDefs() == 0)
1270     return Sched::RegPressure;
1271   if (!Itins->isEmpty() &&
1272       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1273     return Sched::ILP;
1274
1275   return Sched::RegPressure;
1276 }
1277
1278 //===----------------------------------------------------------------------===//
1279 // Lowering Code
1280 //===----------------------------------------------------------------------===//
1281
1282 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1283 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1284   switch (CC) {
1285   default: llvm_unreachable("Unknown condition code!");
1286   case ISD::SETNE:  return ARMCC::NE;
1287   case ISD::SETEQ:  return ARMCC::EQ;
1288   case ISD::SETGT:  return ARMCC::GT;
1289   case ISD::SETGE:  return ARMCC::GE;
1290   case ISD::SETLT:  return ARMCC::LT;
1291   case ISD::SETLE:  return ARMCC::LE;
1292   case ISD::SETUGT: return ARMCC::HI;
1293   case ISD::SETUGE: return ARMCC::HS;
1294   case ISD::SETULT: return ARMCC::LO;
1295   case ISD::SETULE: return ARMCC::LS;
1296   }
1297 }
1298
1299 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1300 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1301                         ARMCC::CondCodes &CondCode2) {
1302   CondCode2 = ARMCC::AL;
1303   switch (CC) {
1304   default: llvm_unreachable("Unknown FP condition!");
1305   case ISD::SETEQ:
1306   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1307   case ISD::SETGT:
1308   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1309   case ISD::SETGE:
1310   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1311   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1312   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1313   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1314   case ISD::SETO:   CondCode = ARMCC::VC; break;
1315   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1316   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1317   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1318   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1319   case ISD::SETLT:
1320   case ISD::SETULT: CondCode = ARMCC::LT; break;
1321   case ISD::SETLE:
1322   case ISD::SETULE: CondCode = ARMCC::LE; break;
1323   case ISD::SETNE:
1324   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1325   }
1326 }
1327
1328 //===----------------------------------------------------------------------===//
1329 //                      Calling Convention Implementation
1330 //===----------------------------------------------------------------------===//
1331
1332 #include "ARMGenCallingConv.inc"
1333
1334 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1335 /// account presence of floating point hardware and calling convention
1336 /// limitations, such as support for variadic functions.
1337 CallingConv::ID
1338 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1339                                            bool isVarArg) const {
1340   switch (CC) {
1341   default:
1342     llvm_unreachable("Unsupported calling convention");
1343   case CallingConv::ARM_AAPCS:
1344   case CallingConv::ARM_APCS:
1345   case CallingConv::GHC:
1346     return CC;
1347   case CallingConv::ARM_AAPCS_VFP:
1348     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1349   case CallingConv::C:
1350     if (!Subtarget->isAAPCS_ABI())
1351       return CallingConv::ARM_APCS;
1352     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1353              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1354              !isVarArg)
1355       return CallingConv::ARM_AAPCS_VFP;
1356     else
1357       return CallingConv::ARM_AAPCS;
1358   case CallingConv::Fast:
1359     if (!Subtarget->isAAPCS_ABI()) {
1360       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1361         return CallingConv::Fast;
1362       return CallingConv::ARM_APCS;
1363     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1364       return CallingConv::ARM_AAPCS_VFP;
1365     else
1366       return CallingConv::ARM_AAPCS;
1367   }
1368 }
1369
1370 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1371 /// CallingConvention.
1372 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1373                                                  bool Return,
1374                                                  bool isVarArg) const {
1375   switch (getEffectiveCallingConv(CC, isVarArg)) {
1376   default:
1377     llvm_unreachable("Unsupported calling convention");
1378   case CallingConv::ARM_APCS:
1379     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1380   case CallingConv::ARM_AAPCS:
1381     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1382   case CallingConv::ARM_AAPCS_VFP:
1383     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1384   case CallingConv::Fast:
1385     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1386   case CallingConv::GHC:
1387     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1388   }
1389 }
1390
1391 /// LowerCallResult - Lower the result values of a call into the
1392 /// appropriate copies out of appropriate physical registers.
1393 SDValue
1394 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1395                                    CallingConv::ID CallConv, bool isVarArg,
1396                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1397                                    SDLoc dl, SelectionDAG &DAG,
1398                                    SmallVectorImpl<SDValue> &InVals,
1399                                    bool isThisReturn, SDValue ThisVal) const {
1400
1401   // Assign locations to each value returned by this call.
1402   SmallVector<CCValAssign, 16> RVLocs;
1403   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1404                     *DAG.getContext(), Call);
1405   CCInfo.AnalyzeCallResult(Ins,
1406                            CCAssignFnForNode(CallConv, /* Return*/ true,
1407                                              isVarArg));
1408
1409   // Copy all of the result registers out of their specified physreg.
1410   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1411     CCValAssign VA = RVLocs[i];
1412
1413     // Pass 'this' value directly from the argument to return value, to avoid
1414     // reg unit interference
1415     if (i == 0 && isThisReturn) {
1416       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1417              "unexpected return calling convention register assignment");
1418       InVals.push_back(ThisVal);
1419       continue;
1420     }
1421
1422     SDValue Val;
1423     if (VA.needsCustom()) {
1424       // Handle f64 or half of a v2f64.
1425       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1426                                       InFlag);
1427       Chain = Lo.getValue(1);
1428       InFlag = Lo.getValue(2);
1429       VA = RVLocs[++i]; // skip ahead to next loc
1430       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1431                                       InFlag);
1432       Chain = Hi.getValue(1);
1433       InFlag = Hi.getValue(2);
1434       if (!Subtarget->isLittle())
1435         std::swap (Lo, Hi);
1436       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1437
1438       if (VA.getLocVT() == MVT::v2f64) {
1439         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1440         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1441                           DAG.getConstant(0, dl, MVT::i32));
1442
1443         VA = RVLocs[++i]; // skip ahead to next loc
1444         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1445         Chain = Lo.getValue(1);
1446         InFlag = Lo.getValue(2);
1447         VA = RVLocs[++i]; // skip ahead to next loc
1448         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1449         Chain = Hi.getValue(1);
1450         InFlag = Hi.getValue(2);
1451         if (!Subtarget->isLittle())
1452           std::swap (Lo, Hi);
1453         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1454         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1455                           DAG.getConstant(1, dl, MVT::i32));
1456       }
1457     } else {
1458       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1459                                InFlag);
1460       Chain = Val.getValue(1);
1461       InFlag = Val.getValue(2);
1462     }
1463
1464     switch (VA.getLocInfo()) {
1465     default: llvm_unreachable("Unknown loc info!");
1466     case CCValAssign::Full: break;
1467     case CCValAssign::BCvt:
1468       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1469       break;
1470     }
1471
1472     InVals.push_back(Val);
1473   }
1474
1475   return Chain;
1476 }
1477
1478 /// LowerMemOpCallTo - Store the argument to the stack.
1479 SDValue
1480 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1481                                     SDValue StackPtr, SDValue Arg,
1482                                     SDLoc dl, SelectionDAG &DAG,
1483                                     const CCValAssign &VA,
1484                                     ISD::ArgFlagsTy Flags) const {
1485   unsigned LocMemOffset = VA.getLocMemOffset();
1486   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1487   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1488                        StackPtr, PtrOff);
1489   return DAG.getStore(
1490       Chain, dl, Arg, PtrOff,
1491       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1492       false, false, 0);
1493 }
1494
1495 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1496                                          SDValue Chain, SDValue &Arg,
1497                                          RegsToPassVector &RegsToPass,
1498                                          CCValAssign &VA, CCValAssign &NextVA,
1499                                          SDValue &StackPtr,
1500                                          SmallVectorImpl<SDValue> &MemOpChains,
1501                                          ISD::ArgFlagsTy Flags) const {
1502
1503   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1504                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1505   unsigned id = Subtarget->isLittle() ? 0 : 1;
1506   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1507
1508   if (NextVA.isRegLoc())
1509     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1510   else {
1511     assert(NextVA.isMemLoc());
1512     if (!StackPtr.getNode())
1513       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1514                                     getPointerTy(DAG.getDataLayout()));
1515
1516     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1517                                            dl, DAG, NextVA,
1518                                            Flags));
1519   }
1520 }
1521
1522 /// LowerCall - Lowering a call into a callseq_start <-
1523 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1524 /// nodes.
1525 SDValue
1526 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1527                              SmallVectorImpl<SDValue> &InVals) const {
1528   SelectionDAG &DAG                     = CLI.DAG;
1529   SDLoc &dl                             = CLI.DL;
1530   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1531   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1532   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1533   SDValue Chain                         = CLI.Chain;
1534   SDValue Callee                        = CLI.Callee;
1535   bool &isTailCall                      = CLI.IsTailCall;
1536   CallingConv::ID CallConv              = CLI.CallConv;
1537   bool doesNotRet                       = CLI.DoesNotReturn;
1538   bool isVarArg                         = CLI.IsVarArg;
1539
1540   MachineFunction &MF = DAG.getMachineFunction();
1541   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1542   bool isThisReturn   = false;
1543   bool isSibCall      = false;
1544   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1545
1546   // Disable tail calls if they're not supported.
1547   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1548     isTailCall = false;
1549
1550   if (isTailCall) {
1551     // Check if it's really possible to do a tail call.
1552     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1553                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1554                                                    Outs, OutVals, Ins, DAG);
1555     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1556       report_fatal_error("failed to perform tail call elimination on a call "
1557                          "site marked musttail");
1558     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1559     // detected sibcalls.
1560     if (isTailCall) {
1561       ++NumTailCalls;
1562       isSibCall = true;
1563     }
1564   }
1565
1566   // Analyze operands of the call, assigning locations to each operand.
1567   SmallVector<CCValAssign, 16> ArgLocs;
1568   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1569                     *DAG.getContext(), Call);
1570   CCInfo.AnalyzeCallOperands(Outs,
1571                              CCAssignFnForNode(CallConv, /* Return*/ false,
1572                                                isVarArg));
1573
1574   // Get a count of how many bytes are to be pushed on the stack.
1575   unsigned NumBytes = CCInfo.getNextStackOffset();
1576
1577   // For tail calls, memory operands are available in our caller's stack.
1578   if (isSibCall)
1579     NumBytes = 0;
1580
1581   // Adjust the stack pointer for the new arguments...
1582   // These operations are automatically eliminated by the prolog/epilog pass
1583   if (!isSibCall)
1584     Chain = DAG.getCALLSEQ_START(Chain,
1585                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1586
1587   SDValue StackPtr =
1588       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1589
1590   RegsToPassVector RegsToPass;
1591   SmallVector<SDValue, 8> MemOpChains;
1592
1593   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1594   // of tail call optimization, arguments are handled later.
1595   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1596        i != e;
1597        ++i, ++realArgIdx) {
1598     CCValAssign &VA = ArgLocs[i];
1599     SDValue Arg = OutVals[realArgIdx];
1600     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1601     bool isByVal = Flags.isByVal();
1602
1603     // Promote the value if needed.
1604     switch (VA.getLocInfo()) {
1605     default: llvm_unreachable("Unknown loc info!");
1606     case CCValAssign::Full: break;
1607     case CCValAssign::SExt:
1608       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1609       break;
1610     case CCValAssign::ZExt:
1611       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1612       break;
1613     case CCValAssign::AExt:
1614       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1615       break;
1616     case CCValAssign::BCvt:
1617       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1618       break;
1619     }
1620
1621     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1622     if (VA.needsCustom()) {
1623       if (VA.getLocVT() == MVT::v2f64) {
1624         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1625                                   DAG.getConstant(0, dl, MVT::i32));
1626         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1627                                   DAG.getConstant(1, dl, MVT::i32));
1628
1629         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1630                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1631
1632         VA = ArgLocs[++i]; // skip ahead to next loc
1633         if (VA.isRegLoc()) {
1634           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1635                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1636         } else {
1637           assert(VA.isMemLoc());
1638
1639           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1640                                                  dl, DAG, VA, Flags));
1641         }
1642       } else {
1643         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1644                          StackPtr, MemOpChains, Flags);
1645       }
1646     } else if (VA.isRegLoc()) {
1647       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1648         assert(VA.getLocVT() == MVT::i32 &&
1649                "unexpected calling convention register assignment");
1650         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1651                "unexpected use of 'returned'");
1652         isThisReturn = true;
1653       }
1654       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1655     } else if (isByVal) {
1656       assert(VA.isMemLoc());
1657       unsigned offset = 0;
1658
1659       // True if this byval aggregate will be split between registers
1660       // and memory.
1661       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1662       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1663
1664       if (CurByValIdx < ByValArgsCount) {
1665
1666         unsigned RegBegin, RegEnd;
1667         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1668
1669         EVT PtrVT =
1670             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1671         unsigned int i, j;
1672         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1673           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1674           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1675           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1676                                      MachinePointerInfo(),
1677                                      false, false, false,
1678                                      DAG.InferPtrAlignment(AddArg));
1679           MemOpChains.push_back(Load.getValue(1));
1680           RegsToPass.push_back(std::make_pair(j, Load));
1681         }
1682
1683         // If parameter size outsides register area, "offset" value
1684         // helps us to calculate stack slot for remained part properly.
1685         offset = RegEnd - RegBegin;
1686
1687         CCInfo.nextInRegsParam();
1688       }
1689
1690       if (Flags.getByValSize() > 4*offset) {
1691         auto PtrVT = getPointerTy(DAG.getDataLayout());
1692         unsigned LocMemOffset = VA.getLocMemOffset();
1693         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1694         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1695         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1696         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1697         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1698                                            MVT::i32);
1699         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1700                                             MVT::i32);
1701
1702         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1703         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1704         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1705                                           Ops));
1706       }
1707     } else if (!isSibCall) {
1708       assert(VA.isMemLoc());
1709
1710       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1711                                              dl, DAG, VA, Flags));
1712     }
1713   }
1714
1715   if (!MemOpChains.empty())
1716     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1717
1718   // Build a sequence of copy-to-reg nodes chained together with token chain
1719   // and flag operands which copy the outgoing args into the appropriate regs.
1720   SDValue InFlag;
1721   // Tail call byval lowering might overwrite argument registers so in case of
1722   // tail call optimization the copies to registers are lowered later.
1723   if (!isTailCall)
1724     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1725       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1726                                RegsToPass[i].second, InFlag);
1727       InFlag = Chain.getValue(1);
1728     }
1729
1730   // For tail calls lower the arguments to the 'real' stack slot.
1731   if (isTailCall) {
1732     // Force all the incoming stack arguments to be loaded from the stack
1733     // before any new outgoing arguments are stored to the stack, because the
1734     // outgoing stack slots may alias the incoming argument stack slots, and
1735     // the alias isn't otherwise explicit. This is slightly more conservative
1736     // than necessary, because it means that each store effectively depends
1737     // on every argument instead of just those arguments it would clobber.
1738
1739     // Do not flag preceding copytoreg stuff together with the following stuff.
1740     InFlag = SDValue();
1741     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1742       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1743                                RegsToPass[i].second, InFlag);
1744       InFlag = Chain.getValue(1);
1745     }
1746     InFlag = SDValue();
1747   }
1748
1749   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1750   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1751   // node so that legalize doesn't hack it.
1752   bool isDirect = false;
1753   bool isARMFunc = false;
1754   bool isLocalARMFunc = false;
1755   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1756   auto PtrVt = getPointerTy(DAG.getDataLayout());
1757
1758   if (Subtarget->genLongCalls()) {
1759     assert((Subtarget->isTargetWindows() ||
1760             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1761            "long-calls with non-static relocation model!");
1762     // Handle a global address or an external symbol. If it's not one of
1763     // those, the target's already in a register, so we don't need to do
1764     // anything extra.
1765     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1766       const GlobalValue *GV = G->getGlobal();
1767       // Create a constant pool entry for the callee address
1768       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1769       ARMConstantPoolValue *CPV =
1770         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1771
1772       // Get the address of the callee into a register
1773       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1774       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1775       Callee = DAG.getLoad(
1776           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1777           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1778           false, false, 0);
1779     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1780       const char *Sym = S->getSymbol();
1781
1782       // Create a constant pool entry for the callee address
1783       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1784       ARMConstantPoolValue *CPV =
1785         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1786                                       ARMPCLabelIndex, 0);
1787       // Get the address of the callee into a register
1788       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1789       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1790       Callee = DAG.getLoad(
1791           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1792           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1793           false, false, 0);
1794     }
1795   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1796     const GlobalValue *GV = G->getGlobal();
1797     isDirect = true;
1798     bool isDef = GV->isStrongDefinitionForLinker();
1799     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1800                    getTargetMachine().getRelocationModel() != Reloc::Static;
1801     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1802     // ARM call to a local ARM function is predicable.
1803     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1804     // tBX takes a register source operand.
1805     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1806       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1807       Callee = DAG.getNode(
1808           ARMISD::WrapperPIC, dl, PtrVt,
1809           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1810       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1811                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1812                            false, false, true, 0);
1813     } else if (Subtarget->isTargetCOFF()) {
1814       assert(Subtarget->isTargetWindows() &&
1815              "Windows is the only supported COFF target");
1816       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1817                                  ? ARMII::MO_DLLIMPORT
1818                                  : ARMII::MO_NO_FLAG;
1819       Callee =
1820           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1821       if (GV->hasDLLImportStorageClass())
1822         Callee =
1823             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1824                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1825                         MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1826                         false, false, false, 0);
1827     } else {
1828       // On ELF targets for PIC code, direct calls should go through the PLT
1829       unsigned OpFlags = 0;
1830       if (Subtarget->isTargetELF() &&
1831           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1832         OpFlags = ARMII::MO_PLT;
1833       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1834     }
1835   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1836     isDirect = true;
1837     bool isStub = Subtarget->isTargetMachO() &&
1838                   getTargetMachine().getRelocationModel() != Reloc::Static;
1839     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1840     // tBX takes a register source operand.
1841     const char *Sym = S->getSymbol();
1842     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1843       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1844       ARMConstantPoolValue *CPV =
1845         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1846                                       ARMPCLabelIndex, 4);
1847       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1848       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1849       Callee = DAG.getLoad(
1850           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1851           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1852           false, false, 0);
1853       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1854       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1855     } else {
1856       unsigned OpFlags = 0;
1857       // On ELF targets for PIC code, direct calls should go through the PLT
1858       if (Subtarget->isTargetELF() &&
1859                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1860         OpFlags = ARMII::MO_PLT;
1861       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1862     }
1863   }
1864
1865   // FIXME: handle tail calls differently.
1866   unsigned CallOpc;
1867   if (Subtarget->isThumb()) {
1868     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1869       CallOpc = ARMISD::CALL_NOLINK;
1870     else
1871       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1872   } else {
1873     if (!isDirect && !Subtarget->hasV5TOps())
1874       CallOpc = ARMISD::CALL_NOLINK;
1875     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1876              // Emit regular call when code size is the priority
1877              !MF.getFunction()->optForMinSize())
1878       // "mov lr, pc; b _foo" to avoid confusing the RSP
1879       CallOpc = ARMISD::CALL_NOLINK;
1880     else
1881       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1882   }
1883
1884   std::vector<SDValue> Ops;
1885   Ops.push_back(Chain);
1886   Ops.push_back(Callee);
1887
1888   // Add argument registers to the end of the list so that they are known live
1889   // into the call.
1890   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1891     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1892                                   RegsToPass[i].second.getValueType()));
1893
1894   // Add a register mask operand representing the call-preserved registers.
1895   if (!isTailCall) {
1896     const uint32_t *Mask;
1897     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1898     if (isThisReturn) {
1899       // For 'this' returns, use the R0-preserving mask if applicable
1900       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1901       if (!Mask) {
1902         // Set isThisReturn to false if the calling convention is not one that
1903         // allows 'returned' to be modeled in this way, so LowerCallResult does
1904         // not try to pass 'this' straight through
1905         isThisReturn = false;
1906         Mask = ARI->getCallPreservedMask(MF, CallConv);
1907       }
1908     } else
1909       Mask = ARI->getCallPreservedMask(MF, CallConv);
1910
1911     assert(Mask && "Missing call preserved mask for calling convention");
1912     Ops.push_back(DAG.getRegisterMask(Mask));
1913   }
1914
1915   if (InFlag.getNode())
1916     Ops.push_back(InFlag);
1917
1918   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1919   if (isTailCall) {
1920     MF.getFrameInfo()->setHasTailCall();
1921     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1922   }
1923
1924   // Returns a chain and a flag for retval copy to use.
1925   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1926   InFlag = Chain.getValue(1);
1927
1928   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1929                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1930   if (!Ins.empty())
1931     InFlag = Chain.getValue(1);
1932
1933   // Handle result values, copying them out of physregs into vregs that we
1934   // return.
1935   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1936                          InVals, isThisReturn,
1937                          isThisReturn ? OutVals[0] : SDValue());
1938 }
1939
1940 /// HandleByVal - Every parameter *after* a byval parameter is passed
1941 /// on the stack.  Remember the next parameter register to allocate,
1942 /// and then confiscate the rest of the parameter registers to insure
1943 /// this.
1944 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1945                                     unsigned Align) const {
1946   assert((State->getCallOrPrologue() == Prologue ||
1947           State->getCallOrPrologue() == Call) &&
1948          "unhandled ParmContext");
1949
1950   // Byval (as with any stack) slots are always at least 4 byte aligned.
1951   Align = std::max(Align, 4U);
1952
1953   unsigned Reg = State->AllocateReg(GPRArgRegs);
1954   if (!Reg)
1955     return;
1956
1957   unsigned AlignInRegs = Align / 4;
1958   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1959   for (unsigned i = 0; i < Waste; ++i)
1960     Reg = State->AllocateReg(GPRArgRegs);
1961
1962   if (!Reg)
1963     return;
1964
1965   unsigned Excess = 4 * (ARM::R4 - Reg);
1966
1967   // Special case when NSAA != SP and parameter size greater than size of
1968   // all remained GPR regs. In that case we can't split parameter, we must
1969   // send it to stack. We also must set NCRN to R4, so waste all
1970   // remained registers.
1971   const unsigned NSAAOffset = State->getNextStackOffset();
1972   if (NSAAOffset != 0 && Size > Excess) {
1973     while (State->AllocateReg(GPRArgRegs))
1974       ;
1975     return;
1976   }
1977
1978   // First register for byval parameter is the first register that wasn't
1979   // allocated before this method call, so it would be "reg".
1980   // If parameter is small enough to be saved in range [reg, r4), then
1981   // the end (first after last) register would be reg + param-size-in-regs,
1982   // else parameter would be splitted between registers and stack,
1983   // end register would be r4 in this case.
1984   unsigned ByValRegBegin = Reg;
1985   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1986   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1987   // Note, first register is allocated in the beginning of function already,
1988   // allocate remained amount of registers we need.
1989   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1990     State->AllocateReg(GPRArgRegs);
1991   // A byval parameter that is split between registers and memory needs its
1992   // size truncated here.
1993   // In the case where the entire structure fits in registers, we set the
1994   // size in memory to zero.
1995   Size = std::max<int>(Size - Excess, 0);
1996 }
1997
1998 /// MatchingStackOffset - Return true if the given stack call argument is
1999 /// already available in the same position (relatively) of the caller's
2000 /// incoming argument stack.
2001 static
2002 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2003                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2004                          const TargetInstrInfo *TII) {
2005   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2006   int FI = INT_MAX;
2007   if (Arg.getOpcode() == ISD::CopyFromReg) {
2008     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2009     if (!TargetRegisterInfo::isVirtualRegister(VR))
2010       return false;
2011     MachineInstr *Def = MRI->getVRegDef(VR);
2012     if (!Def)
2013       return false;
2014     if (!Flags.isByVal()) {
2015       if (!TII->isLoadFromStackSlot(Def, FI))
2016         return false;
2017     } else {
2018       return false;
2019     }
2020   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2021     if (Flags.isByVal())
2022       // ByVal argument is passed in as a pointer but it's now being
2023       // dereferenced. e.g.
2024       // define @foo(%struct.X* %A) {
2025       //   tail call @bar(%struct.X* byval %A)
2026       // }
2027       return false;
2028     SDValue Ptr = Ld->getBasePtr();
2029     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2030     if (!FINode)
2031       return false;
2032     FI = FINode->getIndex();
2033   } else
2034     return false;
2035
2036   assert(FI != INT_MAX);
2037   if (!MFI->isFixedObjectIndex(FI))
2038     return false;
2039   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2040 }
2041
2042 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2043 /// for tail call optimization. Targets which want to do tail call
2044 /// optimization should implement this function.
2045 bool
2046 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2047                                                      CallingConv::ID CalleeCC,
2048                                                      bool isVarArg,
2049                                                      bool isCalleeStructRet,
2050                                                      bool isCallerStructRet,
2051                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2052                                     const SmallVectorImpl<SDValue> &OutVals,
2053                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2054                                                      SelectionDAG& DAG) const {
2055   const Function *CallerF = DAG.getMachineFunction().getFunction();
2056   CallingConv::ID CallerCC = CallerF->getCallingConv();
2057   bool CCMatch = CallerCC == CalleeCC;
2058
2059   // Look for obvious safe cases to perform tail call optimization that do not
2060   // require ABI changes. This is what gcc calls sibcall.
2061
2062   // Do not sibcall optimize vararg calls unless the call site is not passing
2063   // any arguments.
2064   if (isVarArg && !Outs.empty())
2065     return false;
2066
2067   // Exception-handling functions need a special set of instructions to indicate
2068   // a return to the hardware. Tail-calling another function would probably
2069   // break this.
2070   if (CallerF->hasFnAttribute("interrupt"))
2071     return false;
2072
2073   // Also avoid sibcall optimization if either caller or callee uses struct
2074   // return semantics.
2075   if (isCalleeStructRet || isCallerStructRet)
2076     return false;
2077
2078   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2079   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2080   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2081   // support in the assembler and linker to be used. This would need to be
2082   // fixed to fully support tail calls in Thumb1.
2083   //
2084   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2085   // LR.  This means if we need to reload LR, it takes an extra instructions,
2086   // which outweighs the value of the tail call; but here we don't know yet
2087   // whether LR is going to be used.  Probably the right approach is to
2088   // generate the tail call here and turn it back into CALL/RET in
2089   // emitEpilogue if LR is used.
2090
2091   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2092   // but we need to make sure there are enough registers; the only valid
2093   // registers are the 4 used for parameters.  We don't currently do this
2094   // case.
2095   if (Subtarget->isThumb1Only())
2096     return false;
2097
2098   // Externally-defined functions with weak linkage should not be
2099   // tail-called on ARM when the OS does not support dynamic
2100   // pre-emption of symbols, as the AAELF spec requires normal calls
2101   // to undefined weak functions to be replaced with a NOP or jump to the
2102   // next instruction. The behaviour of branch instructions in this
2103   // situation (as used for tail calls) is implementation-defined, so we
2104   // cannot rely on the linker replacing the tail call with a return.
2105   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2106     const GlobalValue *GV = G->getGlobal();
2107     const Triple &TT = getTargetMachine().getTargetTriple();
2108     if (GV->hasExternalWeakLinkage() &&
2109         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2110       return false;
2111   }
2112
2113   // If the calling conventions do not match, then we'd better make sure the
2114   // results are returned in the same way as what the caller expects.
2115   if (!CCMatch) {
2116     SmallVector<CCValAssign, 16> RVLocs1;
2117     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2118                        *DAG.getContext(), Call);
2119     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2120
2121     SmallVector<CCValAssign, 16> RVLocs2;
2122     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2123                        *DAG.getContext(), Call);
2124     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2125
2126     if (RVLocs1.size() != RVLocs2.size())
2127       return false;
2128     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2129       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2130         return false;
2131       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2132         return false;
2133       if (RVLocs1[i].isRegLoc()) {
2134         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2135           return false;
2136       } else {
2137         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2138           return false;
2139       }
2140     }
2141   }
2142
2143   // If Caller's vararg or byval argument has been split between registers and
2144   // stack, do not perform tail call, since part of the argument is in caller's
2145   // local frame.
2146   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2147                                       getInfo<ARMFunctionInfo>();
2148   if (AFI_Caller->getArgRegsSaveSize())
2149     return false;
2150
2151   // If the callee takes no arguments then go on to check the results of the
2152   // call.
2153   if (!Outs.empty()) {
2154     // Check if stack adjustment is needed. For now, do not do this if any
2155     // argument is passed on the stack.
2156     SmallVector<CCValAssign, 16> ArgLocs;
2157     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2158                       *DAG.getContext(), Call);
2159     CCInfo.AnalyzeCallOperands(Outs,
2160                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2161     if (CCInfo.getNextStackOffset()) {
2162       MachineFunction &MF = DAG.getMachineFunction();
2163
2164       // Check if the arguments are already laid out in the right way as
2165       // the caller's fixed stack objects.
2166       MachineFrameInfo *MFI = MF.getFrameInfo();
2167       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2168       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2169       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2170            i != e;
2171            ++i, ++realArgIdx) {
2172         CCValAssign &VA = ArgLocs[i];
2173         EVT RegVT = VA.getLocVT();
2174         SDValue Arg = OutVals[realArgIdx];
2175         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2176         if (VA.getLocInfo() == CCValAssign::Indirect)
2177           return false;
2178         if (VA.needsCustom()) {
2179           // f64 and vector types are split into multiple registers or
2180           // register/stack-slot combinations.  The types will not match
2181           // the registers; give up on memory f64 refs until we figure
2182           // out what to do about this.
2183           if (!VA.isRegLoc())
2184             return false;
2185           if (!ArgLocs[++i].isRegLoc())
2186             return false;
2187           if (RegVT == MVT::v2f64) {
2188             if (!ArgLocs[++i].isRegLoc())
2189               return false;
2190             if (!ArgLocs[++i].isRegLoc())
2191               return false;
2192           }
2193         } else if (!VA.isRegLoc()) {
2194           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2195                                    MFI, MRI, TII))
2196             return false;
2197         }
2198       }
2199     }
2200   }
2201
2202   return true;
2203 }
2204
2205 bool
2206 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2207                                   MachineFunction &MF, bool isVarArg,
2208                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2209                                   LLVMContext &Context) const {
2210   SmallVector<CCValAssign, 16> RVLocs;
2211   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2212   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2213                                                     isVarArg));
2214 }
2215
2216 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2217                                     SDLoc DL, SelectionDAG &DAG) {
2218   const MachineFunction &MF = DAG.getMachineFunction();
2219   const Function *F = MF.getFunction();
2220
2221   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2222
2223   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2224   // version of the "preferred return address". These offsets affect the return
2225   // instruction if this is a return from PL1 without hypervisor extensions.
2226   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2227   //    SWI:     0      "subs pc, lr, #0"
2228   //    ABORT:   +4     "subs pc, lr, #4"
2229   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2230   // UNDEF varies depending on where the exception came from ARM or Thumb
2231   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2232
2233   int64_t LROffset;
2234   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2235       IntKind == "ABORT")
2236     LROffset = 4;
2237   else if (IntKind == "SWI" || IntKind == "UNDEF")
2238     LROffset = 0;
2239   else
2240     report_fatal_error("Unsupported interrupt attribute. If present, value "
2241                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2242
2243   RetOps.insert(RetOps.begin() + 1,
2244                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2245
2246   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2247 }
2248
2249 SDValue
2250 ARMTargetLowering::LowerReturn(SDValue Chain,
2251                                CallingConv::ID CallConv, bool isVarArg,
2252                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2253                                const SmallVectorImpl<SDValue> &OutVals,
2254                                SDLoc dl, SelectionDAG &DAG) const {
2255
2256   // CCValAssign - represent the assignment of the return value to a location.
2257   SmallVector<CCValAssign, 16> RVLocs;
2258
2259   // CCState - Info about the registers and stack slots.
2260   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2261                     *DAG.getContext(), Call);
2262
2263   // Analyze outgoing return values.
2264   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2265                                                isVarArg));
2266
2267   SDValue Flag;
2268   SmallVector<SDValue, 4> RetOps;
2269   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2270   bool isLittleEndian = Subtarget->isLittle();
2271
2272   MachineFunction &MF = DAG.getMachineFunction();
2273   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2274   AFI->setReturnRegsCount(RVLocs.size());
2275
2276   // Copy the result values into the output registers.
2277   for (unsigned i = 0, realRVLocIdx = 0;
2278        i != RVLocs.size();
2279        ++i, ++realRVLocIdx) {
2280     CCValAssign &VA = RVLocs[i];
2281     assert(VA.isRegLoc() && "Can only return in registers!");
2282
2283     SDValue Arg = OutVals[realRVLocIdx];
2284
2285     switch (VA.getLocInfo()) {
2286     default: llvm_unreachable("Unknown loc info!");
2287     case CCValAssign::Full: break;
2288     case CCValAssign::BCvt:
2289       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2290       break;
2291     }
2292
2293     if (VA.needsCustom()) {
2294       if (VA.getLocVT() == MVT::v2f64) {
2295         // Extract the first half and return it in two registers.
2296         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2297                                    DAG.getConstant(0, dl, MVT::i32));
2298         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2299                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2300
2301         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2302                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2303                                  Flag);
2304         Flag = Chain.getValue(1);
2305         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2306         VA = RVLocs[++i]; // skip ahead to next loc
2307         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2308                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2309                                  Flag);
2310         Flag = Chain.getValue(1);
2311         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2312         VA = RVLocs[++i]; // skip ahead to next loc
2313
2314         // Extract the 2nd half and fall through to handle it as an f64 value.
2315         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2316                           DAG.getConstant(1, dl, MVT::i32));
2317       }
2318       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2319       // available.
2320       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2321                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2322       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2323                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2324                                Flag);
2325       Flag = Chain.getValue(1);
2326       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2327       VA = RVLocs[++i]; // skip ahead to next loc
2328       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2329                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2330                                Flag);
2331     } else
2332       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2333
2334     // Guarantee that all emitted copies are
2335     // stuck together, avoiding something bad.
2336     Flag = Chain.getValue(1);
2337     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2338   }
2339
2340   // Update chain and glue.
2341   RetOps[0] = Chain;
2342   if (Flag.getNode())
2343     RetOps.push_back(Flag);
2344
2345   // CPUs which aren't M-class use a special sequence to return from
2346   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2347   // though we use "subs pc, lr, #N").
2348   //
2349   // M-class CPUs actually use a normal return sequence with a special
2350   // (hardware-provided) value in LR, so the normal code path works.
2351   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2352       !Subtarget->isMClass()) {
2353     if (Subtarget->isThumb1Only())
2354       report_fatal_error("interrupt attribute is not supported in Thumb1");
2355     return LowerInterruptReturn(RetOps, dl, DAG);
2356   }
2357
2358   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2359 }
2360
2361 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2362   if (N->getNumValues() != 1)
2363     return false;
2364   if (!N->hasNUsesOfValue(1, 0))
2365     return false;
2366
2367   SDValue TCChain = Chain;
2368   SDNode *Copy = *N->use_begin();
2369   if (Copy->getOpcode() == ISD::CopyToReg) {
2370     // If the copy has a glue operand, we conservatively assume it isn't safe to
2371     // perform a tail call.
2372     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2373       return false;
2374     TCChain = Copy->getOperand(0);
2375   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2376     SDNode *VMov = Copy;
2377     // f64 returned in a pair of GPRs.
2378     SmallPtrSet<SDNode*, 2> Copies;
2379     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2380          UI != UE; ++UI) {
2381       if (UI->getOpcode() != ISD::CopyToReg)
2382         return false;
2383       Copies.insert(*UI);
2384     }
2385     if (Copies.size() > 2)
2386       return false;
2387
2388     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2389          UI != UE; ++UI) {
2390       SDValue UseChain = UI->getOperand(0);
2391       if (Copies.count(UseChain.getNode()))
2392         // Second CopyToReg
2393         Copy = *UI;
2394       else {
2395         // We are at the top of this chain.
2396         // If the copy has a glue operand, we conservatively assume it
2397         // isn't safe to perform a tail call.
2398         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2399           return false;
2400         // First CopyToReg
2401         TCChain = UseChain;
2402       }
2403     }
2404   } else if (Copy->getOpcode() == ISD::BITCAST) {
2405     // f32 returned in a single GPR.
2406     if (!Copy->hasOneUse())
2407       return false;
2408     Copy = *Copy->use_begin();
2409     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2410       return false;
2411     // If the copy has a glue operand, we conservatively assume it isn't safe to
2412     // perform a tail call.
2413     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2414       return false;
2415     TCChain = Copy->getOperand(0);
2416   } else {
2417     return false;
2418   }
2419
2420   bool HasRet = false;
2421   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2422        UI != UE; ++UI) {
2423     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2424         UI->getOpcode() != ARMISD::INTRET_FLAG)
2425       return false;
2426     HasRet = true;
2427   }
2428
2429   if (!HasRet)
2430     return false;
2431
2432   Chain = TCChain;
2433   return true;
2434 }
2435
2436 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2437   if (!Subtarget->supportsTailCall())
2438     return false;
2439
2440   auto Attr =
2441       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2442   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2443     return false;
2444
2445   return !Subtarget->isThumb1Only();
2446 }
2447
2448 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2449 // and pass the lower and high parts through.
2450 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2451   SDLoc DL(Op);
2452   SDValue WriteValue = Op->getOperand(2);
2453
2454   // This function is only supposed to be called for i64 type argument.
2455   assert(WriteValue.getValueType() == MVT::i64
2456           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2457
2458   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2459                            DAG.getConstant(0, DL, MVT::i32));
2460   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2461                            DAG.getConstant(1, DL, MVT::i32));
2462   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2463   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2464 }
2465
2466 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2467 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2468 // one of the above mentioned nodes. It has to be wrapped because otherwise
2469 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2470 // be used to form addressing mode. These wrapped nodes will be selected
2471 // into MOVi.
2472 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2473   EVT PtrVT = Op.getValueType();
2474   // FIXME there is no actual debug info here
2475   SDLoc dl(Op);
2476   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2477   SDValue Res;
2478   if (CP->isMachineConstantPoolEntry())
2479     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2480                                     CP->getAlignment());
2481   else
2482     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2483                                     CP->getAlignment());
2484   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2485 }
2486
2487 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2488   return MachineJumpTableInfo::EK_Inline;
2489 }
2490
2491 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2492                                              SelectionDAG &DAG) const {
2493   MachineFunction &MF = DAG.getMachineFunction();
2494   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2495   unsigned ARMPCLabelIndex = 0;
2496   SDLoc DL(Op);
2497   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2498   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2499   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2500   SDValue CPAddr;
2501   if (RelocM == Reloc::Static) {
2502     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2503   } else {
2504     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2505     ARMPCLabelIndex = AFI->createPICLabelUId();
2506     ARMConstantPoolValue *CPV =
2507       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2508                                       ARMCP::CPBlockAddress, PCAdj);
2509     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2510   }
2511   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2512   SDValue Result =
2513       DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2514                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2515                   false, false, false, 0);
2516   if (RelocM == Reloc::Static)
2517     return Result;
2518   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2519   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2520 }
2521
2522 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2523 SDValue
2524 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2525                                                  SelectionDAG &DAG) const {
2526   SDLoc dl(GA);
2527   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2528   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2529   MachineFunction &MF = DAG.getMachineFunction();
2530   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2531   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2532   ARMConstantPoolValue *CPV =
2533     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2534                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2535   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2536   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2537   Argument =
2538       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2539                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2540                   false, false, false, 0);
2541   SDValue Chain = Argument.getValue(1);
2542
2543   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2544   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2545
2546   // call __tls_get_addr.
2547   ArgListTy Args;
2548   ArgListEntry Entry;
2549   Entry.Node = Argument;
2550   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2551   Args.push_back(Entry);
2552
2553   // FIXME: is there useful debug info available here?
2554   TargetLowering::CallLoweringInfo CLI(DAG);
2555   CLI.setDebugLoc(dl).setChain(Chain)
2556     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2557                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2558                0);
2559
2560   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2561   return CallResult.first;
2562 }
2563
2564 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2565 // "local exec" model.
2566 SDValue
2567 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2568                                         SelectionDAG &DAG,
2569                                         TLSModel::Model model) const {
2570   const GlobalValue *GV = GA->getGlobal();
2571   SDLoc dl(GA);
2572   SDValue Offset;
2573   SDValue Chain = DAG.getEntryNode();
2574   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2575   // Get the Thread Pointer
2576   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2577
2578   if (model == TLSModel::InitialExec) {
2579     MachineFunction &MF = DAG.getMachineFunction();
2580     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2581     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2582     // Initial exec model.
2583     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2584     ARMConstantPoolValue *CPV =
2585       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2586                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2587                                       true);
2588     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2589     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2590     Offset = DAG.getLoad(
2591         PtrVT, dl, Chain, Offset,
2592         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2593         false, false, 0);
2594     Chain = Offset.getValue(1);
2595
2596     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2597     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2598
2599     Offset = DAG.getLoad(
2600         PtrVT, dl, Chain, Offset,
2601         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2602         false, false, 0);
2603   } else {
2604     // local exec model
2605     assert(model == TLSModel::LocalExec);
2606     ARMConstantPoolValue *CPV =
2607       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2608     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2609     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2610     Offset = DAG.getLoad(
2611         PtrVT, dl, Chain, Offset,
2612         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2613         false, false, 0);
2614   }
2615
2616   // The address of the thread local variable is the add of the thread
2617   // pointer with the offset of the variable.
2618   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2619 }
2620
2621 SDValue
2622 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2623   // TODO: implement the "local dynamic" model
2624   assert(Subtarget->isTargetELF() &&
2625          "TLS not implemented for non-ELF targets");
2626   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2627   if (DAG.getTarget().Options.EmulatedTLS)
2628     return LowerToTLSEmulatedModel(GA, DAG);
2629
2630   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2631
2632   switch (model) {
2633     case TLSModel::GeneralDynamic:
2634     case TLSModel::LocalDynamic:
2635       return LowerToTLSGeneralDynamicModel(GA, DAG);
2636     case TLSModel::InitialExec:
2637     case TLSModel::LocalExec:
2638       return LowerToTLSExecModels(GA, DAG, model);
2639   }
2640   llvm_unreachable("bogus TLS model");
2641 }
2642
2643 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2644                                                  SelectionDAG &DAG) const {
2645   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2646   SDLoc dl(Op);
2647   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2648   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2649     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2650     ARMConstantPoolValue *CPV =
2651       ARMConstantPoolConstant::Create(GV,
2652                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2653     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2654     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2655     SDValue Result = DAG.getLoad(
2656         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2657         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2658         false, false, 0);
2659     SDValue Chain = Result.getValue(1);
2660     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2661     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2662     if (!UseGOTOFF)
2663       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2664                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2665                            false, false, false, 0);
2666     return Result;
2667   }
2668
2669   // If we have T2 ops, we can materialize the address directly via movt/movw
2670   // pair. This is always cheaper.
2671   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2672     ++NumMovwMovt;
2673     // FIXME: Once remat is capable of dealing with instructions with register
2674     // operands, expand this into two nodes.
2675     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2676                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2677   } else {
2678     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2679     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2680     return DAG.getLoad(
2681         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2682         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2683         false, false, 0);
2684   }
2685 }
2686
2687 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2688                                                     SelectionDAG &DAG) const {
2689   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2690   SDLoc dl(Op);
2691   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2692   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2693
2694   if (Subtarget->useMovt(DAG.getMachineFunction()))
2695     ++NumMovwMovt;
2696
2697   // FIXME: Once remat is capable of dealing with instructions with register
2698   // operands, expand this into multiple nodes
2699   unsigned Wrapper =
2700       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2701
2702   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2703   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2704
2705   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2706     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2707                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2708                          false, false, false, 0);
2709   return Result;
2710 }
2711
2712 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2713                                                      SelectionDAG &DAG) const {
2714   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2715   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2716          "Windows on ARM expects to use movw/movt");
2717
2718   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2719   const ARMII::TOF TargetFlags =
2720     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2721   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2722   SDValue Result;
2723   SDLoc DL(Op);
2724
2725   ++NumMovwMovt;
2726
2727   // FIXME: Once remat is capable of dealing with instructions with register
2728   // operands, expand this into two nodes.
2729   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2730                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2731                                                   TargetFlags));
2732   if (GV->hasDLLImportStorageClass())
2733     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2734                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2735                          false, false, false, 0);
2736   return Result;
2737 }
2738
2739 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2740                                                     SelectionDAG &DAG) const {
2741   assert(Subtarget->isTargetELF() &&
2742          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2743   MachineFunction &MF = DAG.getMachineFunction();
2744   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2745   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2746   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2747   SDLoc dl(Op);
2748   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2749   ARMConstantPoolValue *CPV =
2750     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2751                                   ARMPCLabelIndex, PCAdj);
2752   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2753   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2754   SDValue Result =
2755       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2756                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2757                   false, false, false, 0);
2758   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2759   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2760 }
2761
2762 SDValue
2763 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2764   SDLoc dl(Op);
2765   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2766   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2767                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2768                      Op.getOperand(1), Val);
2769 }
2770
2771 SDValue
2772 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2773   SDLoc dl(Op);
2774   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2775                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2776 }
2777
2778 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2779                                                       SelectionDAG &DAG) const {
2780   SDLoc dl(Op);
2781   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2782                      Op.getOperand(0));
2783 }
2784
2785 SDValue
2786 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2787                                           const ARMSubtarget *Subtarget) const {
2788   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2789   SDLoc dl(Op);
2790   switch (IntNo) {
2791   default: return SDValue();    // Don't custom lower most intrinsics.
2792   case Intrinsic::arm_rbit: {
2793     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2794            "RBIT intrinsic must have i32 type!");
2795     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2796   }
2797   case Intrinsic::arm_thread_pointer: {
2798     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2799     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2800   }
2801   case Intrinsic::eh_sjlj_lsda: {
2802     MachineFunction &MF = DAG.getMachineFunction();
2803     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2804     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2805     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2806     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2807     SDValue CPAddr;
2808     unsigned PCAdj = (RelocM != Reloc::PIC_)
2809       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2810     ARMConstantPoolValue *CPV =
2811       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2812                                       ARMCP::CPLSDA, PCAdj);
2813     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2814     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2815     SDValue Result = DAG.getLoad(
2816         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2817         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2818         false, false, 0);
2819
2820     if (RelocM == Reloc::PIC_) {
2821       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2822       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2823     }
2824     return Result;
2825   }
2826   case Intrinsic::arm_neon_vmulls:
2827   case Intrinsic::arm_neon_vmullu: {
2828     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2829       ? ARMISD::VMULLs : ARMISD::VMULLu;
2830     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2831                        Op.getOperand(1), Op.getOperand(2));
2832   }
2833   case Intrinsic::arm_neon_vminnm:
2834   case Intrinsic::arm_neon_vmaxnm: {
2835     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2836       ? ISD::FMINNUM : ISD::FMAXNUM;
2837     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2838                        Op.getOperand(1), Op.getOperand(2));
2839   }
2840   case Intrinsic::arm_neon_vminu:
2841   case Intrinsic::arm_neon_vmaxu: {
2842     if (Op.getValueType().isFloatingPoint())
2843       return SDValue();
2844     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2845       ? ISD::UMIN : ISD::UMAX;
2846     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2847                          Op.getOperand(1), Op.getOperand(2));
2848   }
2849   case Intrinsic::arm_neon_vmins:
2850   case Intrinsic::arm_neon_vmaxs: {
2851     // v{min,max}s is overloaded between signed integers and floats.
2852     if (!Op.getValueType().isFloatingPoint()) {
2853       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2854         ? ISD::SMIN : ISD::SMAX;
2855       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2856                          Op.getOperand(1), Op.getOperand(2));
2857     }
2858     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2859       ? ISD::FMINNAN : ISD::FMAXNAN;
2860     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2861                        Op.getOperand(1), Op.getOperand(2));
2862   }
2863   }
2864 }
2865
2866 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2867                                  const ARMSubtarget *Subtarget) {
2868   // FIXME: handle "fence singlethread" more efficiently.
2869   SDLoc dl(Op);
2870   if (!Subtarget->hasDataBarrier()) {
2871     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2872     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2873     // here.
2874     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2875            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2876     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2877                        DAG.getConstant(0, dl, MVT::i32));
2878   }
2879
2880   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2881   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2882   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2883   if (Subtarget->isMClass()) {
2884     // Only a full system barrier exists in the M-class architectures.
2885     Domain = ARM_MB::SY;
2886   } else if (Subtarget->isSwift() && Ord == Release) {
2887     // Swift happens to implement ISHST barriers in a way that's compatible with
2888     // Release semantics but weaker than ISH so we'd be fools not to use
2889     // it. Beware: other processors probably don't!
2890     Domain = ARM_MB::ISHST;
2891   }
2892
2893   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2894                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2895                      DAG.getConstant(Domain, dl, MVT::i32));
2896 }
2897
2898 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2899                              const ARMSubtarget *Subtarget) {
2900   // ARM pre v5TE and Thumb1 does not have preload instructions.
2901   if (!(Subtarget->isThumb2() ||
2902         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2903     // Just preserve the chain.
2904     return Op.getOperand(0);
2905
2906   SDLoc dl(Op);
2907   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2908   if (!isRead &&
2909       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2910     // ARMv7 with MP extension has PLDW.
2911     return Op.getOperand(0);
2912
2913   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2914   if (Subtarget->isThumb()) {
2915     // Invert the bits.
2916     isRead = ~isRead & 1;
2917     isData = ~isData & 1;
2918   }
2919
2920   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2921                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2922                      DAG.getConstant(isData, dl, MVT::i32));
2923 }
2924
2925 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2926   MachineFunction &MF = DAG.getMachineFunction();
2927   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2928
2929   // vastart just stores the address of the VarArgsFrameIndex slot into the
2930   // memory location argument.
2931   SDLoc dl(Op);
2932   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2933   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2934   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2935   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2936                       MachinePointerInfo(SV), false, false, 0);
2937 }
2938
2939 SDValue
2940 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2941                                         SDValue &Root, SelectionDAG &DAG,
2942                                         SDLoc dl) const {
2943   MachineFunction &MF = DAG.getMachineFunction();
2944   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2945
2946   const TargetRegisterClass *RC;
2947   if (AFI->isThumb1OnlyFunction())
2948     RC = &ARM::tGPRRegClass;
2949   else
2950     RC = &ARM::GPRRegClass;
2951
2952   // Transform the arguments stored in physical registers into virtual ones.
2953   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2954   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2955
2956   SDValue ArgValue2;
2957   if (NextVA.isMemLoc()) {
2958     MachineFrameInfo *MFI = MF.getFrameInfo();
2959     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2960
2961     // Create load node to retrieve arguments from the stack.
2962     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2963     ArgValue2 = DAG.getLoad(
2964         MVT::i32, dl, Root, FIN,
2965         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2966         false, false, 0);
2967   } else {
2968     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2969     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2970   }
2971   if (!Subtarget->isLittle())
2972     std::swap (ArgValue, ArgValue2);
2973   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2974 }
2975
2976 // The remaining GPRs hold either the beginning of variable-argument
2977 // data, or the beginning of an aggregate passed by value (usually
2978 // byval).  Either way, we allocate stack slots adjacent to the data
2979 // provided by our caller, and store the unallocated registers there.
2980 // If this is a variadic function, the va_list pointer will begin with
2981 // these values; otherwise, this reassembles a (byval) structure that
2982 // was split between registers and memory.
2983 // Return: The frame index registers were stored into.
2984 int
2985 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2986                                   SDLoc dl, SDValue &Chain,
2987                                   const Value *OrigArg,
2988                                   unsigned InRegsParamRecordIdx,
2989                                   int ArgOffset,
2990                                   unsigned ArgSize) const {
2991   // Currently, two use-cases possible:
2992   // Case #1. Non-var-args function, and we meet first byval parameter.
2993   //          Setup first unallocated register as first byval register;
2994   //          eat all remained registers
2995   //          (these two actions are performed by HandleByVal method).
2996   //          Then, here, we initialize stack frame with
2997   //          "store-reg" instructions.
2998   // Case #2. Var-args function, that doesn't contain byval parameters.
2999   //          The same: eat all remained unallocated registers,
3000   //          initialize stack frame.
3001
3002   MachineFunction &MF = DAG.getMachineFunction();
3003   MachineFrameInfo *MFI = MF.getFrameInfo();
3004   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3005   unsigned RBegin, REnd;
3006   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3007     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3008   } else {
3009     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3010     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3011     REnd = ARM::R4;
3012   }
3013
3014   if (REnd != RBegin)
3015     ArgOffset = -4 * (ARM::R4 - RBegin);
3016
3017   auto PtrVT = getPointerTy(DAG.getDataLayout());
3018   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3019   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3020
3021   SmallVector<SDValue, 4> MemOps;
3022   const TargetRegisterClass *RC =
3023       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3024
3025   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3026     unsigned VReg = MF.addLiveIn(Reg, RC);
3027     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3028     SDValue Store =
3029         DAG.getStore(Val.getValue(1), dl, Val, FIN,
3030                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3031     MemOps.push_back(Store);
3032     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3033   }
3034
3035   if (!MemOps.empty())
3036     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3037   return FrameIndex;
3038 }
3039
3040 // Setup stack frame, the va_list pointer will start from.
3041 void
3042 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3043                                         SDLoc dl, SDValue &Chain,
3044                                         unsigned ArgOffset,
3045                                         unsigned TotalArgRegsSaveSize,
3046                                         bool ForceMutable) const {
3047   MachineFunction &MF = DAG.getMachineFunction();
3048   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3049
3050   // Try to store any remaining integer argument regs
3051   // to their spots on the stack so that they may be loaded by deferencing
3052   // the result of va_next.
3053   // If there is no regs to be stored, just point address after last
3054   // argument passed via stack.
3055   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3056                                   CCInfo.getInRegsParamsCount(),
3057                                   CCInfo.getNextStackOffset(), 4);
3058   AFI->setVarArgsFrameIndex(FrameIndex);
3059 }
3060
3061 SDValue
3062 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3063                                         CallingConv::ID CallConv, bool isVarArg,
3064                                         const SmallVectorImpl<ISD::InputArg>
3065                                           &Ins,
3066                                         SDLoc dl, SelectionDAG &DAG,
3067                                         SmallVectorImpl<SDValue> &InVals)
3068                                           const {
3069   MachineFunction &MF = DAG.getMachineFunction();
3070   MachineFrameInfo *MFI = MF.getFrameInfo();
3071
3072   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3073
3074   // Assign locations to all of the incoming arguments.
3075   SmallVector<CCValAssign, 16> ArgLocs;
3076   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3077                     *DAG.getContext(), Prologue);
3078   CCInfo.AnalyzeFormalArguments(Ins,
3079                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3080                                                   isVarArg));
3081
3082   SmallVector<SDValue, 16> ArgValues;
3083   SDValue ArgValue;
3084   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3085   unsigned CurArgIdx = 0;
3086
3087   // Initially ArgRegsSaveSize is zero.
3088   // Then we increase this value each time we meet byval parameter.
3089   // We also increase this value in case of varargs function.
3090   AFI->setArgRegsSaveSize(0);
3091
3092   // Calculate the amount of stack space that we need to allocate to store
3093   // byval and variadic arguments that are passed in registers.
3094   // We need to know this before we allocate the first byval or variadic
3095   // argument, as they will be allocated a stack slot below the CFA (Canonical
3096   // Frame Address, the stack pointer at entry to the function).
3097   unsigned ArgRegBegin = ARM::R4;
3098   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3099     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3100       break;
3101
3102     CCValAssign &VA = ArgLocs[i];
3103     unsigned Index = VA.getValNo();
3104     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3105     if (!Flags.isByVal())
3106       continue;
3107
3108     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3109     unsigned RBegin, REnd;
3110     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3111     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3112
3113     CCInfo.nextInRegsParam();
3114   }
3115   CCInfo.rewindByValRegsInfo();
3116
3117   int lastInsIndex = -1;
3118   if (isVarArg && MFI->hasVAStart()) {
3119     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3120     if (RegIdx != array_lengthof(GPRArgRegs))
3121       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3122   }
3123
3124   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3125   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3126   auto PtrVT = getPointerTy(DAG.getDataLayout());
3127
3128   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3129     CCValAssign &VA = ArgLocs[i];
3130     if (Ins[VA.getValNo()].isOrigArg()) {
3131       std::advance(CurOrigArg,
3132                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3133       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3134     }
3135     // Arguments stored in registers.
3136     if (VA.isRegLoc()) {
3137       EVT RegVT = VA.getLocVT();
3138
3139       if (VA.needsCustom()) {
3140         // f64 and vector types are split up into multiple registers or
3141         // combinations of registers and stack slots.
3142         if (VA.getLocVT() == MVT::v2f64) {
3143           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3144                                                    Chain, DAG, dl);
3145           VA = ArgLocs[++i]; // skip ahead to next loc
3146           SDValue ArgValue2;
3147           if (VA.isMemLoc()) {
3148             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3149             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3150             ArgValue2 = DAG.getLoad(
3151                 MVT::f64, dl, Chain, FIN,
3152                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3153                 false, false, false, 0);
3154           } else {
3155             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3156                                              Chain, DAG, dl);
3157           }
3158           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3159           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3160                                  ArgValue, ArgValue1,
3161                                  DAG.getIntPtrConstant(0, dl));
3162           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3163                                  ArgValue, ArgValue2,
3164                                  DAG.getIntPtrConstant(1, dl));
3165         } else
3166           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3167
3168       } else {
3169         const TargetRegisterClass *RC;
3170
3171         if (RegVT == MVT::f32)
3172           RC = &ARM::SPRRegClass;
3173         else if (RegVT == MVT::f64)
3174           RC = &ARM::DPRRegClass;
3175         else if (RegVT == MVT::v2f64)
3176           RC = &ARM::QPRRegClass;
3177         else if (RegVT == MVT::i32)
3178           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3179                                            : &ARM::GPRRegClass;
3180         else
3181           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3182
3183         // Transform the arguments in physical registers into virtual ones.
3184         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3185         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3186       }
3187
3188       // If this is an 8 or 16-bit value, it is really passed promoted
3189       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3190       // truncate to the right size.
3191       switch (VA.getLocInfo()) {
3192       default: llvm_unreachable("Unknown loc info!");
3193       case CCValAssign::Full: break;
3194       case CCValAssign::BCvt:
3195         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3196         break;
3197       case CCValAssign::SExt:
3198         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3199                                DAG.getValueType(VA.getValVT()));
3200         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3201         break;
3202       case CCValAssign::ZExt:
3203         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3204                                DAG.getValueType(VA.getValVT()));
3205         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3206         break;
3207       }
3208
3209       InVals.push_back(ArgValue);
3210
3211     } else { // VA.isRegLoc()
3212
3213       // sanity check
3214       assert(VA.isMemLoc());
3215       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3216
3217       int index = VA.getValNo();
3218
3219       // Some Ins[] entries become multiple ArgLoc[] entries.
3220       // Process them only once.
3221       if (index != lastInsIndex)
3222         {
3223           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3224           // FIXME: For now, all byval parameter objects are marked mutable.
3225           // This can be changed with more analysis.
3226           // In case of tail call optimization mark all arguments mutable.
3227           // Since they could be overwritten by lowering of arguments in case of
3228           // a tail call.
3229           if (Flags.isByVal()) {
3230             assert(Ins[index].isOrigArg() &&
3231                    "Byval arguments cannot be implicit");
3232             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3233
3234             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3235                                             CurByValIndex, VA.getLocMemOffset(),
3236                                             Flags.getByValSize());
3237             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3238             CCInfo.nextInRegsParam();
3239           } else {
3240             unsigned FIOffset = VA.getLocMemOffset();
3241             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3242                                             FIOffset, true);
3243
3244             // Create load nodes to retrieve arguments from the stack.
3245             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3246             InVals.push_back(DAG.getLoad(
3247                 VA.getValVT(), dl, Chain, FIN,
3248                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3249                 false, false, false, 0));
3250           }
3251           lastInsIndex = index;
3252         }
3253     }
3254   }
3255
3256   // varargs
3257   if (isVarArg && MFI->hasVAStart())
3258     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3259                          CCInfo.getNextStackOffset(),
3260                          TotalArgRegsSaveSize);
3261
3262   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3263
3264   return Chain;
3265 }
3266
3267 /// isFloatingPointZero - Return true if this is +0.0.
3268 static bool isFloatingPointZero(SDValue Op) {
3269   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3270     return CFP->getValueAPF().isPosZero();
3271   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3272     // Maybe this has already been legalized into the constant pool?
3273     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3274       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3275       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3276         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3277           return CFP->getValueAPF().isPosZero();
3278     }
3279   } else if (Op->getOpcode() == ISD::BITCAST &&
3280              Op->getValueType(0) == MVT::f64) {
3281     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3282     // created by LowerConstantFP().
3283     SDValue BitcastOp = Op->getOperand(0);
3284     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3285       SDValue MoveOp = BitcastOp->getOperand(0);
3286       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3287           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3288         return true;
3289       }
3290     }
3291   }
3292   return false;
3293 }
3294
3295 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3296 /// the given operands.
3297 SDValue
3298 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3299                              SDValue &ARMcc, SelectionDAG &DAG,
3300                              SDLoc dl) const {
3301   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3302     unsigned C = RHSC->getZExtValue();
3303     if (!isLegalICmpImmediate(C)) {
3304       // Constant does not fit, try adjusting it by one?
3305       switch (CC) {
3306       default: break;
3307       case ISD::SETLT:
3308       case ISD::SETGE:
3309         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3310           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3311           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3312         }
3313         break;
3314       case ISD::SETULT:
3315       case ISD::SETUGE:
3316         if (C != 0 && isLegalICmpImmediate(C-1)) {
3317           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3318           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3319         }
3320         break;
3321       case ISD::SETLE:
3322       case ISD::SETGT:
3323         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3324           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3325           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3326         }
3327         break;
3328       case ISD::SETULE:
3329       case ISD::SETUGT:
3330         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3331           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3332           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3333         }
3334         break;
3335       }
3336     }
3337   }
3338
3339   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3340   ARMISD::NodeType CompareType;
3341   switch (CondCode) {
3342   default:
3343     CompareType = ARMISD::CMP;
3344     break;
3345   case ARMCC::EQ:
3346   case ARMCC::NE:
3347     // Uses only Z Flag
3348     CompareType = ARMISD::CMPZ;
3349     break;
3350   }
3351   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3352   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3353 }
3354
3355 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3356 SDValue
3357 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3358                              SDLoc dl) const {
3359   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3360   SDValue Cmp;
3361   if (!isFloatingPointZero(RHS))
3362     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3363   else
3364     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3365   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3366 }
3367
3368 /// duplicateCmp - Glue values can have only one use, so this function
3369 /// duplicates a comparison node.
3370 SDValue
3371 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3372   unsigned Opc = Cmp.getOpcode();
3373   SDLoc DL(Cmp);
3374   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3375     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3376
3377   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3378   Cmp = Cmp.getOperand(0);
3379   Opc = Cmp.getOpcode();
3380   if (Opc == ARMISD::CMPFP)
3381     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3382   else {
3383     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3384     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3385   }
3386   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3387 }
3388
3389 std::pair<SDValue, SDValue>
3390 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3391                                  SDValue &ARMcc) const {
3392   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3393
3394   SDValue Value, OverflowCmp;
3395   SDValue LHS = Op.getOperand(0);
3396   SDValue RHS = Op.getOperand(1);
3397   SDLoc dl(Op);
3398
3399   // FIXME: We are currently always generating CMPs because we don't support
3400   // generating CMN through the backend. This is not as good as the natural
3401   // CMP case because it causes a register dependency and cannot be folded
3402   // later.
3403
3404   switch (Op.getOpcode()) {
3405   default:
3406     llvm_unreachable("Unknown overflow instruction!");
3407   case ISD::SADDO:
3408     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3409     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3410     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3411     break;
3412   case ISD::UADDO:
3413     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3414     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3415     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3416     break;
3417   case ISD::SSUBO:
3418     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3419     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3420     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3421     break;
3422   case ISD::USUBO:
3423     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3424     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3425     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3426     break;
3427   } // switch (...)
3428
3429   return std::make_pair(Value, OverflowCmp);
3430 }
3431
3432
3433 SDValue
3434 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3435   // Let legalize expand this if it isn't a legal type yet.
3436   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3437     return SDValue();
3438
3439   SDValue Value, OverflowCmp;
3440   SDValue ARMcc;
3441   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3442   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3443   SDLoc dl(Op);
3444   // We use 0 and 1 as false and true values.
3445   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3446   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3447   EVT VT = Op.getValueType();
3448
3449   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3450                                  ARMcc, CCR, OverflowCmp);
3451
3452   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3453   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3454 }
3455
3456
3457 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3458   SDValue Cond = Op.getOperand(0);
3459   SDValue SelectTrue = Op.getOperand(1);
3460   SDValue SelectFalse = Op.getOperand(2);
3461   SDLoc dl(Op);
3462   unsigned Opc = Cond.getOpcode();
3463
3464   if (Cond.getResNo() == 1 &&
3465       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3466        Opc == ISD::USUBO)) {
3467     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3468       return SDValue();
3469
3470     SDValue Value, OverflowCmp;
3471     SDValue ARMcc;
3472     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3473     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3474     EVT VT = Op.getValueType();
3475
3476     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3477                    OverflowCmp, DAG);
3478   }
3479
3480   // Convert:
3481   //
3482   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3483   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3484   //
3485   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3486     const ConstantSDNode *CMOVTrue =
3487       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3488     const ConstantSDNode *CMOVFalse =
3489       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3490
3491     if (CMOVTrue && CMOVFalse) {
3492       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3493       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3494
3495       SDValue True;
3496       SDValue False;
3497       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3498         True = SelectTrue;
3499         False = SelectFalse;
3500       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3501         True = SelectFalse;
3502         False = SelectTrue;
3503       }
3504
3505       if (True.getNode() && False.getNode()) {
3506         EVT VT = Op.getValueType();
3507         SDValue ARMcc = Cond.getOperand(2);
3508         SDValue CCR = Cond.getOperand(3);
3509         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3510         assert(True.getValueType() == VT);
3511         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3512       }
3513     }
3514   }
3515
3516   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3517   // undefined bits before doing a full-word comparison with zero.
3518   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3519                      DAG.getConstant(1, dl, Cond.getValueType()));
3520
3521   return DAG.getSelectCC(dl, Cond,
3522                          DAG.getConstant(0, dl, Cond.getValueType()),
3523                          SelectTrue, SelectFalse, ISD::SETNE);
3524 }
3525
3526 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3527                                  bool &swpCmpOps, bool &swpVselOps) {
3528   // Start by selecting the GE condition code for opcodes that return true for
3529   // 'equality'
3530   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3531       CC == ISD::SETULE)
3532     CondCode = ARMCC::GE;
3533
3534   // and GT for opcodes that return false for 'equality'.
3535   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3536            CC == ISD::SETULT)
3537     CondCode = ARMCC::GT;
3538
3539   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3540   // to swap the compare operands.
3541   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3542       CC == ISD::SETULT)
3543     swpCmpOps = true;
3544
3545   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3546   // If we have an unordered opcode, we need to swap the operands to the VSEL
3547   // instruction (effectively negating the condition).
3548   //
3549   // This also has the effect of swapping which one of 'less' or 'greater'
3550   // returns true, so we also swap the compare operands. It also switches
3551   // whether we return true for 'equality', so we compensate by picking the
3552   // opposite condition code to our original choice.
3553   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3554       CC == ISD::SETUGT) {
3555     swpCmpOps = !swpCmpOps;
3556     swpVselOps = !swpVselOps;
3557     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3558   }
3559
3560   // 'ordered' is 'anything but unordered', so use the VS condition code and
3561   // swap the VSEL operands.
3562   if (CC == ISD::SETO) {
3563     CondCode = ARMCC::VS;
3564     swpVselOps = true;
3565   }
3566
3567   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3568   // code and swap the VSEL operands.
3569   if (CC == ISD::SETUNE) {
3570     CondCode = ARMCC::EQ;
3571     swpVselOps = true;
3572   }
3573 }
3574
3575 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3576                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3577                                    SDValue Cmp, SelectionDAG &DAG) const {
3578   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3579     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3580                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3581     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3582                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3583
3584     SDValue TrueLow = TrueVal.getValue(0);
3585     SDValue TrueHigh = TrueVal.getValue(1);
3586     SDValue FalseLow = FalseVal.getValue(0);
3587     SDValue FalseHigh = FalseVal.getValue(1);
3588
3589     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3590                               ARMcc, CCR, Cmp);
3591     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3592                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3593
3594     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3595   } else {
3596     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3597                        Cmp);
3598   }
3599 }
3600
3601 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3602   EVT VT = Op.getValueType();
3603   SDValue LHS = Op.getOperand(0);
3604   SDValue RHS = Op.getOperand(1);
3605   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3606   SDValue TrueVal = Op.getOperand(2);
3607   SDValue FalseVal = Op.getOperand(3);
3608   SDLoc dl(Op);
3609
3610   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3611     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3612                                                     dl);
3613
3614     // If softenSetCCOperands only returned one value, we should compare it to
3615     // zero.
3616     if (!RHS.getNode()) {
3617       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3618       CC = ISD::SETNE;
3619     }
3620   }
3621
3622   if (LHS.getValueType() == MVT::i32) {
3623     // Try to generate VSEL on ARMv8.
3624     // The VSEL instruction can't use all the usual ARM condition
3625     // codes: it only has two bits to select the condition code, so it's
3626     // constrained to use only GE, GT, VS and EQ.
3627     //
3628     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3629     // swap the operands of the previous compare instruction (effectively
3630     // inverting the compare condition, swapping 'less' and 'greater') and
3631     // sometimes need to swap the operands to the VSEL (which inverts the
3632     // condition in the sense of firing whenever the previous condition didn't)
3633     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3634                                     TrueVal.getValueType() == MVT::f64)) {
3635       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3636       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3637           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3638         CC = ISD::getSetCCInverse(CC, true);
3639         std::swap(TrueVal, FalseVal);
3640       }
3641     }
3642
3643     SDValue ARMcc;
3644     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3645     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3646     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3647   }
3648
3649   ARMCC::CondCodes CondCode, CondCode2;
3650   FPCCToARMCC(CC, CondCode, CondCode2);
3651
3652   // Try to generate VMAXNM/VMINNM on ARMv8.
3653   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3654                                   TrueVal.getValueType() == MVT::f64)) {
3655     bool swpCmpOps = false;
3656     bool swpVselOps = false;
3657     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3658
3659     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3660         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3661       if (swpCmpOps)
3662         std::swap(LHS, RHS);
3663       if (swpVselOps)
3664         std::swap(TrueVal, FalseVal);
3665     }
3666   }
3667
3668   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3669   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3670   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3671   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3672   if (CondCode2 != ARMCC::AL) {
3673     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3674     // FIXME: Needs another CMP because flag can have but one use.
3675     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3676     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3677   }
3678   return Result;
3679 }
3680
3681 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3682 /// to morph to an integer compare sequence.
3683 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3684                            const ARMSubtarget *Subtarget) {
3685   SDNode *N = Op.getNode();
3686   if (!N->hasOneUse())
3687     // Otherwise it requires moving the value from fp to integer registers.
3688     return false;
3689   if (!N->getNumValues())
3690     return false;
3691   EVT VT = Op.getValueType();
3692   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3693     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3694     // vmrs are very slow, e.g. cortex-a8.
3695     return false;
3696
3697   if (isFloatingPointZero(Op)) {
3698     SeenZero = true;
3699     return true;
3700   }
3701   return ISD::isNormalLoad(N);
3702 }
3703
3704 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3705   if (isFloatingPointZero(Op))
3706     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3707
3708   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3709     return DAG.getLoad(MVT::i32, SDLoc(Op),
3710                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3711                        Ld->isVolatile(), Ld->isNonTemporal(),
3712                        Ld->isInvariant(), Ld->getAlignment());
3713
3714   llvm_unreachable("Unknown VFP cmp argument!");
3715 }
3716
3717 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3718                            SDValue &RetVal1, SDValue &RetVal2) {
3719   SDLoc dl(Op);
3720
3721   if (isFloatingPointZero(Op)) {
3722     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3723     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3724     return;
3725   }
3726
3727   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3728     SDValue Ptr = Ld->getBasePtr();
3729     RetVal1 = DAG.getLoad(MVT::i32, dl,
3730                           Ld->getChain(), Ptr,
3731                           Ld->getPointerInfo(),
3732                           Ld->isVolatile(), Ld->isNonTemporal(),
3733                           Ld->isInvariant(), Ld->getAlignment());
3734
3735     EVT PtrType = Ptr.getValueType();
3736     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3737     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3738                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3739     RetVal2 = DAG.getLoad(MVT::i32, dl,
3740                           Ld->getChain(), NewPtr,
3741                           Ld->getPointerInfo().getWithOffset(4),
3742                           Ld->isVolatile(), Ld->isNonTemporal(),
3743                           Ld->isInvariant(), NewAlign);
3744     return;
3745   }
3746
3747   llvm_unreachable("Unknown VFP cmp argument!");
3748 }
3749
3750 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3751 /// f32 and even f64 comparisons to integer ones.
3752 SDValue
3753 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3754   SDValue Chain = Op.getOperand(0);
3755   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3756   SDValue LHS = Op.getOperand(2);
3757   SDValue RHS = Op.getOperand(3);
3758   SDValue Dest = Op.getOperand(4);
3759   SDLoc dl(Op);
3760
3761   bool LHSSeenZero = false;
3762   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3763   bool RHSSeenZero = false;
3764   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3765   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3766     // If unsafe fp math optimization is enabled and there are no other uses of
3767     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3768     // to an integer comparison.
3769     if (CC == ISD::SETOEQ)
3770       CC = ISD::SETEQ;
3771     else if (CC == ISD::SETUNE)
3772       CC = ISD::SETNE;
3773
3774     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3775     SDValue ARMcc;
3776     if (LHS.getValueType() == MVT::f32) {
3777       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3778                         bitcastf32Toi32(LHS, DAG), Mask);
3779       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3780                         bitcastf32Toi32(RHS, DAG), Mask);
3781       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3782       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3783       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3784                          Chain, Dest, ARMcc, CCR, Cmp);
3785     }
3786
3787     SDValue LHS1, LHS2;
3788     SDValue RHS1, RHS2;
3789     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3790     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3791     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3792     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3793     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3794     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3795     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3796     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3797     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3798   }
3799
3800   return SDValue();
3801 }
3802
3803 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3804   SDValue Chain = Op.getOperand(0);
3805   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3806   SDValue LHS = Op.getOperand(2);
3807   SDValue RHS = Op.getOperand(3);
3808   SDValue Dest = Op.getOperand(4);
3809   SDLoc dl(Op);
3810
3811   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3812     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3813                                                     dl);
3814
3815     // If softenSetCCOperands only returned one value, we should compare it to
3816     // zero.
3817     if (!RHS.getNode()) {
3818       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3819       CC = ISD::SETNE;
3820     }
3821   }
3822
3823   if (LHS.getValueType() == MVT::i32) {
3824     SDValue ARMcc;
3825     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3826     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3827     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3828                        Chain, Dest, ARMcc, CCR, Cmp);
3829   }
3830
3831   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3832
3833   if (getTargetMachine().Options.UnsafeFPMath &&
3834       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3835        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3836     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3837     if (Result.getNode())
3838       return Result;
3839   }
3840
3841   ARMCC::CondCodes CondCode, CondCode2;
3842   FPCCToARMCC(CC, CondCode, CondCode2);
3843
3844   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3845   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3846   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3847   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3848   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3849   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3850   if (CondCode2 != ARMCC::AL) {
3851     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3852     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3853     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3854   }
3855   return Res;
3856 }
3857
3858 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3859   SDValue Chain = Op.getOperand(0);
3860   SDValue Table = Op.getOperand(1);
3861   SDValue Index = Op.getOperand(2);
3862   SDLoc dl(Op);
3863
3864   EVT PTy = getPointerTy(DAG.getDataLayout());
3865   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3866   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3867   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3868   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3869   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3870   if (Subtarget->isThumb2()) {
3871     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3872     // which does another jump to the destination. This also makes it easier
3873     // to translate it to TBB / TBH later.
3874     // FIXME: This might not work if the function is extremely large.
3875     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3876                        Addr, Op.getOperand(2), JTI);
3877   }
3878   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3879     Addr =
3880         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3881                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3882                     false, false, false, 0);
3883     Chain = Addr.getValue(1);
3884     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3885     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3886   } else {
3887     Addr =
3888         DAG.getLoad(PTy, dl, Chain, Addr,
3889                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3890                     false, false, false, 0);
3891     Chain = Addr.getValue(1);
3892     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3893   }
3894 }
3895
3896 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3897   EVT VT = Op.getValueType();
3898   SDLoc dl(Op);
3899
3900   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3901     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3902       return Op;
3903     return DAG.UnrollVectorOp(Op.getNode());
3904   }
3905
3906   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3907          "Invalid type for custom lowering!");
3908   if (VT != MVT::v4i16)
3909     return DAG.UnrollVectorOp(Op.getNode());
3910
3911   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3912   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3913 }
3914
3915 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3916   EVT VT = Op.getValueType();
3917   if (VT.isVector())
3918     return LowerVectorFP_TO_INT(Op, DAG);
3919   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3920     RTLIB::Libcall LC;
3921     if (Op.getOpcode() == ISD::FP_TO_SINT)
3922       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3923                               Op.getValueType());
3924     else
3925       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3926                               Op.getValueType());
3927     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3928                        /*isSigned*/ false, SDLoc(Op)).first;
3929   }
3930
3931   return Op;
3932 }
3933
3934 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3935   EVT VT = Op.getValueType();
3936   SDLoc dl(Op);
3937
3938   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3939     if (VT.getVectorElementType() == MVT::f32)
3940       return Op;
3941     return DAG.UnrollVectorOp(Op.getNode());
3942   }
3943
3944   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3945          "Invalid type for custom lowering!");
3946   if (VT != MVT::v4f32)
3947     return DAG.UnrollVectorOp(Op.getNode());
3948
3949   unsigned CastOpc;
3950   unsigned Opc;
3951   switch (Op.getOpcode()) {
3952   default: llvm_unreachable("Invalid opcode!");
3953   case ISD::SINT_TO_FP:
3954     CastOpc = ISD::SIGN_EXTEND;
3955     Opc = ISD::SINT_TO_FP;
3956     break;
3957   case ISD::UINT_TO_FP:
3958     CastOpc = ISD::ZERO_EXTEND;
3959     Opc = ISD::UINT_TO_FP;
3960     break;
3961   }
3962
3963   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3964   return DAG.getNode(Opc, dl, VT, Op);
3965 }
3966
3967 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3968   EVT VT = Op.getValueType();
3969   if (VT.isVector())
3970     return LowerVectorINT_TO_FP(Op, DAG);
3971   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3972     RTLIB::Libcall LC;
3973     if (Op.getOpcode() == ISD::SINT_TO_FP)
3974       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3975                               Op.getValueType());
3976     else
3977       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3978                               Op.getValueType());
3979     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3980                        /*isSigned*/ false, SDLoc(Op)).first;
3981   }
3982
3983   return Op;
3984 }
3985
3986 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3987   // Implement fcopysign with a fabs and a conditional fneg.
3988   SDValue Tmp0 = Op.getOperand(0);
3989   SDValue Tmp1 = Op.getOperand(1);
3990   SDLoc dl(Op);
3991   EVT VT = Op.getValueType();
3992   EVT SrcVT = Tmp1.getValueType();
3993   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3994     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3995   bool UseNEON = !InGPR && Subtarget->hasNEON();
3996
3997   if (UseNEON) {
3998     // Use VBSL to copy the sign bit.
3999     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4000     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4001                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4002     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4003     if (VT == MVT::f64)
4004       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4005                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4006                          DAG.getConstant(32, dl, MVT::i32));
4007     else /*if (VT == MVT::f32)*/
4008       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4009     if (SrcVT == MVT::f32) {
4010       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4011       if (VT == MVT::f64)
4012         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4013                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4014                            DAG.getConstant(32, dl, MVT::i32));
4015     } else if (VT == MVT::f32)
4016       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4017                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4018                          DAG.getConstant(32, dl, MVT::i32));
4019     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4020     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4021
4022     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4023                                             dl, MVT::i32);
4024     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4025     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4026                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4027
4028     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4029                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4030                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4031     if (VT == MVT::f32) {
4032       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4033       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4034                         DAG.getConstant(0, dl, MVT::i32));
4035     } else {
4036       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4037     }
4038
4039     return Res;
4040   }
4041
4042   // Bitcast operand 1 to i32.
4043   if (SrcVT == MVT::f64)
4044     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4045                        Tmp1).getValue(1);
4046   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4047
4048   // Or in the signbit with integer operations.
4049   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4050   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4051   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4052   if (VT == MVT::f32) {
4053     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4054                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4055     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4056                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4057   }
4058
4059   // f64: Or the high part with signbit and then combine two parts.
4060   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4061                      Tmp0);
4062   SDValue Lo = Tmp0.getValue(0);
4063   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4064   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4065   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4066 }
4067
4068 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4069   MachineFunction &MF = DAG.getMachineFunction();
4070   MachineFrameInfo *MFI = MF.getFrameInfo();
4071   MFI->setReturnAddressIsTaken(true);
4072
4073   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4074     return SDValue();
4075
4076   EVT VT = Op.getValueType();
4077   SDLoc dl(Op);
4078   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4079   if (Depth) {
4080     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4081     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4082     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4083                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4084                        MachinePointerInfo(), false, false, false, 0);
4085   }
4086
4087   // Return LR, which contains the return address. Mark it an implicit live-in.
4088   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4089   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4090 }
4091
4092 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4093   const ARMBaseRegisterInfo &ARI =
4094     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4095   MachineFunction &MF = DAG.getMachineFunction();
4096   MachineFrameInfo *MFI = MF.getFrameInfo();
4097   MFI->setFrameAddressIsTaken(true);
4098
4099   EVT VT = Op.getValueType();
4100   SDLoc dl(Op);  // FIXME probably not meaningful
4101   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4102   unsigned FrameReg = ARI.getFrameRegister(MF);
4103   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4104   while (Depth--)
4105     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4106                             MachinePointerInfo(),
4107                             false, false, false, 0);
4108   return FrameAddr;
4109 }
4110
4111 // FIXME? Maybe this could be a TableGen attribute on some registers and
4112 // this table could be generated automatically from RegInfo.
4113 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4114                                               SelectionDAG &DAG) const {
4115   unsigned Reg = StringSwitch<unsigned>(RegName)
4116                        .Case("sp", ARM::SP)
4117                        .Default(0);
4118   if (Reg)
4119     return Reg;
4120   report_fatal_error(Twine("Invalid register name \""
4121                               + StringRef(RegName)  + "\"."));
4122 }
4123
4124 // Result is 64 bit value so split into two 32 bit values and return as a
4125 // pair of values.
4126 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4127                                 SelectionDAG &DAG) {
4128   SDLoc DL(N);
4129
4130   // This function is only supposed to be called for i64 type destination.
4131   assert(N->getValueType(0) == MVT::i64
4132           && "ExpandREAD_REGISTER called for non-i64 type result.");
4133
4134   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4135                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4136                              N->getOperand(0),
4137                              N->getOperand(1));
4138
4139   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4140                     Read.getValue(1)));
4141   Results.push_back(Read.getOperand(0));
4142 }
4143
4144 /// ExpandBITCAST - If the target supports VFP, this function is called to
4145 /// expand a bit convert where either the source or destination type is i64 to
4146 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4147 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4148 /// vectors), since the legalizer won't know what to do with that.
4149 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4150   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4151   SDLoc dl(N);
4152   SDValue Op = N->getOperand(0);
4153
4154   // This function is only supposed to be called for i64 types, either as the
4155   // source or destination of the bit convert.
4156   EVT SrcVT = Op.getValueType();
4157   EVT DstVT = N->getValueType(0);
4158   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4159          "ExpandBITCAST called for non-i64 type");
4160
4161   // Turn i64->f64 into VMOVDRR.
4162   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4163     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4164                              DAG.getConstant(0, dl, MVT::i32));
4165     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4166                              DAG.getConstant(1, dl, MVT::i32));
4167     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4168                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4169   }
4170
4171   // Turn f64->i64 into VMOVRRD.
4172   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4173     SDValue Cvt;
4174     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4175         SrcVT.getVectorNumElements() > 1)
4176       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4177                         DAG.getVTList(MVT::i32, MVT::i32),
4178                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4179     else
4180       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4181                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4182     // Merge the pieces into a single i64 value.
4183     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4184   }
4185
4186   return SDValue();
4187 }
4188
4189 /// getZeroVector - Returns a vector of specified type with all zero elements.
4190 /// Zero vectors are used to represent vector negation and in those cases
4191 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4192 /// not support i64 elements, so sometimes the zero vectors will need to be
4193 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4194 /// zero vector.
4195 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4196   assert(VT.isVector() && "Expected a vector type");
4197   // The canonical modified immediate encoding of a zero vector is....0!
4198   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4199   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4200   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4201   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4202 }
4203
4204 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4205 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4206 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4207                                                 SelectionDAG &DAG) const {
4208   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4209   EVT VT = Op.getValueType();
4210   unsigned VTBits = VT.getSizeInBits();
4211   SDLoc dl(Op);
4212   SDValue ShOpLo = Op.getOperand(0);
4213   SDValue ShOpHi = Op.getOperand(1);
4214   SDValue ShAmt  = Op.getOperand(2);
4215   SDValue ARMcc;
4216   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4217
4218   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4219
4220   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4221                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4222   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4223   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4224                                    DAG.getConstant(VTBits, dl, MVT::i32));
4225   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4226   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4227   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4228
4229   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4230   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4231                           ISD::SETGE, ARMcc, DAG, dl);
4232   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4233   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4234                            CCR, Cmp);
4235
4236   SDValue Ops[2] = { Lo, Hi };
4237   return DAG.getMergeValues(Ops, dl);
4238 }
4239
4240 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4241 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4242 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4243                                                SelectionDAG &DAG) const {
4244   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4245   EVT VT = Op.getValueType();
4246   unsigned VTBits = VT.getSizeInBits();
4247   SDLoc dl(Op);
4248   SDValue ShOpLo = Op.getOperand(0);
4249   SDValue ShOpHi = Op.getOperand(1);
4250   SDValue ShAmt  = Op.getOperand(2);
4251   SDValue ARMcc;
4252
4253   assert(Op.getOpcode() == ISD::SHL_PARTS);
4254   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4255                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4256   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4257   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4258                                    DAG.getConstant(VTBits, dl, MVT::i32));
4259   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4260   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4261
4262   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4263   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4264   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4265                           ISD::SETGE, ARMcc, DAG, dl);
4266   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4267   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4268                            CCR, Cmp);
4269
4270   SDValue Ops[2] = { Lo, Hi };
4271   return DAG.getMergeValues(Ops, dl);
4272 }
4273
4274 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4275                                             SelectionDAG &DAG) const {
4276   // The rounding mode is in bits 23:22 of the FPSCR.
4277   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4278   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4279   // so that the shift + and get folded into a bitfield extract.
4280   SDLoc dl(Op);
4281   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4282                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4283                                               MVT::i32));
4284   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4285                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4286   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4287                               DAG.getConstant(22, dl, MVT::i32));
4288   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4289                      DAG.getConstant(3, dl, MVT::i32));
4290 }
4291
4292 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4293                          const ARMSubtarget *ST) {
4294   SDLoc dl(N);
4295   EVT VT = N->getValueType(0);
4296   if (VT.isVector()) {
4297     assert(ST->hasNEON());
4298
4299     // Compute the least significant set bit: LSB = X & -X
4300     SDValue X = N->getOperand(0);
4301     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4302     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4303
4304     EVT ElemTy = VT.getVectorElementType();
4305
4306     if (ElemTy == MVT::i8) {
4307       // Compute with: cttz(x) = ctpop(lsb - 1)
4308       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4309                                 DAG.getTargetConstant(1, dl, ElemTy));
4310       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4311       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4312     }
4313
4314     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4315         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4316       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4317       unsigned NumBits = ElemTy.getSizeInBits();
4318       SDValue WidthMinus1 =
4319           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4320                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4321       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4322       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4323     }
4324
4325     // Compute with: cttz(x) = ctpop(lsb - 1)
4326
4327     // Since we can only compute the number of bits in a byte with vcnt.8, we
4328     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4329     // and i64.
4330
4331     // Compute LSB - 1.
4332     SDValue Bits;
4333     if (ElemTy == MVT::i64) {
4334       // Load constant 0xffff'ffff'ffff'ffff to register.
4335       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4336                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4337       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4338     } else {
4339       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4340                                 DAG.getTargetConstant(1, dl, ElemTy));
4341       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4342     }
4343
4344     // Count #bits with vcnt.8.
4345     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4346     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4347     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4348
4349     // Gather the #bits with vpaddl (pairwise add.)
4350     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4351     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4352         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4353         Cnt8);
4354     if (ElemTy == MVT::i16)
4355       return Cnt16;
4356
4357     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4358     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4359         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4360         Cnt16);
4361     if (ElemTy == MVT::i32)
4362       return Cnt32;
4363
4364     assert(ElemTy == MVT::i64);
4365     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4366         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4367         Cnt32);
4368     return Cnt64;
4369   }
4370
4371   if (!ST->hasV6T2Ops())
4372     return SDValue();
4373
4374   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4375   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4376 }
4377
4378 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4379 /// for each 16-bit element from operand, repeated.  The basic idea is to
4380 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4381 ///
4382 /// Trace for v4i16:
4383 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4384 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4385 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4386 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4387 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4388 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4389 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4390 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4391 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4392   EVT VT = N->getValueType(0);
4393   SDLoc DL(N);
4394
4395   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4396   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4397   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4398   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4399   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4400   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4401 }
4402
4403 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4404 /// bit-count for each 16-bit element from the operand.  We need slightly
4405 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4406 /// 64/128-bit registers.
4407 ///
4408 /// Trace for v4i16:
4409 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4410 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4411 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4412 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4413 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4414   EVT VT = N->getValueType(0);
4415   SDLoc DL(N);
4416
4417   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4418   if (VT.is64BitVector()) {
4419     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4420     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4421                        DAG.getIntPtrConstant(0, DL));
4422   } else {
4423     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4424                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4425     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4426   }
4427 }
4428
4429 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4430 /// bit-count for each 32-bit element from the operand.  The idea here is
4431 /// to split the vector into 16-bit elements, leverage the 16-bit count
4432 /// routine, and then combine the results.
4433 ///
4434 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4435 /// input    = [v0    v1    ] (vi: 32-bit elements)
4436 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4437 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4438 /// vrev: N0 = [k1 k0 k3 k2 ]
4439 ///            [k0 k1 k2 k3 ]
4440 ///       N1 =+[k1 k0 k3 k2 ]
4441 ///            [k0 k2 k1 k3 ]
4442 ///       N2 =+[k1 k3 k0 k2 ]
4443 ///            [k0    k2    k1    k3    ]
4444 /// Extended =+[k1    k3    k0    k2    ]
4445 ///            [k0    k2    ]
4446 /// Extracted=+[k1    k3    ]
4447 ///
4448 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4449   EVT VT = N->getValueType(0);
4450   SDLoc DL(N);
4451
4452   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4453
4454   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4455   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4456   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4457   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4458   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4459
4460   if (VT.is64BitVector()) {
4461     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4462     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4463                        DAG.getIntPtrConstant(0, DL));
4464   } else {
4465     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4466                                     DAG.getIntPtrConstant(0, DL));
4467     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4468   }
4469 }
4470
4471 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4472                           const ARMSubtarget *ST) {
4473   EVT VT = N->getValueType(0);
4474
4475   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4476   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4477           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4478          "Unexpected type for custom ctpop lowering");
4479
4480   if (VT.getVectorElementType() == MVT::i32)
4481     return lowerCTPOP32BitElements(N, DAG);
4482   else
4483     return lowerCTPOP16BitElements(N, DAG);
4484 }
4485
4486 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4487                           const ARMSubtarget *ST) {
4488   EVT VT = N->getValueType(0);
4489   SDLoc dl(N);
4490
4491   if (!VT.isVector())
4492     return SDValue();
4493
4494   // Lower vector shifts on NEON to use VSHL.
4495   assert(ST->hasNEON() && "unexpected vector shift");
4496
4497   // Left shifts translate directly to the vshiftu intrinsic.
4498   if (N->getOpcode() == ISD::SHL)
4499     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4500                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4501                                        MVT::i32),
4502                        N->getOperand(0), N->getOperand(1));
4503
4504   assert((N->getOpcode() == ISD::SRA ||
4505           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4506
4507   // NEON uses the same intrinsics for both left and right shifts.  For
4508   // right shifts, the shift amounts are negative, so negate the vector of
4509   // shift amounts.
4510   EVT ShiftVT = N->getOperand(1).getValueType();
4511   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4512                                      getZeroVector(ShiftVT, DAG, dl),
4513                                      N->getOperand(1));
4514   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4515                              Intrinsic::arm_neon_vshifts :
4516                              Intrinsic::arm_neon_vshiftu);
4517   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4518                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4519                      N->getOperand(0), NegatedCount);
4520 }
4521
4522 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4523                                 const ARMSubtarget *ST) {
4524   EVT VT = N->getValueType(0);
4525   SDLoc dl(N);
4526
4527   // We can get here for a node like i32 = ISD::SHL i32, i64
4528   if (VT != MVT::i64)
4529     return SDValue();
4530
4531   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4532          "Unknown shift to lower!");
4533
4534   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4535   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4536       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4537     return SDValue();
4538
4539   // If we are in thumb mode, we don't have RRX.
4540   if (ST->isThumb1Only()) return SDValue();
4541
4542   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4543   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4544                            DAG.getConstant(0, dl, MVT::i32));
4545   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4546                            DAG.getConstant(1, dl, MVT::i32));
4547
4548   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4549   // captures the result into a carry flag.
4550   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4551   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4552
4553   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4554   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4555
4556   // Merge the pieces into a single i64 value.
4557  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4558 }
4559
4560 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4561   SDValue TmpOp0, TmpOp1;
4562   bool Invert = false;
4563   bool Swap = false;
4564   unsigned Opc = 0;
4565
4566   SDValue Op0 = Op.getOperand(0);
4567   SDValue Op1 = Op.getOperand(1);
4568   SDValue CC = Op.getOperand(2);
4569   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4570   EVT VT = Op.getValueType();
4571   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4572   SDLoc dl(Op);
4573
4574   if (CmpVT.getVectorElementType() == MVT::i64)
4575     // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4576     // but it's possible that our operands are 64-bit but our result is 32-bit.
4577     // Bail in this case.
4578     return SDValue();
4579
4580   if (Op1.getValueType().isFloatingPoint()) {
4581     switch (SetCCOpcode) {
4582     default: llvm_unreachable("Illegal FP comparison");
4583     case ISD::SETUNE:
4584     case ISD::SETNE:  Invert = true; // Fallthrough
4585     case ISD::SETOEQ:
4586     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4587     case ISD::SETOLT:
4588     case ISD::SETLT: Swap = true; // Fallthrough
4589     case ISD::SETOGT:
4590     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4591     case ISD::SETOLE:
4592     case ISD::SETLE:  Swap = true; // Fallthrough
4593     case ISD::SETOGE:
4594     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4595     case ISD::SETUGE: Swap = true; // Fallthrough
4596     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4597     case ISD::SETUGT: Swap = true; // Fallthrough
4598     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4599     case ISD::SETUEQ: Invert = true; // Fallthrough
4600     case ISD::SETONE:
4601       // Expand this to (OLT | OGT).
4602       TmpOp0 = Op0;
4603       TmpOp1 = Op1;
4604       Opc = ISD::OR;
4605       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4606       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4607       break;
4608     case ISD::SETUO: Invert = true; // Fallthrough
4609     case ISD::SETO:
4610       // Expand this to (OLT | OGE).
4611       TmpOp0 = Op0;
4612       TmpOp1 = Op1;
4613       Opc = ISD::OR;
4614       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4615       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4616       break;
4617     }
4618   } else {
4619     // Integer comparisons.
4620     switch (SetCCOpcode) {
4621     default: llvm_unreachable("Illegal integer comparison");
4622     case ISD::SETNE:  Invert = true;
4623     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4624     case ISD::SETLT:  Swap = true;
4625     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4626     case ISD::SETLE:  Swap = true;
4627     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4628     case ISD::SETULT: Swap = true;
4629     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4630     case ISD::SETULE: Swap = true;
4631     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4632     }
4633
4634     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4635     if (Opc == ARMISD::VCEQ) {
4636
4637       SDValue AndOp;
4638       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4639         AndOp = Op0;
4640       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4641         AndOp = Op1;
4642
4643       // Ignore bitconvert.
4644       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4645         AndOp = AndOp.getOperand(0);
4646
4647       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4648         Opc = ARMISD::VTST;
4649         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4650         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4651         Invert = !Invert;
4652       }
4653     }
4654   }
4655
4656   if (Swap)
4657     std::swap(Op0, Op1);
4658
4659   // If one of the operands is a constant vector zero, attempt to fold the
4660   // comparison to a specialized compare-against-zero form.
4661   SDValue SingleOp;
4662   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4663     SingleOp = Op0;
4664   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4665     if (Opc == ARMISD::VCGE)
4666       Opc = ARMISD::VCLEZ;
4667     else if (Opc == ARMISD::VCGT)
4668       Opc = ARMISD::VCLTZ;
4669     SingleOp = Op1;
4670   }
4671
4672   SDValue Result;
4673   if (SingleOp.getNode()) {
4674     switch (Opc) {
4675     case ARMISD::VCEQ:
4676       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4677     case ARMISD::VCGE:
4678       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4679     case ARMISD::VCLEZ:
4680       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4681     case ARMISD::VCGT:
4682       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4683     case ARMISD::VCLTZ:
4684       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4685     default:
4686       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4687     }
4688   } else {
4689      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4690   }
4691
4692   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4693
4694   if (Invert)
4695     Result = DAG.getNOT(dl, Result, VT);
4696
4697   return Result;
4698 }
4699
4700 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4701 /// valid vector constant for a NEON instruction with a "modified immediate"
4702 /// operand (e.g., VMOV).  If so, return the encoded value.
4703 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4704                                  unsigned SplatBitSize, SelectionDAG &DAG,
4705                                  SDLoc dl, EVT &VT, bool is128Bits,
4706                                  NEONModImmType type) {
4707   unsigned OpCmode, Imm;
4708
4709   // SplatBitSize is set to the smallest size that splats the vector, so a
4710   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4711   // immediate instructions others than VMOV do not support the 8-bit encoding
4712   // of a zero vector, and the default encoding of zero is supposed to be the
4713   // 32-bit version.
4714   if (SplatBits == 0)
4715     SplatBitSize = 32;
4716
4717   switch (SplatBitSize) {
4718   case 8:
4719     if (type != VMOVModImm)
4720       return SDValue();
4721     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4722     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4723     OpCmode = 0xe;
4724     Imm = SplatBits;
4725     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4726     break;
4727
4728   case 16:
4729     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4730     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4731     if ((SplatBits & ~0xff) == 0) {
4732       // Value = 0x00nn: Op=x, Cmode=100x.
4733       OpCmode = 0x8;
4734       Imm = SplatBits;
4735       break;
4736     }
4737     if ((SplatBits & ~0xff00) == 0) {
4738       // Value = 0xnn00: Op=x, Cmode=101x.
4739       OpCmode = 0xa;
4740       Imm = SplatBits >> 8;
4741       break;
4742     }
4743     return SDValue();
4744
4745   case 32:
4746     // NEON's 32-bit VMOV supports splat values where:
4747     // * only one byte is nonzero, or
4748     // * the least significant byte is 0xff and the second byte is nonzero, or
4749     // * the least significant 2 bytes are 0xff and the third is nonzero.
4750     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4751     if ((SplatBits & ~0xff) == 0) {
4752       // Value = 0x000000nn: Op=x, Cmode=000x.
4753       OpCmode = 0;
4754       Imm = SplatBits;
4755       break;
4756     }
4757     if ((SplatBits & ~0xff00) == 0) {
4758       // Value = 0x0000nn00: Op=x, Cmode=001x.
4759       OpCmode = 0x2;
4760       Imm = SplatBits >> 8;
4761       break;
4762     }
4763     if ((SplatBits & ~0xff0000) == 0) {
4764       // Value = 0x00nn0000: Op=x, Cmode=010x.
4765       OpCmode = 0x4;
4766       Imm = SplatBits >> 16;
4767       break;
4768     }
4769     if ((SplatBits & ~0xff000000) == 0) {
4770       // Value = 0xnn000000: Op=x, Cmode=011x.
4771       OpCmode = 0x6;
4772       Imm = SplatBits >> 24;
4773       break;
4774     }
4775
4776     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4777     if (type == OtherModImm) return SDValue();
4778
4779     if ((SplatBits & ~0xffff) == 0 &&
4780         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4781       // Value = 0x0000nnff: Op=x, Cmode=1100.
4782       OpCmode = 0xc;
4783       Imm = SplatBits >> 8;
4784       break;
4785     }
4786
4787     if ((SplatBits & ~0xffffff) == 0 &&
4788         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4789       // Value = 0x00nnffff: Op=x, Cmode=1101.
4790       OpCmode = 0xd;
4791       Imm = SplatBits >> 16;
4792       break;
4793     }
4794
4795     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4796     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4797     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4798     // and fall through here to test for a valid 64-bit splat.  But, then the
4799     // caller would also need to check and handle the change in size.
4800     return SDValue();
4801
4802   case 64: {
4803     if (type != VMOVModImm)
4804       return SDValue();
4805     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4806     uint64_t BitMask = 0xff;
4807     uint64_t Val = 0;
4808     unsigned ImmMask = 1;
4809     Imm = 0;
4810     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4811       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4812         Val |= BitMask;
4813         Imm |= ImmMask;
4814       } else if ((SplatBits & BitMask) != 0) {
4815         return SDValue();
4816       }
4817       BitMask <<= 8;
4818       ImmMask <<= 1;
4819     }
4820
4821     if (DAG.getDataLayout().isBigEndian())
4822       // swap higher and lower 32 bit word
4823       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4824
4825     // Op=1, Cmode=1110.
4826     OpCmode = 0x1e;
4827     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4828     break;
4829   }
4830
4831   default:
4832     llvm_unreachable("unexpected size for isNEONModifiedImm");
4833   }
4834
4835   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4836   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4837 }
4838
4839 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4840                                            const ARMSubtarget *ST) const {
4841   if (!ST->hasVFP3())
4842     return SDValue();
4843
4844   bool IsDouble = Op.getValueType() == MVT::f64;
4845   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4846
4847   // Use the default (constant pool) lowering for double constants when we have
4848   // an SP-only FPU
4849   if (IsDouble && Subtarget->isFPOnlySP())
4850     return SDValue();
4851
4852   // Try splatting with a VMOV.f32...
4853   APFloat FPVal = CFP->getValueAPF();
4854   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4855
4856   if (ImmVal != -1) {
4857     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4858       // We have code in place to select a valid ConstantFP already, no need to
4859       // do any mangling.
4860       return Op;
4861     }
4862
4863     // It's a float and we are trying to use NEON operations where
4864     // possible. Lower it to a splat followed by an extract.
4865     SDLoc DL(Op);
4866     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4867     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4868                                       NewVal);
4869     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4870                        DAG.getConstant(0, DL, MVT::i32));
4871   }
4872
4873   // The rest of our options are NEON only, make sure that's allowed before
4874   // proceeding..
4875   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4876     return SDValue();
4877
4878   EVT VMovVT;
4879   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4880
4881   // It wouldn't really be worth bothering for doubles except for one very
4882   // important value, which does happen to match: 0.0. So make sure we don't do
4883   // anything stupid.
4884   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4885     return SDValue();
4886
4887   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4888   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4889                                      VMovVT, false, VMOVModImm);
4890   if (NewVal != SDValue()) {
4891     SDLoc DL(Op);
4892     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4893                                       NewVal);
4894     if (IsDouble)
4895       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4896
4897     // It's a float: cast and extract a vector element.
4898     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4899                                        VecConstant);
4900     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4901                        DAG.getConstant(0, DL, MVT::i32));
4902   }
4903
4904   // Finally, try a VMVN.i32
4905   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4906                              false, VMVNModImm);
4907   if (NewVal != SDValue()) {
4908     SDLoc DL(Op);
4909     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4910
4911     if (IsDouble)
4912       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4913
4914     // It's a float: cast and extract a vector element.
4915     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4916                                        VecConstant);
4917     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4918                        DAG.getConstant(0, DL, MVT::i32));
4919   }
4920
4921   return SDValue();
4922 }
4923
4924 // check if an VEXT instruction can handle the shuffle mask when the
4925 // vector sources of the shuffle are the same.
4926 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4927   unsigned NumElts = VT.getVectorNumElements();
4928
4929   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4930   if (M[0] < 0)
4931     return false;
4932
4933   Imm = M[0];
4934
4935   // If this is a VEXT shuffle, the immediate value is the index of the first
4936   // element.  The other shuffle indices must be the successive elements after
4937   // the first one.
4938   unsigned ExpectedElt = Imm;
4939   for (unsigned i = 1; i < NumElts; ++i) {
4940     // Increment the expected index.  If it wraps around, just follow it
4941     // back to index zero and keep going.
4942     ++ExpectedElt;
4943     if (ExpectedElt == NumElts)
4944       ExpectedElt = 0;
4945
4946     if (M[i] < 0) continue; // ignore UNDEF indices
4947     if (ExpectedElt != static_cast<unsigned>(M[i]))
4948       return false;
4949   }
4950
4951   return true;
4952 }
4953
4954
4955 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4956                        bool &ReverseVEXT, unsigned &Imm) {
4957   unsigned NumElts = VT.getVectorNumElements();
4958   ReverseVEXT = false;
4959
4960   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4961   if (M[0] < 0)
4962     return false;
4963
4964   Imm = M[0];
4965
4966   // If this is a VEXT shuffle, the immediate value is the index of the first
4967   // element.  The other shuffle indices must be the successive elements after
4968   // the first one.
4969   unsigned ExpectedElt = Imm;
4970   for (unsigned i = 1; i < NumElts; ++i) {
4971     // Increment the expected index.  If it wraps around, it may still be
4972     // a VEXT but the source vectors must be swapped.
4973     ExpectedElt += 1;
4974     if (ExpectedElt == NumElts * 2) {
4975       ExpectedElt = 0;
4976       ReverseVEXT = true;
4977     }
4978
4979     if (M[i] < 0) continue; // ignore UNDEF indices
4980     if (ExpectedElt != static_cast<unsigned>(M[i]))
4981       return false;
4982   }
4983
4984   // Adjust the index value if the source operands will be swapped.
4985   if (ReverseVEXT)
4986     Imm -= NumElts;
4987
4988   return true;
4989 }
4990
4991 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4992 /// instruction with the specified blocksize.  (The order of the elements
4993 /// within each block of the vector is reversed.)
4994 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4995   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4996          "Only possible block sizes for VREV are: 16, 32, 64");
4997
4998   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4999   if (EltSz == 64)
5000     return false;
5001
5002   unsigned NumElts = VT.getVectorNumElements();
5003   unsigned BlockElts = M[0] + 1;
5004   // If the first shuffle index is UNDEF, be optimistic.
5005   if (M[0] < 0)
5006     BlockElts = BlockSize / EltSz;
5007
5008   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5009     return false;
5010
5011   for (unsigned i = 0; i < NumElts; ++i) {
5012     if (M[i] < 0) continue; // ignore UNDEF indices
5013     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5014       return false;
5015   }
5016
5017   return true;
5018 }
5019
5020 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5021   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5022   // range, then 0 is placed into the resulting vector. So pretty much any mask
5023   // of 8 elements can work here.
5024   return VT == MVT::v8i8 && M.size() == 8;
5025 }
5026
5027 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5028 // checking that pairs of elements in the shuffle mask represent the same index
5029 // in each vector, incrementing the expected index by 2 at each step.
5030 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5031 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5032 //  v2={e,f,g,h}
5033 // WhichResult gives the offset for each element in the mask based on which
5034 // of the two results it belongs to.
5035 //
5036 // The transpose can be represented either as:
5037 // result1 = shufflevector v1, v2, result1_shuffle_mask
5038 // result2 = shufflevector v1, v2, result2_shuffle_mask
5039 // where v1/v2 and the shuffle masks have the same number of elements
5040 // (here WhichResult (see below) indicates which result is being checked)
5041 //
5042 // or as:
5043 // results = shufflevector v1, v2, shuffle_mask
5044 // where both results are returned in one vector and the shuffle mask has twice
5045 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5046 // want to check the low half and high half of the shuffle mask as if it were
5047 // the other case
5048 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5049   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5050   if (EltSz == 64)
5051     return false;
5052
5053   unsigned NumElts = VT.getVectorNumElements();
5054   if (M.size() != NumElts && M.size() != NumElts*2)
5055     return false;
5056
5057   // If the mask is twice as long as the input vector then we need to check the
5058   // upper and lower parts of the mask with a matching value for WhichResult
5059   // FIXME: A mask with only even values will be rejected in case the first
5060   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5061   // M[0] is used to determine WhichResult
5062   for (unsigned i = 0; i < M.size(); i += NumElts) {
5063     if (M.size() == NumElts * 2)
5064       WhichResult = i / NumElts;
5065     else
5066       WhichResult = M[i] == 0 ? 0 : 1;
5067     for (unsigned j = 0; j < NumElts; j += 2) {
5068       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5069           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5070         return false;
5071     }
5072   }
5073
5074   if (M.size() == NumElts*2)
5075     WhichResult = 0;
5076
5077   return true;
5078 }
5079
5080 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5081 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5082 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5083 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5084   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5085   if (EltSz == 64)
5086     return false;
5087
5088   unsigned NumElts = VT.getVectorNumElements();
5089   if (M.size() != NumElts && M.size() != NumElts*2)
5090     return false;
5091
5092   for (unsigned i = 0; i < M.size(); i += NumElts) {
5093     if (M.size() == NumElts * 2)
5094       WhichResult = i / NumElts;
5095     else
5096       WhichResult = M[i] == 0 ? 0 : 1;
5097     for (unsigned j = 0; j < NumElts; j += 2) {
5098       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5099           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5100         return false;
5101     }
5102   }
5103
5104   if (M.size() == NumElts*2)
5105     WhichResult = 0;
5106
5107   return true;
5108 }
5109
5110 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5111 // that the mask elements are either all even and in steps of size 2 or all odd
5112 // and in steps of size 2.
5113 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5114 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5115 //  v2={e,f,g,h}
5116 // Requires similar checks to that of isVTRNMask with
5117 // respect the how results are returned.
5118 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5119   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5120   if (EltSz == 64)
5121     return false;
5122
5123   unsigned NumElts = VT.getVectorNumElements();
5124   if (M.size() != NumElts && M.size() != NumElts*2)
5125     return false;
5126
5127   for (unsigned i = 0; i < M.size(); i += NumElts) {
5128     WhichResult = M[i] == 0 ? 0 : 1;
5129     for (unsigned j = 0; j < NumElts; ++j) {
5130       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5131         return false;
5132     }
5133   }
5134
5135   if (M.size() == NumElts*2)
5136     WhichResult = 0;
5137
5138   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5139   if (VT.is64BitVector() && EltSz == 32)
5140     return false;
5141
5142   return true;
5143 }
5144
5145 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5146 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5147 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5148 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5149   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5150   if (EltSz == 64)
5151     return false;
5152
5153   unsigned NumElts = VT.getVectorNumElements();
5154   if (M.size() != NumElts && M.size() != NumElts*2)
5155     return false;
5156
5157   unsigned Half = NumElts / 2;
5158   for (unsigned i = 0; i < M.size(); i += NumElts) {
5159     WhichResult = M[i] == 0 ? 0 : 1;
5160     for (unsigned j = 0; j < NumElts; j += Half) {
5161       unsigned Idx = WhichResult;
5162       for (unsigned k = 0; k < Half; ++k) {
5163         int MIdx = M[i + j + k];
5164         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5165           return false;
5166         Idx += 2;
5167       }
5168     }
5169   }
5170
5171   if (M.size() == NumElts*2)
5172     WhichResult = 0;
5173
5174   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5175   if (VT.is64BitVector() && EltSz == 32)
5176     return false;
5177
5178   return true;
5179 }
5180
5181 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5182 // that pairs of elements of the shufflemask represent the same index in each
5183 // vector incrementing sequentially through the vectors.
5184 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5185 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5186 //  v2={e,f,g,h}
5187 // Requires similar checks to that of isVTRNMask with respect the how results
5188 // are returned.
5189 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5190   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5191   if (EltSz == 64)
5192     return false;
5193
5194   unsigned NumElts = VT.getVectorNumElements();
5195   if (M.size() != NumElts && M.size() != NumElts*2)
5196     return false;
5197
5198   for (unsigned i = 0; i < M.size(); i += NumElts) {
5199     WhichResult = M[i] == 0 ? 0 : 1;
5200     unsigned Idx = WhichResult * NumElts / 2;
5201     for (unsigned j = 0; j < NumElts; j += 2) {
5202       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5203           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5204         return false;
5205       Idx += 1;
5206     }
5207   }
5208
5209   if (M.size() == NumElts*2)
5210     WhichResult = 0;
5211
5212   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5213   if (VT.is64BitVector() && EltSz == 32)
5214     return false;
5215
5216   return true;
5217 }
5218
5219 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5220 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5221 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5222 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5223   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5224   if (EltSz == 64)
5225     return false;
5226
5227   unsigned NumElts = VT.getVectorNumElements();
5228   if (M.size() != NumElts && M.size() != NumElts*2)
5229     return false;
5230
5231   for (unsigned i = 0; i < M.size(); i += NumElts) {
5232     WhichResult = M[i] == 0 ? 0 : 1;
5233     unsigned Idx = WhichResult * NumElts / 2;
5234     for (unsigned j = 0; j < NumElts; j += 2) {
5235       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5236           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5237         return false;
5238       Idx += 1;
5239     }
5240   }
5241
5242   if (M.size() == NumElts*2)
5243     WhichResult = 0;
5244
5245   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5246   if (VT.is64BitVector() && EltSz == 32)
5247     return false;
5248
5249   return true;
5250 }
5251
5252 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5253 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5254 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5255                                            unsigned &WhichResult,
5256                                            bool &isV_UNDEF) {
5257   isV_UNDEF = false;
5258   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5259     return ARMISD::VTRN;
5260   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5261     return ARMISD::VUZP;
5262   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5263     return ARMISD::VZIP;
5264
5265   isV_UNDEF = true;
5266   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5267     return ARMISD::VTRN;
5268   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5269     return ARMISD::VUZP;
5270   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5271     return ARMISD::VZIP;
5272
5273   return 0;
5274 }
5275
5276 /// \return true if this is a reverse operation on an vector.
5277 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5278   unsigned NumElts = VT.getVectorNumElements();
5279   // Make sure the mask has the right size.
5280   if (NumElts != M.size())
5281       return false;
5282
5283   // Look for <15, ..., 3, -1, 1, 0>.
5284   for (unsigned i = 0; i != NumElts; ++i)
5285     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5286       return false;
5287
5288   return true;
5289 }
5290
5291 // If N is an integer constant that can be moved into a register in one
5292 // instruction, return an SDValue of such a constant (will become a MOV
5293 // instruction).  Otherwise return null.
5294 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5295                                      const ARMSubtarget *ST, SDLoc dl) {
5296   uint64_t Val;
5297   if (!isa<ConstantSDNode>(N))
5298     return SDValue();
5299   Val = cast<ConstantSDNode>(N)->getZExtValue();
5300
5301   if (ST->isThumb1Only()) {
5302     if (Val <= 255 || ~Val <= 255)
5303       return DAG.getConstant(Val, dl, MVT::i32);
5304   } else {
5305     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5306       return DAG.getConstant(Val, dl, MVT::i32);
5307   }
5308   return SDValue();
5309 }
5310
5311 // If this is a case we can't handle, return null and let the default
5312 // expansion code take care of it.
5313 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5314                                              const ARMSubtarget *ST) const {
5315   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5316   SDLoc dl(Op);
5317   EVT VT = Op.getValueType();
5318
5319   APInt SplatBits, SplatUndef;
5320   unsigned SplatBitSize;
5321   bool HasAnyUndefs;
5322   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5323     if (SplatBitSize <= 64) {
5324       // Check if an immediate VMOV works.
5325       EVT VmovVT;
5326       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5327                                       SplatUndef.getZExtValue(), SplatBitSize,
5328                                       DAG, dl, VmovVT, VT.is128BitVector(),
5329                                       VMOVModImm);
5330       if (Val.getNode()) {
5331         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5332         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5333       }
5334
5335       // Try an immediate VMVN.
5336       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5337       Val = isNEONModifiedImm(NegatedImm,
5338                                       SplatUndef.getZExtValue(), SplatBitSize,
5339                                       DAG, dl, VmovVT, VT.is128BitVector(),
5340                                       VMVNModImm);
5341       if (Val.getNode()) {
5342         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5343         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5344       }
5345
5346       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5347       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5348         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5349         if (ImmVal != -1) {
5350           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5351           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5352         }
5353       }
5354     }
5355   }
5356
5357   // Scan through the operands to see if only one value is used.
5358   //
5359   // As an optimisation, even if more than one value is used it may be more
5360   // profitable to splat with one value then change some lanes.
5361   //
5362   // Heuristically we decide to do this if the vector has a "dominant" value,
5363   // defined as splatted to more than half of the lanes.
5364   unsigned NumElts = VT.getVectorNumElements();
5365   bool isOnlyLowElement = true;
5366   bool usesOnlyOneValue = true;
5367   bool hasDominantValue = false;
5368   bool isConstant = true;
5369
5370   // Map of the number of times a particular SDValue appears in the
5371   // element list.
5372   DenseMap<SDValue, unsigned> ValueCounts;
5373   SDValue Value;
5374   for (unsigned i = 0; i < NumElts; ++i) {
5375     SDValue V = Op.getOperand(i);
5376     if (V.getOpcode() == ISD::UNDEF)
5377       continue;
5378     if (i > 0)
5379       isOnlyLowElement = false;
5380     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5381       isConstant = false;
5382
5383     ValueCounts.insert(std::make_pair(V, 0));
5384     unsigned &Count = ValueCounts[V];
5385
5386     // Is this value dominant? (takes up more than half of the lanes)
5387     if (++Count > (NumElts / 2)) {
5388       hasDominantValue = true;
5389       Value = V;
5390     }
5391   }
5392   if (ValueCounts.size() != 1)
5393     usesOnlyOneValue = false;
5394   if (!Value.getNode() && ValueCounts.size() > 0)
5395     Value = ValueCounts.begin()->first;
5396
5397   if (ValueCounts.size() == 0)
5398     return DAG.getUNDEF(VT);
5399
5400   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5401   // Keep going if we are hitting this case.
5402   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5403     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5404
5405   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5406
5407   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5408   // i32 and try again.
5409   if (hasDominantValue && EltSize <= 32) {
5410     if (!isConstant) {
5411       SDValue N;
5412
5413       // If we are VDUPing a value that comes directly from a vector, that will
5414       // cause an unnecessary move to and from a GPR, where instead we could
5415       // just use VDUPLANE. We can only do this if the lane being extracted
5416       // is at a constant index, as the VDUP from lane instructions only have
5417       // constant-index forms.
5418       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5419           isa<ConstantSDNode>(Value->getOperand(1))) {
5420         // We need to create a new undef vector to use for the VDUPLANE if the
5421         // size of the vector from which we get the value is different than the
5422         // size of the vector that we need to create. We will insert the element
5423         // such that the register coalescer will remove unnecessary copies.
5424         if (VT != Value->getOperand(0).getValueType()) {
5425           ConstantSDNode *constIndex;
5426           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5427           assert(constIndex && "The index is not a constant!");
5428           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5429                              VT.getVectorNumElements();
5430           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5431                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5432                         Value, DAG.getConstant(index, dl, MVT::i32)),
5433                            DAG.getConstant(index, dl, MVT::i32));
5434         } else
5435           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5436                         Value->getOperand(0), Value->getOperand(1));
5437       } else
5438         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5439
5440       if (!usesOnlyOneValue) {
5441         // The dominant value was splatted as 'N', but we now have to insert
5442         // all differing elements.
5443         for (unsigned I = 0; I < NumElts; ++I) {
5444           if (Op.getOperand(I) == Value)
5445             continue;
5446           SmallVector<SDValue, 3> Ops;
5447           Ops.push_back(N);
5448           Ops.push_back(Op.getOperand(I));
5449           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5450           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5451         }
5452       }
5453       return N;
5454     }
5455     if (VT.getVectorElementType().isFloatingPoint()) {
5456       SmallVector<SDValue, 8> Ops;
5457       for (unsigned i = 0; i < NumElts; ++i)
5458         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5459                                   Op.getOperand(i)));
5460       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5461       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5462       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5463       if (Val.getNode())
5464         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5465     }
5466     if (usesOnlyOneValue) {
5467       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5468       if (isConstant && Val.getNode())
5469         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5470     }
5471   }
5472
5473   // If all elements are constants and the case above didn't get hit, fall back
5474   // to the default expansion, which will generate a load from the constant
5475   // pool.
5476   if (isConstant)
5477     return SDValue();
5478
5479   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5480   if (NumElts >= 4) {
5481     SDValue shuffle = ReconstructShuffle(Op, DAG);
5482     if (shuffle != SDValue())
5483       return shuffle;
5484   }
5485
5486   // Vectors with 32- or 64-bit elements can be built by directly assigning
5487   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5488   // will be legalized.
5489   if (EltSize >= 32) {
5490     // Do the expansion with floating-point types, since that is what the VFP
5491     // registers are defined to use, and since i64 is not legal.
5492     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5493     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5494     SmallVector<SDValue, 8> Ops;
5495     for (unsigned i = 0; i < NumElts; ++i)
5496       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5497     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5498     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5499   }
5500
5501   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5502   // know the default expansion would otherwise fall back on something even
5503   // worse. For a vector with one or two non-undef values, that's
5504   // scalar_to_vector for the elements followed by a shuffle (provided the
5505   // shuffle is valid for the target) and materialization element by element
5506   // on the stack followed by a load for everything else.
5507   if (!isConstant && !usesOnlyOneValue) {
5508     SDValue Vec = DAG.getUNDEF(VT);
5509     for (unsigned i = 0 ; i < NumElts; ++i) {
5510       SDValue V = Op.getOperand(i);
5511       if (V.getOpcode() == ISD::UNDEF)
5512         continue;
5513       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5514       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5515     }
5516     return Vec;
5517   }
5518
5519   return SDValue();
5520 }
5521
5522 // Gather data to see if the operation can be modelled as a
5523 // shuffle in combination with VEXTs.
5524 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5525                                               SelectionDAG &DAG) const {
5526   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5527   SDLoc dl(Op);
5528   EVT VT = Op.getValueType();
5529   unsigned NumElts = VT.getVectorNumElements();
5530
5531   struct ShuffleSourceInfo {
5532     SDValue Vec;
5533     unsigned MinElt;
5534     unsigned MaxElt;
5535
5536     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5537     // be compatible with the shuffle we intend to construct. As a result
5538     // ShuffleVec will be some sliding window into the original Vec.
5539     SDValue ShuffleVec;
5540
5541     // Code should guarantee that element i in Vec starts at element "WindowBase
5542     // + i * WindowScale in ShuffleVec".
5543     int WindowBase;
5544     int WindowScale;
5545
5546     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5547     ShuffleSourceInfo(SDValue Vec)
5548         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5549           WindowScale(1) {}
5550   };
5551
5552   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5553   // node.
5554   SmallVector<ShuffleSourceInfo, 2> Sources;
5555   for (unsigned i = 0; i < NumElts; ++i) {
5556     SDValue V = Op.getOperand(i);
5557     if (V.getOpcode() == ISD::UNDEF)
5558       continue;
5559     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5560       // A shuffle can only come from building a vector from various
5561       // elements of other vectors.
5562       return SDValue();
5563     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5564       // Furthermore, shuffles require a constant mask, whereas extractelts
5565       // accept variable indices.
5566       return SDValue();
5567     }
5568
5569     // Add this element source to the list if it's not already there.
5570     SDValue SourceVec = V.getOperand(0);
5571     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5572     if (Source == Sources.end())
5573       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5574
5575     // Update the minimum and maximum lane number seen.
5576     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5577     Source->MinElt = std::min(Source->MinElt, EltNo);
5578     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5579   }
5580
5581   // Currently only do something sane when at most two source vectors
5582   // are involved.
5583   if (Sources.size() > 2)
5584     return SDValue();
5585
5586   // Find out the smallest element size among result and two sources, and use
5587   // it as element size to build the shuffle_vector.
5588   EVT SmallestEltTy = VT.getVectorElementType();
5589   for (auto &Source : Sources) {
5590     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5591     if (SrcEltTy.bitsLT(SmallestEltTy))
5592       SmallestEltTy = SrcEltTy;
5593   }
5594   unsigned ResMultiplier =
5595       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5596   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5597   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5598
5599   // If the source vector is too wide or too narrow, we may nevertheless be able
5600   // to construct a compatible shuffle either by concatenating it with UNDEF or
5601   // extracting a suitable range of elements.
5602   for (auto &Src : Sources) {
5603     EVT SrcVT = Src.ShuffleVec.getValueType();
5604
5605     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5606       continue;
5607
5608     // This stage of the search produces a source with the same element type as
5609     // the original, but with a total width matching the BUILD_VECTOR output.
5610     EVT EltVT = SrcVT.getVectorElementType();
5611     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5612     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5613
5614     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5615       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5616         return SDValue();
5617       // We can pad out the smaller vector for free, so if it's part of a
5618       // shuffle...
5619       Src.ShuffleVec =
5620           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5621                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5622       continue;
5623     }
5624
5625     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5626       return SDValue();
5627
5628     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5629       // Span too large for a VEXT to cope
5630       return SDValue();
5631     }
5632
5633     if (Src.MinElt >= NumSrcElts) {
5634       // The extraction can just take the second half
5635       Src.ShuffleVec =
5636           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5637                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5638       Src.WindowBase = -NumSrcElts;
5639     } else if (Src.MaxElt < NumSrcElts) {
5640       // The extraction can just take the first half
5641       Src.ShuffleVec =
5642           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5643                       DAG.getConstant(0, dl, MVT::i32));
5644     } else {
5645       // An actual VEXT is needed
5646       SDValue VEXTSrc1 =
5647           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5648                       DAG.getConstant(0, dl, MVT::i32));
5649       SDValue VEXTSrc2 =
5650           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5651                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5652
5653       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5654                                    VEXTSrc2,
5655                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
5656       Src.WindowBase = -Src.MinElt;
5657     }
5658   }
5659
5660   // Another possible incompatibility occurs from the vector element types. We
5661   // can fix this by bitcasting the source vectors to the same type we intend
5662   // for the shuffle.
5663   for (auto &Src : Sources) {
5664     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5665     if (SrcEltTy == SmallestEltTy)
5666       continue;
5667     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5668     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5669     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5670     Src.WindowBase *= Src.WindowScale;
5671   }
5672
5673   // Final sanity check before we try to actually produce a shuffle.
5674   DEBUG(
5675     for (auto Src : Sources)
5676       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5677   );
5678
5679   // The stars all align, our next step is to produce the mask for the shuffle.
5680   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5681   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5682   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5683     SDValue Entry = Op.getOperand(i);
5684     if (Entry.getOpcode() == ISD::UNDEF)
5685       continue;
5686
5687     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5688     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5689
5690     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5691     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5692     // segment.
5693     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5694     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5695                                VT.getVectorElementType().getSizeInBits());
5696     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5697
5698     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5699     // starting at the appropriate offset.
5700     int *LaneMask = &Mask[i * ResMultiplier];
5701
5702     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5703     ExtractBase += NumElts * (Src - Sources.begin());
5704     for (int j = 0; j < LanesDefined; ++j)
5705       LaneMask[j] = ExtractBase + j;
5706   }
5707
5708   // Final check before we try to produce nonsense...
5709   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5710     return SDValue();
5711
5712   // We can't handle more than two sources. This should have already
5713   // been checked before this point.
5714   assert(Sources.size() <= 2 && "Too many sources!");
5715
5716   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5717   for (unsigned i = 0; i < Sources.size(); ++i)
5718     ShuffleOps[i] = Sources[i].ShuffleVec;
5719
5720   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5721                                          ShuffleOps[1], &Mask[0]);
5722   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5723 }
5724
5725 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5726 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5727 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5728 /// are assumed to be legal.
5729 bool
5730 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5731                                       EVT VT) const {
5732   if (VT.getVectorNumElements() == 4 &&
5733       (VT.is128BitVector() || VT.is64BitVector())) {
5734     unsigned PFIndexes[4];
5735     for (unsigned i = 0; i != 4; ++i) {
5736       if (M[i] < 0)
5737         PFIndexes[i] = 8;
5738       else
5739         PFIndexes[i] = M[i];
5740     }
5741
5742     // Compute the index in the perfect shuffle table.
5743     unsigned PFTableIndex =
5744       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5745     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5746     unsigned Cost = (PFEntry >> 30);
5747
5748     if (Cost <= 4)
5749       return true;
5750   }
5751
5752   bool ReverseVEXT, isV_UNDEF;
5753   unsigned Imm, WhichResult;
5754
5755   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5756   return (EltSize >= 32 ||
5757           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5758           isVREVMask(M, VT, 64) ||
5759           isVREVMask(M, VT, 32) ||
5760           isVREVMask(M, VT, 16) ||
5761           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5762           isVTBLMask(M, VT) ||
5763           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5764           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5765 }
5766
5767 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5768 /// the specified operations to build the shuffle.
5769 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5770                                       SDValue RHS, SelectionDAG &DAG,
5771                                       SDLoc dl) {
5772   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5773   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5774   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5775
5776   enum {
5777     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5778     OP_VREV,
5779     OP_VDUP0,
5780     OP_VDUP1,
5781     OP_VDUP2,
5782     OP_VDUP3,
5783     OP_VEXT1,
5784     OP_VEXT2,
5785     OP_VEXT3,
5786     OP_VUZPL, // VUZP, left result
5787     OP_VUZPR, // VUZP, right result
5788     OP_VZIPL, // VZIP, left result
5789     OP_VZIPR, // VZIP, right result
5790     OP_VTRNL, // VTRN, left result
5791     OP_VTRNR  // VTRN, right result
5792   };
5793
5794   if (OpNum == OP_COPY) {
5795     if (LHSID == (1*9+2)*9+3) return LHS;
5796     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5797     return RHS;
5798   }
5799
5800   SDValue OpLHS, OpRHS;
5801   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5802   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5803   EVT VT = OpLHS.getValueType();
5804
5805   switch (OpNum) {
5806   default: llvm_unreachable("Unknown shuffle opcode!");
5807   case OP_VREV:
5808     // VREV divides the vector in half and swaps within the half.
5809     if (VT.getVectorElementType() == MVT::i32 ||
5810         VT.getVectorElementType() == MVT::f32)
5811       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5812     // vrev <4 x i16> -> VREV32
5813     if (VT.getVectorElementType() == MVT::i16)
5814       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5815     // vrev <4 x i8> -> VREV16
5816     assert(VT.getVectorElementType() == MVT::i8);
5817     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5818   case OP_VDUP0:
5819   case OP_VDUP1:
5820   case OP_VDUP2:
5821   case OP_VDUP3:
5822     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5823                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5824   case OP_VEXT1:
5825   case OP_VEXT2:
5826   case OP_VEXT3:
5827     return DAG.getNode(ARMISD::VEXT, dl, VT,
5828                        OpLHS, OpRHS,
5829                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5830   case OP_VUZPL:
5831   case OP_VUZPR:
5832     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5833                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5834   case OP_VZIPL:
5835   case OP_VZIPR:
5836     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5837                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5838   case OP_VTRNL:
5839   case OP_VTRNR:
5840     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5841                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5842   }
5843 }
5844
5845 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5846                                        ArrayRef<int> ShuffleMask,
5847                                        SelectionDAG &DAG) {
5848   // Check to see if we can use the VTBL instruction.
5849   SDValue V1 = Op.getOperand(0);
5850   SDValue V2 = Op.getOperand(1);
5851   SDLoc DL(Op);
5852
5853   SmallVector<SDValue, 8> VTBLMask;
5854   for (ArrayRef<int>::iterator
5855          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5856     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5857
5858   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5859     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5860                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5861
5862   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5863                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5864 }
5865
5866 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5867                                                       SelectionDAG &DAG) {
5868   SDLoc DL(Op);
5869   SDValue OpLHS = Op.getOperand(0);
5870   EVT VT = OpLHS.getValueType();
5871
5872   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5873          "Expect an v8i16/v16i8 type");
5874   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5875   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5876   // extract the first 8 bytes into the top double word and the last 8 bytes
5877   // into the bottom double word. The v8i16 case is similar.
5878   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5879   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5880                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5881 }
5882
5883 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5884   SDValue V1 = Op.getOperand(0);
5885   SDValue V2 = Op.getOperand(1);
5886   SDLoc dl(Op);
5887   EVT VT = Op.getValueType();
5888   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5889
5890   // Convert shuffles that are directly supported on NEON to target-specific
5891   // DAG nodes, instead of keeping them as shuffles and matching them again
5892   // during code selection.  This is more efficient and avoids the possibility
5893   // of inconsistencies between legalization and selection.
5894   // FIXME: floating-point vectors should be canonicalized to integer vectors
5895   // of the same time so that they get CSEd properly.
5896   ArrayRef<int> ShuffleMask = SVN->getMask();
5897
5898   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5899   if (EltSize <= 32) {
5900     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5901       int Lane = SVN->getSplatIndex();
5902       // If this is undef splat, generate it via "just" vdup, if possible.
5903       if (Lane == -1) Lane = 0;
5904
5905       // Test if V1 is a SCALAR_TO_VECTOR.
5906       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5907         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5908       }
5909       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5910       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5911       // reaches it).
5912       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5913           !isa<ConstantSDNode>(V1.getOperand(0))) {
5914         bool IsScalarToVector = true;
5915         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5916           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5917             IsScalarToVector = false;
5918             break;
5919           }
5920         if (IsScalarToVector)
5921           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5922       }
5923       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5924                          DAG.getConstant(Lane, dl, MVT::i32));
5925     }
5926
5927     bool ReverseVEXT;
5928     unsigned Imm;
5929     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5930       if (ReverseVEXT)
5931         std::swap(V1, V2);
5932       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5933                          DAG.getConstant(Imm, dl, MVT::i32));
5934     }
5935
5936     if (isVREVMask(ShuffleMask, VT, 64))
5937       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5938     if (isVREVMask(ShuffleMask, VT, 32))
5939       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5940     if (isVREVMask(ShuffleMask, VT, 16))
5941       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5942
5943     if (V2->getOpcode() == ISD::UNDEF &&
5944         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5945       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5946                          DAG.getConstant(Imm, dl, MVT::i32));
5947     }
5948
5949     // Check for Neon shuffles that modify both input vectors in place.
5950     // If both results are used, i.e., if there are two shuffles with the same
5951     // source operands and with masks corresponding to both results of one of
5952     // these operations, DAG memoization will ensure that a single node is
5953     // used for both shuffles.
5954     unsigned WhichResult;
5955     bool isV_UNDEF;
5956     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5957             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5958       if (isV_UNDEF)
5959         V2 = V1;
5960       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5961           .getValue(WhichResult);
5962     }
5963
5964     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5965     // shuffles that produce a result larger than their operands with:
5966     //   shuffle(concat(v1, undef), concat(v2, undef))
5967     // ->
5968     //   shuffle(concat(v1, v2), undef)
5969     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5970     //
5971     // This is useful in the general case, but there are special cases where
5972     // native shuffles produce larger results: the two-result ops.
5973     //
5974     // Look through the concat when lowering them:
5975     //   shuffle(concat(v1, v2), undef)
5976     // ->
5977     //   concat(VZIP(v1, v2):0, :1)
5978     //
5979     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5980         V2->getOpcode() == ISD::UNDEF) {
5981       SDValue SubV1 = V1->getOperand(0);
5982       SDValue SubV2 = V1->getOperand(1);
5983       EVT SubVT = SubV1.getValueType();
5984
5985       // We expect these to have been canonicalized to -1.
5986       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5987         return i < (int)VT.getVectorNumElements();
5988       }) && "Unexpected shuffle index into UNDEF operand!");
5989
5990       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5991               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5992         if (isV_UNDEF)
5993           SubV2 = SubV1;
5994         assert((WhichResult == 0) &&
5995                "In-place shuffle of concat can only have one result!");
5996         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5997                                   SubV1, SubV2);
5998         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5999                            Res.getValue(1));
6000       }
6001     }
6002   }
6003
6004   // If the shuffle is not directly supported and it has 4 elements, use
6005   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6006   unsigned NumElts = VT.getVectorNumElements();
6007   if (NumElts == 4) {
6008     unsigned PFIndexes[4];
6009     for (unsigned i = 0; i != 4; ++i) {
6010       if (ShuffleMask[i] < 0)
6011         PFIndexes[i] = 8;
6012       else
6013         PFIndexes[i] = ShuffleMask[i];
6014     }
6015
6016     // Compute the index in the perfect shuffle table.
6017     unsigned PFTableIndex =
6018       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6019     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6020     unsigned Cost = (PFEntry >> 30);
6021
6022     if (Cost <= 4)
6023       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6024   }
6025
6026   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6027   if (EltSize >= 32) {
6028     // Do the expansion with floating-point types, since that is what the VFP
6029     // registers are defined to use, and since i64 is not legal.
6030     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6031     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6032     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6033     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6034     SmallVector<SDValue, 8> Ops;
6035     for (unsigned i = 0; i < NumElts; ++i) {
6036       if (ShuffleMask[i] < 0)
6037         Ops.push_back(DAG.getUNDEF(EltVT));
6038       else
6039         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6040                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6041                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6042                                                   dl, MVT::i32)));
6043     }
6044     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6045     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6046   }
6047
6048   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6049     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6050
6051   if (VT == MVT::v8i8) {
6052     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6053     if (NewOp.getNode())
6054       return NewOp;
6055   }
6056
6057   return SDValue();
6058 }
6059
6060 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6061   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6062   SDValue Lane = Op.getOperand(2);
6063   if (!isa<ConstantSDNode>(Lane))
6064     return SDValue();
6065
6066   return Op;
6067 }
6068
6069 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6070   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6071   SDValue Lane = Op.getOperand(1);
6072   if (!isa<ConstantSDNode>(Lane))
6073     return SDValue();
6074
6075   SDValue Vec = Op.getOperand(0);
6076   if (Op.getValueType() == MVT::i32 &&
6077       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6078     SDLoc dl(Op);
6079     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6080   }
6081
6082   return Op;
6083 }
6084
6085 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6086   // The only time a CONCAT_VECTORS operation can have legal types is when
6087   // two 64-bit vectors are concatenated to a 128-bit vector.
6088   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6089          "unexpected CONCAT_VECTORS");
6090   SDLoc dl(Op);
6091   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6092   SDValue Op0 = Op.getOperand(0);
6093   SDValue Op1 = Op.getOperand(1);
6094   if (Op0.getOpcode() != ISD::UNDEF)
6095     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6096                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6097                       DAG.getIntPtrConstant(0, dl));
6098   if (Op1.getOpcode() != ISD::UNDEF)
6099     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6100                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6101                       DAG.getIntPtrConstant(1, dl));
6102   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6103 }
6104
6105 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6106 /// element has been zero/sign-extended, depending on the isSigned parameter,
6107 /// from an integer type half its size.
6108 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6109                                    bool isSigned) {
6110   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6111   EVT VT = N->getValueType(0);
6112   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6113     SDNode *BVN = N->getOperand(0).getNode();
6114     if (BVN->getValueType(0) != MVT::v4i32 ||
6115         BVN->getOpcode() != ISD::BUILD_VECTOR)
6116       return false;
6117     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6118     unsigned HiElt = 1 - LoElt;
6119     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6120     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6121     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6122     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6123     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6124       return false;
6125     if (isSigned) {
6126       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6127           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6128         return true;
6129     } else {
6130       if (Hi0->isNullValue() && Hi1->isNullValue())
6131         return true;
6132     }
6133     return false;
6134   }
6135
6136   if (N->getOpcode() != ISD::BUILD_VECTOR)
6137     return false;
6138
6139   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6140     SDNode *Elt = N->getOperand(i).getNode();
6141     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6142       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6143       unsigned HalfSize = EltSize / 2;
6144       if (isSigned) {
6145         if (!isIntN(HalfSize, C->getSExtValue()))
6146           return false;
6147       } else {
6148         if (!isUIntN(HalfSize, C->getZExtValue()))
6149           return false;
6150       }
6151       continue;
6152     }
6153     return false;
6154   }
6155
6156   return true;
6157 }
6158
6159 /// isSignExtended - Check if a node is a vector value that is sign-extended
6160 /// or a constant BUILD_VECTOR with sign-extended elements.
6161 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6162   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6163     return true;
6164   if (isExtendedBUILD_VECTOR(N, DAG, true))
6165     return true;
6166   return false;
6167 }
6168
6169 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6170 /// or a constant BUILD_VECTOR with zero-extended elements.
6171 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6172   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6173     return true;
6174   if (isExtendedBUILD_VECTOR(N, DAG, false))
6175     return true;
6176   return false;
6177 }
6178
6179 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6180   if (OrigVT.getSizeInBits() >= 64)
6181     return OrigVT;
6182
6183   assert(OrigVT.isSimple() && "Expecting a simple value type");
6184
6185   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6186   switch (OrigSimpleTy) {
6187   default: llvm_unreachable("Unexpected Vector Type");
6188   case MVT::v2i8:
6189   case MVT::v2i16:
6190      return MVT::v2i32;
6191   case MVT::v4i8:
6192     return  MVT::v4i16;
6193   }
6194 }
6195
6196 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6197 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6198 /// We insert the required extension here to get the vector to fill a D register.
6199 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6200                                             const EVT &OrigTy,
6201                                             const EVT &ExtTy,
6202                                             unsigned ExtOpcode) {
6203   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6204   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6205   // 64-bits we need to insert a new extension so that it will be 64-bits.
6206   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6207   if (OrigTy.getSizeInBits() >= 64)
6208     return N;
6209
6210   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6211   EVT NewVT = getExtensionTo64Bits(OrigTy);
6212
6213   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6214 }
6215
6216 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6217 /// does not do any sign/zero extension. If the original vector is less
6218 /// than 64 bits, an appropriate extension will be added after the load to
6219 /// reach a total size of 64 bits. We have to add the extension separately
6220 /// because ARM does not have a sign/zero extending load for vectors.
6221 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6222   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6223
6224   // The load already has the right type.
6225   if (ExtendedTy == LD->getMemoryVT())
6226     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6227                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6228                 LD->isNonTemporal(), LD->isInvariant(),
6229                 LD->getAlignment());
6230
6231   // We need to create a zextload/sextload. We cannot just create a load
6232   // followed by a zext/zext node because LowerMUL is also run during normal
6233   // operation legalization where we can't create illegal types.
6234   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6235                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6236                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6237                         LD->isNonTemporal(), LD->getAlignment());
6238 }
6239
6240 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6241 /// extending load, or BUILD_VECTOR with extended elements, return the
6242 /// unextended value. The unextended vector should be 64 bits so that it can
6243 /// be used as an operand to a VMULL instruction. If the original vector size
6244 /// before extension is less than 64 bits we add a an extension to resize
6245 /// the vector to 64 bits.
6246 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6247   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6248     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6249                                         N->getOperand(0)->getValueType(0),
6250                                         N->getValueType(0),
6251                                         N->getOpcode());
6252
6253   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6254     return SkipLoadExtensionForVMULL(LD, DAG);
6255
6256   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6257   // have been legalized as a BITCAST from v4i32.
6258   if (N->getOpcode() == ISD::BITCAST) {
6259     SDNode *BVN = N->getOperand(0).getNode();
6260     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6261            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6262     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6263     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6264                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6265   }
6266   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6267   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6268   EVT VT = N->getValueType(0);
6269   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6270   unsigned NumElts = VT.getVectorNumElements();
6271   MVT TruncVT = MVT::getIntegerVT(EltSize);
6272   SmallVector<SDValue, 8> Ops;
6273   SDLoc dl(N);
6274   for (unsigned i = 0; i != NumElts; ++i) {
6275     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6276     const APInt &CInt = C->getAPIntValue();
6277     // Element types smaller than 32 bits are not legal, so use i32 elements.
6278     // The values are implicitly truncated so sext vs. zext doesn't matter.
6279     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6280   }
6281   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6282                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6283 }
6284
6285 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6286   unsigned Opcode = N->getOpcode();
6287   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6288     SDNode *N0 = N->getOperand(0).getNode();
6289     SDNode *N1 = N->getOperand(1).getNode();
6290     return N0->hasOneUse() && N1->hasOneUse() &&
6291       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6292   }
6293   return false;
6294 }
6295
6296 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6297   unsigned Opcode = N->getOpcode();
6298   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6299     SDNode *N0 = N->getOperand(0).getNode();
6300     SDNode *N1 = N->getOperand(1).getNode();
6301     return N0->hasOneUse() && N1->hasOneUse() &&
6302       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6303   }
6304   return false;
6305 }
6306
6307 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6308   // Multiplications are only custom-lowered for 128-bit vectors so that
6309   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6310   EVT VT = Op.getValueType();
6311   assert(VT.is128BitVector() && VT.isInteger() &&
6312          "unexpected type for custom-lowering ISD::MUL");
6313   SDNode *N0 = Op.getOperand(0).getNode();
6314   SDNode *N1 = Op.getOperand(1).getNode();
6315   unsigned NewOpc = 0;
6316   bool isMLA = false;
6317   bool isN0SExt = isSignExtended(N0, DAG);
6318   bool isN1SExt = isSignExtended(N1, DAG);
6319   if (isN0SExt && isN1SExt)
6320     NewOpc = ARMISD::VMULLs;
6321   else {
6322     bool isN0ZExt = isZeroExtended(N0, DAG);
6323     bool isN1ZExt = isZeroExtended(N1, DAG);
6324     if (isN0ZExt && isN1ZExt)
6325       NewOpc = ARMISD::VMULLu;
6326     else if (isN1SExt || isN1ZExt) {
6327       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6328       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6329       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6330         NewOpc = ARMISD::VMULLs;
6331         isMLA = true;
6332       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6333         NewOpc = ARMISD::VMULLu;
6334         isMLA = true;
6335       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6336         std::swap(N0, N1);
6337         NewOpc = ARMISD::VMULLu;
6338         isMLA = true;
6339       }
6340     }
6341
6342     if (!NewOpc) {
6343       if (VT == MVT::v2i64)
6344         // Fall through to expand this.  It is not legal.
6345         return SDValue();
6346       else
6347         // Other vector multiplications are legal.
6348         return Op;
6349     }
6350   }
6351
6352   // Legalize to a VMULL instruction.
6353   SDLoc DL(Op);
6354   SDValue Op0;
6355   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6356   if (!isMLA) {
6357     Op0 = SkipExtensionForVMULL(N0, DAG);
6358     assert(Op0.getValueType().is64BitVector() &&
6359            Op1.getValueType().is64BitVector() &&
6360            "unexpected types for extended operands to VMULL");
6361     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6362   }
6363
6364   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6365   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6366   //   vmull q0, d4, d6
6367   //   vmlal q0, d5, d6
6368   // is faster than
6369   //   vaddl q0, d4, d5
6370   //   vmovl q1, d6
6371   //   vmul  q0, q0, q1
6372   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6373   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6374   EVT Op1VT = Op1.getValueType();
6375   return DAG.getNode(N0->getOpcode(), DL, VT,
6376                      DAG.getNode(NewOpc, DL, VT,
6377                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6378                      DAG.getNode(NewOpc, DL, VT,
6379                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6380 }
6381
6382 static SDValue
6383 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6384   // TODO: Should this propagate fast-math-flags?
6385
6386   // Convert to float
6387   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6388   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6389   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6390   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6391   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6392   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6393   // Get reciprocal estimate.
6394   // float4 recip = vrecpeq_f32(yf);
6395   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6396                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6397                    Y);
6398   // Because char has a smaller range than uchar, we can actually get away
6399   // without any newton steps.  This requires that we use a weird bias
6400   // of 0xb000, however (again, this has been exhaustively tested).
6401   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6402   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6403   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6404   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6405   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6406   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6407   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6408   // Convert back to short.
6409   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6410   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6411   return X;
6412 }
6413
6414 static SDValue
6415 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6416   // TODO: Should this propagate fast-math-flags?
6417
6418   SDValue N2;
6419   // Convert to float.
6420   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6421   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6422   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6423   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6424   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6425   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6426
6427   // Use reciprocal estimate and one refinement step.
6428   // float4 recip = vrecpeq_f32(yf);
6429   // recip *= vrecpsq_f32(yf, recip);
6430   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6431                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6432                    N1);
6433   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6434                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6435                    N1, N2);
6436   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6437   // Because short has a smaller range than ushort, we can actually get away
6438   // with only a single newton step.  This requires that we use a weird bias
6439   // of 89, however (again, this has been exhaustively tested).
6440   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6441   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6442   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6443   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6444   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6445   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6446   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6447   // Convert back to integer and return.
6448   // return vmovn_s32(vcvt_s32_f32(result));
6449   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6450   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6451   return N0;
6452 }
6453
6454 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6455   EVT VT = Op.getValueType();
6456   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6457          "unexpected type for custom-lowering ISD::SDIV");
6458
6459   SDLoc dl(Op);
6460   SDValue N0 = Op.getOperand(0);
6461   SDValue N1 = Op.getOperand(1);
6462   SDValue N2, N3;
6463
6464   if (VT == MVT::v8i8) {
6465     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6466     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6467
6468     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6469                      DAG.getIntPtrConstant(4, dl));
6470     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6471                      DAG.getIntPtrConstant(4, dl));
6472     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6473                      DAG.getIntPtrConstant(0, dl));
6474     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6475                      DAG.getIntPtrConstant(0, dl));
6476
6477     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6478     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6479
6480     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6481     N0 = LowerCONCAT_VECTORS(N0, DAG);
6482
6483     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6484     return N0;
6485   }
6486   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6487 }
6488
6489 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6490   // TODO: Should this propagate fast-math-flags?
6491   EVT VT = Op.getValueType();
6492   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6493          "unexpected type for custom-lowering ISD::UDIV");
6494
6495   SDLoc dl(Op);
6496   SDValue N0 = Op.getOperand(0);
6497   SDValue N1 = Op.getOperand(1);
6498   SDValue N2, N3;
6499
6500   if (VT == MVT::v8i8) {
6501     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6502     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6503
6504     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6505                      DAG.getIntPtrConstant(4, dl));
6506     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6507                      DAG.getIntPtrConstant(4, dl));
6508     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6509                      DAG.getIntPtrConstant(0, dl));
6510     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6511                      DAG.getIntPtrConstant(0, dl));
6512
6513     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6514     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6515
6516     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6517     N0 = LowerCONCAT_VECTORS(N0, DAG);
6518
6519     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6520                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6521                                      MVT::i32),
6522                      N0);
6523     return N0;
6524   }
6525
6526   // v4i16 sdiv ... Convert to float.
6527   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6528   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6529   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6530   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6531   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6532   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6533
6534   // Use reciprocal estimate and two refinement steps.
6535   // float4 recip = vrecpeq_f32(yf);
6536   // recip *= vrecpsq_f32(yf, recip);
6537   // recip *= vrecpsq_f32(yf, recip);
6538   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6539                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6540                    BN1);
6541   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6542                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6543                    BN1, N2);
6544   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6545   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6546                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6547                    BN1, N2);
6548   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6549   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6550   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6551   // and that it will never cause us to return an answer too large).
6552   // float4 result = as_float4(as_int4(xf*recip) + 2);
6553   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6554   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6555   N1 = DAG.getConstant(2, dl, MVT::i32);
6556   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6557   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6558   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6559   // Convert back to integer and return.
6560   // return vmovn_u32(vcvt_s32_f32(result));
6561   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6562   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6563   return N0;
6564 }
6565
6566 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6567   EVT VT = Op.getNode()->getValueType(0);
6568   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6569
6570   unsigned Opc;
6571   bool ExtraOp = false;
6572   switch (Op.getOpcode()) {
6573   default: llvm_unreachable("Invalid code");
6574   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6575   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6576   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6577   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6578   }
6579
6580   if (!ExtraOp)
6581     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6582                        Op.getOperand(1));
6583   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6584                      Op.getOperand(1), Op.getOperand(2));
6585 }
6586
6587 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6588   assert(Subtarget->isTargetDarwin());
6589
6590   // For iOS, we want to call an alternative entry point: __sincos_stret,
6591   // return values are passed via sret.
6592   SDLoc dl(Op);
6593   SDValue Arg = Op.getOperand(0);
6594   EVT ArgVT = Arg.getValueType();
6595   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6596   auto PtrVT = getPointerTy(DAG.getDataLayout());
6597
6598   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6599
6600   // Pair of floats / doubles used to pass the result.
6601   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6602
6603   // Create stack object for sret.
6604   auto &DL = DAG.getDataLayout();
6605   const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6606   const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6607   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6608   SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6609
6610   ArgListTy Args;
6611   ArgListEntry Entry;
6612
6613   Entry.Node = SRet;
6614   Entry.Ty = RetTy->getPointerTo();
6615   Entry.isSExt = false;
6616   Entry.isZExt = false;
6617   Entry.isSRet = true;
6618   Args.push_back(Entry);
6619
6620   Entry.Node = Arg;
6621   Entry.Ty = ArgTy;
6622   Entry.isSExt = false;
6623   Entry.isZExt = false;
6624   Args.push_back(Entry);
6625
6626   const char *LibcallName =
6627       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6628   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6629
6630   TargetLowering::CallLoweringInfo CLI(DAG);
6631   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6632     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6633                std::move(Args), 0)
6634     .setDiscardResult();
6635
6636   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6637
6638   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6639                                 MachinePointerInfo(), false, false, false, 0);
6640
6641   // Address of cos field.
6642   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6643                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6644   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6645                                 MachinePointerInfo(), false, false, false, 0);
6646
6647   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6648   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6649                      LoadSin.getValue(0), LoadCos.getValue(0));
6650 }
6651
6652 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6653                                                   bool Signed,
6654                                                   SDValue &Chain) const {
6655   EVT VT = Op.getValueType();
6656   assert((VT == MVT::i32 || VT == MVT::i64) &&
6657          "unexpected type for custom lowering DIV");
6658   SDLoc dl(Op);
6659
6660   const auto &DL = DAG.getDataLayout();
6661   const auto &TLI = DAG.getTargetLoweringInfo();
6662
6663   const char *Name = nullptr;
6664   if (Signed)
6665     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6666   else
6667     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6668
6669   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6670
6671   ARMTargetLowering::ArgListTy Args;
6672
6673   for (auto AI : {1, 0}) {
6674     ArgListEntry Arg;
6675     Arg.Node = Op.getOperand(AI);
6676     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6677     Args.push_back(Arg);
6678   }
6679
6680   CallLoweringInfo CLI(DAG);
6681   CLI.setDebugLoc(dl)
6682     .setChain(Chain)
6683     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6684                ES, std::move(Args), 0);
6685
6686   return LowerCallTo(CLI).first;
6687 }
6688
6689 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
6690                                             bool Signed) const {
6691   assert(Op.getValueType() == MVT::i32 &&
6692          "unexpected type for custom lowering DIV");
6693   SDLoc dl(Op);
6694
6695   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6696                                DAG.getEntryNode(), Op.getOperand(1));
6697
6698   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6699 }
6700
6701 void ARMTargetLowering::ExpandDIV_Windows(
6702     SDValue Op, SelectionDAG &DAG, bool Signed,
6703     SmallVectorImpl<SDValue> &Results) const {
6704   const auto &DL = DAG.getDataLayout();
6705   const auto &TLI = DAG.getTargetLoweringInfo();
6706
6707   assert(Op.getValueType() == MVT::i64 &&
6708          "unexpected type for custom lowering DIV");
6709   SDLoc dl(Op);
6710
6711   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6712                            DAG.getConstant(0, dl, MVT::i32));
6713   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6714                            DAG.getConstant(1, dl, MVT::i32));
6715   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6716
6717   SDValue DBZCHK =
6718       DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6719
6720   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6721
6722   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6723   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6724                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6725   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6726
6727   Results.push_back(Lower);
6728   Results.push_back(Upper);
6729 }
6730
6731 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6732   // Monotonic load/store is legal for all targets
6733   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6734     return Op;
6735
6736   // Acquire/Release load/store is not legal for targets without a
6737   // dmb or equivalent available.
6738   return SDValue();
6739 }
6740
6741 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6742                                     SmallVectorImpl<SDValue> &Results,
6743                                     SelectionDAG &DAG,
6744                                     const ARMSubtarget *Subtarget) {
6745   SDLoc DL(N);
6746   // Under Power Management extensions, the cycle-count is:
6747   //    mrc p15, #0, <Rt>, c9, c13, #0
6748   SDValue Ops[] = { N->getOperand(0), // Chain
6749                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6750                     DAG.getConstant(15, DL, MVT::i32),
6751                     DAG.getConstant(0, DL, MVT::i32),
6752                     DAG.getConstant(9, DL, MVT::i32),
6753                     DAG.getConstant(13, DL, MVT::i32),
6754                     DAG.getConstant(0, DL, MVT::i32)
6755   };
6756
6757   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6758                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
6759   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6760                                 DAG.getConstant(0, DL, MVT::i32)));
6761   Results.push_back(Cycles32.getValue(1));
6762 }
6763
6764 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6765   switch (Op.getOpcode()) {
6766   default: llvm_unreachable("Don't know how to custom lower this!");
6767   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6768   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6769   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6770   case ISD::GlobalAddress:
6771     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6772     default: llvm_unreachable("unknown object format");
6773     case Triple::COFF:
6774       return LowerGlobalAddressWindows(Op, DAG);
6775     case Triple::ELF:
6776       return LowerGlobalAddressELF(Op, DAG);
6777     case Triple::MachO:
6778       return LowerGlobalAddressDarwin(Op, DAG);
6779     }
6780   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6781   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6782   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6783   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6784   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6785   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6786   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6787   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6788   case ISD::SINT_TO_FP:
6789   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6790   case ISD::FP_TO_SINT:
6791   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6792   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6793   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6794   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6795   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6796   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6797   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6798   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6799   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6800                                                                Subtarget);
6801   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6802   case ISD::SHL:
6803   case ISD::SRL:
6804   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6805   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
6806   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
6807   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6808   case ISD::SRL_PARTS:
6809   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6810   case ISD::CTTZ:
6811   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6812   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6813   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6814   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6815   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6816   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6817   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6818   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6819   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6820   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6821   case ISD::MUL:           return LowerMUL(Op, DAG);
6822   case ISD::SDIV:
6823     if (Subtarget->isTargetWindows())
6824       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
6825     return LowerSDIV(Op, DAG);
6826   case ISD::UDIV:
6827     if (Subtarget->isTargetWindows())
6828       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
6829     return LowerUDIV(Op, DAG);
6830   case ISD::ADDC:
6831   case ISD::ADDE:
6832   case ISD::SUBC:
6833   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6834   case ISD::SADDO:
6835   case ISD::UADDO:
6836   case ISD::SSUBO:
6837   case ISD::USUBO:
6838     return LowerXALUO(Op, DAG);
6839   case ISD::ATOMIC_LOAD:
6840   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6841   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6842   case ISD::SDIVREM:
6843   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6844   case ISD::DYNAMIC_STACKALLOC:
6845     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6846       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6847     llvm_unreachable("Don't know how to custom lower this!");
6848   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6849   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6850   case ARMISD::WIN__DBZCHK: return SDValue();
6851   }
6852 }
6853
6854 /// ReplaceNodeResults - Replace the results of node with an illegal result
6855 /// type with new values built out of custom code.
6856 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6857                                            SmallVectorImpl<SDValue> &Results,
6858                                            SelectionDAG &DAG) const {
6859   SDValue Res;
6860   switch (N->getOpcode()) {
6861   default:
6862     llvm_unreachable("Don't know how to custom expand this!");
6863   case ISD::READ_REGISTER:
6864     ExpandREAD_REGISTER(N, Results, DAG);
6865     break;
6866   case ISD::BITCAST:
6867     Res = ExpandBITCAST(N, DAG);
6868     break;
6869   case ISD::SRL:
6870   case ISD::SRA:
6871     Res = Expand64BitShift(N, DAG, Subtarget);
6872     break;
6873   case ISD::SREM:
6874   case ISD::UREM:
6875     Res = LowerREM(N, DAG);
6876     break;
6877   case ISD::READCYCLECOUNTER:
6878     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6879     return;
6880   case ISD::UDIV:
6881   case ISD::SDIV:
6882     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
6883     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
6884                              Results);
6885   }
6886   if (Res.getNode())
6887     Results.push_back(Res);
6888 }
6889
6890 //===----------------------------------------------------------------------===//
6891 //                           ARM Scheduler Hooks
6892 //===----------------------------------------------------------------------===//
6893
6894 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6895 /// registers the function context.
6896 void ARMTargetLowering::
6897 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6898                        MachineBasicBlock *DispatchBB, int FI) const {
6899   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6900   DebugLoc dl = MI->getDebugLoc();
6901   MachineFunction *MF = MBB->getParent();
6902   MachineRegisterInfo *MRI = &MF->getRegInfo();
6903   MachineConstantPool *MCP = MF->getConstantPool();
6904   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6905   const Function *F = MF->getFunction();
6906
6907   bool isThumb = Subtarget->isThumb();
6908   bool isThumb2 = Subtarget->isThumb2();
6909
6910   unsigned PCLabelId = AFI->createPICLabelUId();
6911   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6912   ARMConstantPoolValue *CPV =
6913     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6914   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6915
6916   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6917                                            : &ARM::GPRRegClass;
6918
6919   // Grab constant pool and fixed stack memory operands.
6920   MachineMemOperand *CPMMO =
6921       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6922                                MachineMemOperand::MOLoad, 4, 4);
6923
6924   MachineMemOperand *FIMMOSt =
6925       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6926                                MachineMemOperand::MOStore, 4, 4);
6927
6928   // Load the address of the dispatch MBB into the jump buffer.
6929   if (isThumb2) {
6930     // Incoming value: jbuf
6931     //   ldr.n  r5, LCPI1_1
6932     //   orr    r5, r5, #1
6933     //   add    r5, pc
6934     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6935     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6936     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6937                    .addConstantPoolIndex(CPI)
6938                    .addMemOperand(CPMMO));
6939     // Set the low bit because of thumb mode.
6940     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6941     AddDefaultCC(
6942       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6943                      .addReg(NewVReg1, RegState::Kill)
6944                      .addImm(0x01)));
6945     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6946     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6947       .addReg(NewVReg2, RegState::Kill)
6948       .addImm(PCLabelId);
6949     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6950                    .addReg(NewVReg3, RegState::Kill)
6951                    .addFrameIndex(FI)
6952                    .addImm(36)  // &jbuf[1] :: pc
6953                    .addMemOperand(FIMMOSt));
6954   } else if (isThumb) {
6955     // Incoming value: jbuf
6956     //   ldr.n  r1, LCPI1_4
6957     //   add    r1, pc
6958     //   mov    r2, #1
6959     //   orrs   r1, r2
6960     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6961     //   str    r1, [r2]
6962     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6963     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6964                    .addConstantPoolIndex(CPI)
6965                    .addMemOperand(CPMMO));
6966     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6967     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6968       .addReg(NewVReg1, RegState::Kill)
6969       .addImm(PCLabelId);
6970     // Set the low bit because of thumb mode.
6971     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6972     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6973                    .addReg(ARM::CPSR, RegState::Define)
6974                    .addImm(1));
6975     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6976     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6977                    .addReg(ARM::CPSR, RegState::Define)
6978                    .addReg(NewVReg2, RegState::Kill)
6979                    .addReg(NewVReg3, RegState::Kill));
6980     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6981     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6982             .addFrameIndex(FI)
6983             .addImm(36); // &jbuf[1] :: pc
6984     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6985                    .addReg(NewVReg4, RegState::Kill)
6986                    .addReg(NewVReg5, RegState::Kill)
6987                    .addImm(0)
6988                    .addMemOperand(FIMMOSt));
6989   } else {
6990     // Incoming value: jbuf
6991     //   ldr  r1, LCPI1_1
6992     //   add  r1, pc, r1
6993     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6994     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6995     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6996                    .addConstantPoolIndex(CPI)
6997                    .addImm(0)
6998                    .addMemOperand(CPMMO));
6999     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7000     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7001                    .addReg(NewVReg1, RegState::Kill)
7002                    .addImm(PCLabelId));
7003     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7004                    .addReg(NewVReg2, RegState::Kill)
7005                    .addFrameIndex(FI)
7006                    .addImm(36)  // &jbuf[1] :: pc
7007                    .addMemOperand(FIMMOSt));
7008   }
7009 }
7010
7011 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
7012                                               MachineBasicBlock *MBB) const {
7013   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7014   DebugLoc dl = MI->getDebugLoc();
7015   MachineFunction *MF = MBB->getParent();
7016   MachineRegisterInfo *MRI = &MF->getRegInfo();
7017   MachineFrameInfo *MFI = MF->getFrameInfo();
7018   int FI = MFI->getFunctionContextIndex();
7019
7020   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7021                                                         : &ARM::GPRnopcRegClass;
7022
7023   // Get a mapping of the call site numbers to all of the landing pads they're
7024   // associated with.
7025   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7026   unsigned MaxCSNum = 0;
7027   MachineModuleInfo &MMI = MF->getMMI();
7028   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7029        ++BB) {
7030     if (!BB->isEHPad()) continue;
7031
7032     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7033     // pad.
7034     for (MachineBasicBlock::iterator
7035            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7036       if (!II->isEHLabel()) continue;
7037
7038       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7039       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7040
7041       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7042       for (SmallVectorImpl<unsigned>::iterator
7043              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7044            CSI != CSE; ++CSI) {
7045         CallSiteNumToLPad[*CSI].push_back(BB);
7046         MaxCSNum = std::max(MaxCSNum, *CSI);
7047       }
7048       break;
7049     }
7050   }
7051
7052   // Get an ordered list of the machine basic blocks for the jump table.
7053   std::vector<MachineBasicBlock*> LPadList;
7054   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7055   LPadList.reserve(CallSiteNumToLPad.size());
7056   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7057     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7058     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7059            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7060       LPadList.push_back(*II);
7061       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7062     }
7063   }
7064
7065   assert(!LPadList.empty() &&
7066          "No landing pad destinations for the dispatch jump table!");
7067
7068   // Create the jump table and associated information.
7069   MachineJumpTableInfo *JTI =
7070     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7071   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7072   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7073
7074   // Create the MBBs for the dispatch code.
7075
7076   // Shove the dispatch's address into the return slot in the function context.
7077   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7078   DispatchBB->setIsEHPad();
7079
7080   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7081   unsigned trap_opcode;
7082   if (Subtarget->isThumb())
7083     trap_opcode = ARM::tTRAP;
7084   else
7085     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7086
7087   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7088   DispatchBB->addSuccessor(TrapBB);
7089
7090   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7091   DispatchBB->addSuccessor(DispContBB);
7092
7093   // Insert and MBBs.
7094   MF->insert(MF->end(), DispatchBB);
7095   MF->insert(MF->end(), DispContBB);
7096   MF->insert(MF->end(), TrapBB);
7097
7098   // Insert code into the entry block that creates and registers the function
7099   // context.
7100   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7101
7102   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7103       MachinePointerInfo::getFixedStack(*MF, FI),
7104       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7105
7106   MachineInstrBuilder MIB;
7107   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7108
7109   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7110   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7111
7112   // Add a register mask with no preserved registers.  This results in all
7113   // registers being marked as clobbered.
7114   MIB.addRegMask(RI.getNoPreservedMask());
7115
7116   unsigned NumLPads = LPadList.size();
7117   if (Subtarget->isThumb2()) {
7118     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7119     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7120                    .addFrameIndex(FI)
7121                    .addImm(4)
7122                    .addMemOperand(FIMMOLd));
7123
7124     if (NumLPads < 256) {
7125       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7126                      .addReg(NewVReg1)
7127                      .addImm(LPadList.size()));
7128     } else {
7129       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7130       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7131                      .addImm(NumLPads & 0xFFFF));
7132
7133       unsigned VReg2 = VReg1;
7134       if ((NumLPads & 0xFFFF0000) != 0) {
7135         VReg2 = MRI->createVirtualRegister(TRC);
7136         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7137                        .addReg(VReg1)
7138                        .addImm(NumLPads >> 16));
7139       }
7140
7141       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7142                      .addReg(NewVReg1)
7143                      .addReg(VReg2));
7144     }
7145
7146     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7147       .addMBB(TrapBB)
7148       .addImm(ARMCC::HI)
7149       .addReg(ARM::CPSR);
7150
7151     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7152     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7153                    .addJumpTableIndex(MJTI));
7154
7155     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7156     AddDefaultCC(
7157       AddDefaultPred(
7158         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7159         .addReg(NewVReg3, RegState::Kill)
7160         .addReg(NewVReg1)
7161         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7162
7163     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7164       .addReg(NewVReg4, RegState::Kill)
7165       .addReg(NewVReg1)
7166       .addJumpTableIndex(MJTI);
7167   } else if (Subtarget->isThumb()) {
7168     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7169     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7170                    .addFrameIndex(FI)
7171                    .addImm(1)
7172                    .addMemOperand(FIMMOLd));
7173
7174     if (NumLPads < 256) {
7175       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7176                      .addReg(NewVReg1)
7177                      .addImm(NumLPads));
7178     } else {
7179       MachineConstantPool *ConstantPool = MF->getConstantPool();
7180       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7181       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7182
7183       // MachineConstantPool wants an explicit alignment.
7184       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7185       if (Align == 0)
7186         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7187       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7188
7189       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7190       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7191                      .addReg(VReg1, RegState::Define)
7192                      .addConstantPoolIndex(Idx));
7193       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7194                      .addReg(NewVReg1)
7195                      .addReg(VReg1));
7196     }
7197
7198     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7199       .addMBB(TrapBB)
7200       .addImm(ARMCC::HI)
7201       .addReg(ARM::CPSR);
7202
7203     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7204     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7205                    .addReg(ARM::CPSR, RegState::Define)
7206                    .addReg(NewVReg1)
7207                    .addImm(2));
7208
7209     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7210     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7211                    .addJumpTableIndex(MJTI));
7212
7213     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7214     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7215                    .addReg(ARM::CPSR, RegState::Define)
7216                    .addReg(NewVReg2, RegState::Kill)
7217                    .addReg(NewVReg3));
7218
7219     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7220         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7221
7222     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7223     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7224                    .addReg(NewVReg4, RegState::Kill)
7225                    .addImm(0)
7226                    .addMemOperand(JTMMOLd));
7227
7228     unsigned NewVReg6 = NewVReg5;
7229     if (RelocM == Reloc::PIC_) {
7230       NewVReg6 = MRI->createVirtualRegister(TRC);
7231       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7232                      .addReg(ARM::CPSR, RegState::Define)
7233                      .addReg(NewVReg5, RegState::Kill)
7234                      .addReg(NewVReg3));
7235     }
7236
7237     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7238       .addReg(NewVReg6, RegState::Kill)
7239       .addJumpTableIndex(MJTI);
7240   } else {
7241     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7242     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7243                    .addFrameIndex(FI)
7244                    .addImm(4)
7245                    .addMemOperand(FIMMOLd));
7246
7247     if (NumLPads < 256) {
7248       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7249                      .addReg(NewVReg1)
7250                      .addImm(NumLPads));
7251     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7252       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7253       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7254                      .addImm(NumLPads & 0xFFFF));
7255
7256       unsigned VReg2 = VReg1;
7257       if ((NumLPads & 0xFFFF0000) != 0) {
7258         VReg2 = MRI->createVirtualRegister(TRC);
7259         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7260                        .addReg(VReg1)
7261                        .addImm(NumLPads >> 16));
7262       }
7263
7264       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7265                      .addReg(NewVReg1)
7266                      .addReg(VReg2));
7267     } else {
7268       MachineConstantPool *ConstantPool = MF->getConstantPool();
7269       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7270       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7271
7272       // MachineConstantPool wants an explicit alignment.
7273       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7274       if (Align == 0)
7275         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7276       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7277
7278       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7279       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7280                      .addReg(VReg1, RegState::Define)
7281                      .addConstantPoolIndex(Idx)
7282                      .addImm(0));
7283       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7284                      .addReg(NewVReg1)
7285                      .addReg(VReg1, RegState::Kill));
7286     }
7287
7288     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7289       .addMBB(TrapBB)
7290       .addImm(ARMCC::HI)
7291       .addReg(ARM::CPSR);
7292
7293     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7294     AddDefaultCC(
7295       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7296                      .addReg(NewVReg1)
7297                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7298     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7299     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7300                    .addJumpTableIndex(MJTI));
7301
7302     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7303         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7304     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7305     AddDefaultPred(
7306       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7307       .addReg(NewVReg3, RegState::Kill)
7308       .addReg(NewVReg4)
7309       .addImm(0)
7310       .addMemOperand(JTMMOLd));
7311
7312     if (RelocM == Reloc::PIC_) {
7313       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7314         .addReg(NewVReg5, RegState::Kill)
7315         .addReg(NewVReg4)
7316         .addJumpTableIndex(MJTI);
7317     } else {
7318       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7319         .addReg(NewVReg5, RegState::Kill)
7320         .addJumpTableIndex(MJTI);
7321     }
7322   }
7323
7324   // Add the jump table entries as successors to the MBB.
7325   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7326   for (std::vector<MachineBasicBlock*>::iterator
7327          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7328     MachineBasicBlock *CurMBB = *I;
7329     if (SeenMBBs.insert(CurMBB).second)
7330       DispContBB->addSuccessor(CurMBB);
7331   }
7332
7333   // N.B. the order the invoke BBs are processed in doesn't matter here.
7334   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7335   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7336   for (MachineBasicBlock *BB : InvokeBBs) {
7337
7338     // Remove the landing pad successor from the invoke block and replace it
7339     // with the new dispatch block.
7340     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7341                                                   BB->succ_end());
7342     while (!Successors.empty()) {
7343       MachineBasicBlock *SMBB = Successors.pop_back_val();
7344       if (SMBB->isEHPad()) {
7345         BB->removeSuccessor(SMBB);
7346         MBBLPads.push_back(SMBB);
7347       }
7348     }
7349
7350     BB->addSuccessor(DispatchBB);
7351
7352     // Find the invoke call and mark all of the callee-saved registers as
7353     // 'implicit defined' so that they're spilled. This prevents code from
7354     // moving instructions to before the EH block, where they will never be
7355     // executed.
7356     for (MachineBasicBlock::reverse_iterator
7357            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7358       if (!II->isCall()) continue;
7359
7360       DenseMap<unsigned, bool> DefRegs;
7361       for (MachineInstr::mop_iterator
7362              OI = II->operands_begin(), OE = II->operands_end();
7363            OI != OE; ++OI) {
7364         if (!OI->isReg()) continue;
7365         DefRegs[OI->getReg()] = true;
7366       }
7367
7368       MachineInstrBuilder MIB(*MF, &*II);
7369
7370       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7371         unsigned Reg = SavedRegs[i];
7372         if (Subtarget->isThumb2() &&
7373             !ARM::tGPRRegClass.contains(Reg) &&
7374             !ARM::hGPRRegClass.contains(Reg))
7375           continue;
7376         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7377           continue;
7378         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7379           continue;
7380         if (!DefRegs[Reg])
7381           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7382       }
7383
7384       break;
7385     }
7386   }
7387
7388   // Mark all former landing pads as non-landing pads. The dispatch is the only
7389   // landing pad now.
7390   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7391          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7392     (*I)->setIsEHPad(false);
7393
7394   // The instruction is gone now.
7395   MI->eraseFromParent();
7396 }
7397
7398 static
7399 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7400   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7401        E = MBB->succ_end(); I != E; ++I)
7402     if (*I != Succ)
7403       return *I;
7404   llvm_unreachable("Expecting a BB with two successors!");
7405 }
7406
7407 /// Return the load opcode for a given load size. If load size >= 8,
7408 /// neon opcode will be returned.
7409 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7410   if (LdSize >= 8)
7411     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7412                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7413   if (IsThumb1)
7414     return LdSize == 4 ? ARM::tLDRi
7415                        : LdSize == 2 ? ARM::tLDRHi
7416                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7417   if (IsThumb2)
7418     return LdSize == 4 ? ARM::t2LDR_POST
7419                        : LdSize == 2 ? ARM::t2LDRH_POST
7420                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7421   return LdSize == 4 ? ARM::LDR_POST_IMM
7422                      : LdSize == 2 ? ARM::LDRH_POST
7423                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7424 }
7425
7426 /// Return the store opcode for a given store size. If store size >= 8,
7427 /// neon opcode will be returned.
7428 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7429   if (StSize >= 8)
7430     return StSize == 16 ? ARM::VST1q32wb_fixed
7431                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7432   if (IsThumb1)
7433     return StSize == 4 ? ARM::tSTRi
7434                        : StSize == 2 ? ARM::tSTRHi
7435                                      : StSize == 1 ? ARM::tSTRBi : 0;
7436   if (IsThumb2)
7437     return StSize == 4 ? ARM::t2STR_POST
7438                        : StSize == 2 ? ARM::t2STRH_POST
7439                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7440   return StSize == 4 ? ARM::STR_POST_IMM
7441                      : StSize == 2 ? ARM::STRH_POST
7442                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7443 }
7444
7445 /// Emit a post-increment load operation with given size. The instructions
7446 /// will be added to BB at Pos.
7447 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7448                        const TargetInstrInfo *TII, DebugLoc dl,
7449                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7450                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7451   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7452   assert(LdOpc != 0 && "Should have a load opcode");
7453   if (LdSize >= 8) {
7454     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7455                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7456                        .addImm(0));
7457   } else if (IsThumb1) {
7458     // load + update AddrIn
7459     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7460                        .addReg(AddrIn).addImm(0));
7461     MachineInstrBuilder MIB =
7462         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7463     MIB = AddDefaultT1CC(MIB);
7464     MIB.addReg(AddrIn).addImm(LdSize);
7465     AddDefaultPred(MIB);
7466   } else if (IsThumb2) {
7467     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7468                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7469                        .addImm(LdSize));
7470   } else { // arm
7471     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7472                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7473                        .addReg(0).addImm(LdSize));
7474   }
7475 }
7476
7477 /// Emit a post-increment store operation with given size. The instructions
7478 /// will be added to BB at Pos.
7479 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7480                        const TargetInstrInfo *TII, DebugLoc dl,
7481                        unsigned StSize, unsigned Data, unsigned AddrIn,
7482                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7483   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7484   assert(StOpc != 0 && "Should have a store opcode");
7485   if (StSize >= 8) {
7486     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7487                        .addReg(AddrIn).addImm(0).addReg(Data));
7488   } else if (IsThumb1) {
7489     // store + update AddrIn
7490     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7491                        .addReg(AddrIn).addImm(0));
7492     MachineInstrBuilder MIB =
7493         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7494     MIB = AddDefaultT1CC(MIB);
7495     MIB.addReg(AddrIn).addImm(StSize);
7496     AddDefaultPred(MIB);
7497   } else if (IsThumb2) {
7498     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7499                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7500   } else { // arm
7501     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7502                        .addReg(Data).addReg(AddrIn).addReg(0)
7503                        .addImm(StSize));
7504   }
7505 }
7506
7507 MachineBasicBlock *
7508 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7509                                    MachineBasicBlock *BB) const {
7510   // This pseudo instruction has 3 operands: dst, src, size
7511   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7512   // Otherwise, we will generate unrolled scalar copies.
7513   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7514   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7515   MachineFunction::iterator It = BB;
7516   ++It;
7517
7518   unsigned dest = MI->getOperand(0).getReg();
7519   unsigned src = MI->getOperand(1).getReg();
7520   unsigned SizeVal = MI->getOperand(2).getImm();
7521   unsigned Align = MI->getOperand(3).getImm();
7522   DebugLoc dl = MI->getDebugLoc();
7523
7524   MachineFunction *MF = BB->getParent();
7525   MachineRegisterInfo &MRI = MF->getRegInfo();
7526   unsigned UnitSize = 0;
7527   const TargetRegisterClass *TRC = nullptr;
7528   const TargetRegisterClass *VecTRC = nullptr;
7529
7530   bool IsThumb1 = Subtarget->isThumb1Only();
7531   bool IsThumb2 = Subtarget->isThumb2();
7532
7533   if (Align & 1) {
7534     UnitSize = 1;
7535   } else if (Align & 2) {
7536     UnitSize = 2;
7537   } else {
7538     // Check whether we can use NEON instructions.
7539     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7540         Subtarget->hasNEON()) {
7541       if ((Align % 16 == 0) && SizeVal >= 16)
7542         UnitSize = 16;
7543       else if ((Align % 8 == 0) && SizeVal >= 8)
7544         UnitSize = 8;
7545     }
7546     // Can't use NEON instructions.
7547     if (UnitSize == 0)
7548       UnitSize = 4;
7549   }
7550
7551   // Select the correct opcode and register class for unit size load/store
7552   bool IsNeon = UnitSize >= 8;
7553   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7554   if (IsNeon)
7555     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7556                             : UnitSize == 8 ? &ARM::DPRRegClass
7557                                             : nullptr;
7558
7559   unsigned BytesLeft = SizeVal % UnitSize;
7560   unsigned LoopSize = SizeVal - BytesLeft;
7561
7562   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7563     // Use LDR and STR to copy.
7564     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7565     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7566     unsigned srcIn = src;
7567     unsigned destIn = dest;
7568     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7569       unsigned srcOut = MRI.createVirtualRegister(TRC);
7570       unsigned destOut = MRI.createVirtualRegister(TRC);
7571       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7572       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7573                  IsThumb1, IsThumb2);
7574       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7575                  IsThumb1, IsThumb2);
7576       srcIn = srcOut;
7577       destIn = destOut;
7578     }
7579
7580     // Handle the leftover bytes with LDRB and STRB.
7581     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7582     // [destOut] = STRB_POST(scratch, destIn, 1)
7583     for (unsigned i = 0; i < BytesLeft; i++) {
7584       unsigned srcOut = MRI.createVirtualRegister(TRC);
7585       unsigned destOut = MRI.createVirtualRegister(TRC);
7586       unsigned scratch = MRI.createVirtualRegister(TRC);
7587       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7588                  IsThumb1, IsThumb2);
7589       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7590                  IsThumb1, IsThumb2);
7591       srcIn = srcOut;
7592       destIn = destOut;
7593     }
7594     MI->eraseFromParent();   // The instruction is gone now.
7595     return BB;
7596   }
7597
7598   // Expand the pseudo op to a loop.
7599   // thisMBB:
7600   //   ...
7601   //   movw varEnd, # --> with thumb2
7602   //   movt varEnd, #
7603   //   ldrcp varEnd, idx --> without thumb2
7604   //   fallthrough --> loopMBB
7605   // loopMBB:
7606   //   PHI varPhi, varEnd, varLoop
7607   //   PHI srcPhi, src, srcLoop
7608   //   PHI destPhi, dst, destLoop
7609   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7610   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7611   //   subs varLoop, varPhi, #UnitSize
7612   //   bne loopMBB
7613   //   fallthrough --> exitMBB
7614   // exitMBB:
7615   //   epilogue to handle left-over bytes
7616   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7617   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7618   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7619   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7620   MF->insert(It, loopMBB);
7621   MF->insert(It, exitMBB);
7622
7623   // Transfer the remainder of BB and its successor edges to exitMBB.
7624   exitMBB->splice(exitMBB->begin(), BB,
7625                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7626   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7627
7628   // Load an immediate to varEnd.
7629   unsigned varEnd = MRI.createVirtualRegister(TRC);
7630   if (Subtarget->useMovt(*MF)) {
7631     unsigned Vtmp = varEnd;
7632     if ((LoopSize & 0xFFFF0000) != 0)
7633       Vtmp = MRI.createVirtualRegister(TRC);
7634     AddDefaultPred(BuildMI(BB, dl,
7635                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7636                            Vtmp).addImm(LoopSize & 0xFFFF));
7637
7638     if ((LoopSize & 0xFFFF0000) != 0)
7639       AddDefaultPred(BuildMI(BB, dl,
7640                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7641                              varEnd)
7642                          .addReg(Vtmp)
7643                          .addImm(LoopSize >> 16));
7644   } else {
7645     MachineConstantPool *ConstantPool = MF->getConstantPool();
7646     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7647     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7648
7649     // MachineConstantPool wants an explicit alignment.
7650     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7651     if (Align == 0)
7652       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7653     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7654
7655     if (IsThumb1)
7656       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7657           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7658     else
7659       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7660           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7661   }
7662   BB->addSuccessor(loopMBB);
7663
7664   // Generate the loop body:
7665   //   varPhi = PHI(varLoop, varEnd)
7666   //   srcPhi = PHI(srcLoop, src)
7667   //   destPhi = PHI(destLoop, dst)
7668   MachineBasicBlock *entryBB = BB;
7669   BB = loopMBB;
7670   unsigned varLoop = MRI.createVirtualRegister(TRC);
7671   unsigned varPhi = MRI.createVirtualRegister(TRC);
7672   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7673   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7674   unsigned destLoop = MRI.createVirtualRegister(TRC);
7675   unsigned destPhi = MRI.createVirtualRegister(TRC);
7676
7677   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7678     .addReg(varLoop).addMBB(loopMBB)
7679     .addReg(varEnd).addMBB(entryBB);
7680   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7681     .addReg(srcLoop).addMBB(loopMBB)
7682     .addReg(src).addMBB(entryBB);
7683   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7684     .addReg(destLoop).addMBB(loopMBB)
7685     .addReg(dest).addMBB(entryBB);
7686
7687   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7688   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7689   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7690   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7691              IsThumb1, IsThumb2);
7692   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7693              IsThumb1, IsThumb2);
7694
7695   // Decrement loop variable by UnitSize.
7696   if (IsThumb1) {
7697     MachineInstrBuilder MIB =
7698         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7699     MIB = AddDefaultT1CC(MIB);
7700     MIB.addReg(varPhi).addImm(UnitSize);
7701     AddDefaultPred(MIB);
7702   } else {
7703     MachineInstrBuilder MIB =
7704         BuildMI(*BB, BB->end(), dl,
7705                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7706     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7707     MIB->getOperand(5).setReg(ARM::CPSR);
7708     MIB->getOperand(5).setIsDef(true);
7709   }
7710   BuildMI(*BB, BB->end(), dl,
7711           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7712       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7713
7714   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7715   BB->addSuccessor(loopMBB);
7716   BB->addSuccessor(exitMBB);
7717
7718   // Add epilogue to handle BytesLeft.
7719   BB = exitMBB;
7720   MachineInstr *StartOfExit = exitMBB->begin();
7721
7722   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7723   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7724   unsigned srcIn = srcLoop;
7725   unsigned destIn = destLoop;
7726   for (unsigned i = 0; i < BytesLeft; i++) {
7727     unsigned srcOut = MRI.createVirtualRegister(TRC);
7728     unsigned destOut = MRI.createVirtualRegister(TRC);
7729     unsigned scratch = MRI.createVirtualRegister(TRC);
7730     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7731                IsThumb1, IsThumb2);
7732     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7733                IsThumb1, IsThumb2);
7734     srcIn = srcOut;
7735     destIn = destOut;
7736   }
7737
7738   MI->eraseFromParent();   // The instruction is gone now.
7739   return BB;
7740 }
7741
7742 MachineBasicBlock *
7743 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7744                                        MachineBasicBlock *MBB) const {
7745   const TargetMachine &TM = getTargetMachine();
7746   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7747   DebugLoc DL = MI->getDebugLoc();
7748
7749   assert(Subtarget->isTargetWindows() &&
7750          "__chkstk is only supported on Windows");
7751   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7752
7753   // __chkstk takes the number of words to allocate on the stack in R4, and
7754   // returns the stack adjustment in number of bytes in R4.  This will not
7755   // clober any other registers (other than the obvious lr).
7756   //
7757   // Although, technically, IP should be considered a register which may be
7758   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7759   // thumb-2 environment, so there is no interworking required.  As a result, we
7760   // do not expect a veneer to be emitted by the linker, clobbering IP.
7761   //
7762   // Each module receives its own copy of __chkstk, so no import thunk is
7763   // required, again, ensuring that IP is not clobbered.
7764   //
7765   // Finally, although some linkers may theoretically provide a trampoline for
7766   // out of range calls (which is quite common due to a 32M range limitation of
7767   // branches for Thumb), we can generate the long-call version via
7768   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7769   // IP.
7770
7771   switch (TM.getCodeModel()) {
7772   case CodeModel::Small:
7773   case CodeModel::Medium:
7774   case CodeModel::Default:
7775   case CodeModel::Kernel:
7776     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7777       .addImm((unsigned)ARMCC::AL).addReg(0)
7778       .addExternalSymbol("__chkstk")
7779       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7780       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7781       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7782     break;
7783   case CodeModel::Large:
7784   case CodeModel::JITDefault: {
7785     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7786     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7787
7788     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7789       .addExternalSymbol("__chkstk");
7790     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7791       .addImm((unsigned)ARMCC::AL).addReg(0)
7792       .addReg(Reg, RegState::Kill)
7793       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7794       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7795       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7796     break;
7797   }
7798   }
7799
7800   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7801                                       ARM::SP)
7802                               .addReg(ARM::SP).addReg(ARM::R4)));
7803
7804   MI->eraseFromParent();
7805   return MBB;
7806 }
7807
7808 MachineBasicBlock *
7809 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
7810                                        MachineBasicBlock *MBB) const {
7811   DebugLoc DL = MI->getDebugLoc();
7812   MachineFunction *MF = MBB->getParent();
7813   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7814
7815   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
7816   MF->push_back(ContBB);
7817   ContBB->splice(ContBB->begin(), MBB,
7818                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7819   MBB->addSuccessor(ContBB);
7820
7821   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7822   MF->push_back(TrapBB);
7823   BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
7824   MBB->addSuccessor(TrapBB);
7825
7826   BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
7827       .addReg(MI->getOperand(0).getReg())
7828       .addMBB(TrapBB);
7829
7830   MI->eraseFromParent();
7831   return ContBB;
7832 }
7833
7834 MachineBasicBlock *
7835 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7836                                                MachineBasicBlock *BB) const {
7837   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7838   DebugLoc dl = MI->getDebugLoc();
7839   bool isThumb2 = Subtarget->isThumb2();
7840   switch (MI->getOpcode()) {
7841   default: {
7842     MI->dump();
7843     llvm_unreachable("Unexpected instr type to insert");
7844   }
7845   // The Thumb2 pre-indexed stores have the same MI operands, they just
7846   // define them differently in the .td files from the isel patterns, so
7847   // they need pseudos.
7848   case ARM::t2STR_preidx:
7849     MI->setDesc(TII->get(ARM::t2STR_PRE));
7850     return BB;
7851   case ARM::t2STRB_preidx:
7852     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7853     return BB;
7854   case ARM::t2STRH_preidx:
7855     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7856     return BB;
7857
7858   case ARM::STRi_preidx:
7859   case ARM::STRBi_preidx: {
7860     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7861       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7862     // Decode the offset.
7863     unsigned Offset = MI->getOperand(4).getImm();
7864     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7865     Offset = ARM_AM::getAM2Offset(Offset);
7866     if (isSub)
7867       Offset = -Offset;
7868
7869     MachineMemOperand *MMO = *MI->memoperands_begin();
7870     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7871       .addOperand(MI->getOperand(0))  // Rn_wb
7872       .addOperand(MI->getOperand(1))  // Rt
7873       .addOperand(MI->getOperand(2))  // Rn
7874       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7875       .addOperand(MI->getOperand(5))  // pred
7876       .addOperand(MI->getOperand(6))
7877       .addMemOperand(MMO);
7878     MI->eraseFromParent();
7879     return BB;
7880   }
7881   case ARM::STRr_preidx:
7882   case ARM::STRBr_preidx:
7883   case ARM::STRH_preidx: {
7884     unsigned NewOpc;
7885     switch (MI->getOpcode()) {
7886     default: llvm_unreachable("unexpected opcode!");
7887     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7888     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7889     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7890     }
7891     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7892     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7893       MIB.addOperand(MI->getOperand(i));
7894     MI->eraseFromParent();
7895     return BB;
7896   }
7897
7898   case ARM::tMOVCCr_pseudo: {
7899     // To "insert" a SELECT_CC instruction, we actually have to insert the
7900     // diamond control-flow pattern.  The incoming instruction knows the
7901     // destination vreg to set, the condition code register to branch on, the
7902     // true/false values to select between, and a branch opcode to use.
7903     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7904     MachineFunction::iterator It = BB;
7905     ++It;
7906
7907     //  thisMBB:
7908     //  ...
7909     //   TrueVal = ...
7910     //   cmpTY ccX, r1, r2
7911     //   bCC copy1MBB
7912     //   fallthrough --> copy0MBB
7913     MachineBasicBlock *thisMBB  = BB;
7914     MachineFunction *F = BB->getParent();
7915     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7916     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7917     F->insert(It, copy0MBB);
7918     F->insert(It, sinkMBB);
7919
7920     // Transfer the remainder of BB and its successor edges to sinkMBB.
7921     sinkMBB->splice(sinkMBB->begin(), BB,
7922                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7923     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7924
7925     BB->addSuccessor(copy0MBB);
7926     BB->addSuccessor(sinkMBB);
7927
7928     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7929       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7930
7931     //  copy0MBB:
7932     //   %FalseValue = ...
7933     //   # fallthrough to sinkMBB
7934     BB = copy0MBB;
7935
7936     // Update machine-CFG edges
7937     BB->addSuccessor(sinkMBB);
7938
7939     //  sinkMBB:
7940     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7941     //  ...
7942     BB = sinkMBB;
7943     BuildMI(*BB, BB->begin(), dl,
7944             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7945       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7946       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7947
7948     MI->eraseFromParent();   // The pseudo instruction is gone now.
7949     return BB;
7950   }
7951
7952   case ARM::BCCi64:
7953   case ARM::BCCZi64: {
7954     // If there is an unconditional branch to the other successor, remove it.
7955     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7956
7957     // Compare both parts that make up the double comparison separately for
7958     // equality.
7959     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7960
7961     unsigned LHS1 = MI->getOperand(1).getReg();
7962     unsigned LHS2 = MI->getOperand(2).getReg();
7963     if (RHSisZero) {
7964       AddDefaultPred(BuildMI(BB, dl,
7965                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7966                      .addReg(LHS1).addImm(0));
7967       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7968         .addReg(LHS2).addImm(0)
7969         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7970     } else {
7971       unsigned RHS1 = MI->getOperand(3).getReg();
7972       unsigned RHS2 = MI->getOperand(4).getReg();
7973       AddDefaultPred(BuildMI(BB, dl,
7974                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7975                      .addReg(LHS1).addReg(RHS1));
7976       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7977         .addReg(LHS2).addReg(RHS2)
7978         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7979     }
7980
7981     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7982     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7983     if (MI->getOperand(0).getImm() == ARMCC::NE)
7984       std::swap(destMBB, exitMBB);
7985
7986     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7987       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7988     if (isThumb2)
7989       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7990     else
7991       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7992
7993     MI->eraseFromParent();   // The pseudo instruction is gone now.
7994     return BB;
7995   }
7996
7997   case ARM::Int_eh_sjlj_setjmp:
7998   case ARM::Int_eh_sjlj_setjmp_nofp:
7999   case ARM::tInt_eh_sjlj_setjmp:
8000   case ARM::t2Int_eh_sjlj_setjmp:
8001   case ARM::t2Int_eh_sjlj_setjmp_nofp:
8002     return BB;
8003
8004   case ARM::Int_eh_sjlj_setup_dispatch:
8005     EmitSjLjDispatchBlock(MI, BB);
8006     return BB;
8007
8008   case ARM::ABS:
8009   case ARM::t2ABS: {
8010     // To insert an ABS instruction, we have to insert the
8011     // diamond control-flow pattern.  The incoming instruction knows the
8012     // source vreg to test against 0, the destination vreg to set,
8013     // the condition code register to branch on, the
8014     // true/false values to select between, and a branch opcode to use.
8015     // It transforms
8016     //     V1 = ABS V0
8017     // into
8018     //     V2 = MOVS V0
8019     //     BCC                      (branch to SinkBB if V0 >= 0)
8020     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
8021     //     SinkBB: V1 = PHI(V2, V3)
8022     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8023     MachineFunction::iterator BBI = BB;
8024     ++BBI;
8025     MachineFunction *Fn = BB->getParent();
8026     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8027     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
8028     Fn->insert(BBI, RSBBB);
8029     Fn->insert(BBI, SinkBB);
8030
8031     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8032     unsigned int ABSDstReg = MI->getOperand(0).getReg();
8033     bool ABSSrcKIll = MI->getOperand(1).isKill();
8034     bool isThumb2 = Subtarget->isThumb2();
8035     MachineRegisterInfo &MRI = Fn->getRegInfo();
8036     // In Thumb mode S must not be specified if source register is the SP or
8037     // PC and if destination register is the SP, so restrict register class
8038     unsigned NewRsbDstReg =
8039       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8040
8041     // Transfer the remainder of BB and its successor edges to sinkMBB.
8042     SinkBB->splice(SinkBB->begin(), BB,
8043                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
8044     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8045
8046     BB->addSuccessor(RSBBB);
8047     BB->addSuccessor(SinkBB);
8048
8049     // fall through to SinkMBB
8050     RSBBB->addSuccessor(SinkBB);
8051
8052     // insert a cmp at the end of BB
8053     AddDefaultPred(BuildMI(BB, dl,
8054                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8055                    .addReg(ABSSrcReg).addImm(0));
8056
8057     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8058     BuildMI(BB, dl,
8059       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8060       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8061
8062     // insert rsbri in RSBBB
8063     // Note: BCC and rsbri will be converted into predicated rsbmi
8064     // by if-conversion pass
8065     BuildMI(*RSBBB, RSBBB->begin(), dl,
8066       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8067       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8068       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8069
8070     // insert PHI in SinkBB,
8071     // reuse ABSDstReg to not change uses of ABS instruction
8072     BuildMI(*SinkBB, SinkBB->begin(), dl,
8073       TII->get(ARM::PHI), ABSDstReg)
8074       .addReg(NewRsbDstReg).addMBB(RSBBB)
8075       .addReg(ABSSrcReg).addMBB(BB);
8076
8077     // remove ABS instruction
8078     MI->eraseFromParent();
8079
8080     // return last added BB
8081     return SinkBB;
8082   }
8083   case ARM::COPY_STRUCT_BYVAL_I32:
8084     ++NumLoopByVals;
8085     return EmitStructByval(MI, BB);
8086   case ARM::WIN__CHKSTK:
8087     return EmitLowered__chkstk(MI, BB);
8088   case ARM::WIN__DBZCHK:
8089     return EmitLowered__dbzchk(MI, BB);
8090   }
8091 }
8092
8093 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8094                                                       SDNode *Node) const {
8095   const MCInstrDesc *MCID = &MI->getDesc();
8096   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8097   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8098   // operand is still set to noreg. If needed, set the optional operand's
8099   // register to CPSR, and remove the redundant implicit def.
8100   //
8101   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8102
8103   // Rename pseudo opcodes.
8104   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8105   if (NewOpc) {
8106     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8107     MCID = &TII->get(NewOpc);
8108
8109     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8110            "converted opcode should be the same except for cc_out");
8111
8112     MI->setDesc(*MCID);
8113
8114     // Add the optional cc_out operand
8115     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8116   }
8117   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8118
8119   // Any ARM instruction that sets the 's' bit should specify an optional
8120   // "cc_out" operand in the last operand position.
8121   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8122     assert(!NewOpc && "Optional cc_out operand required");
8123     return;
8124   }
8125   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8126   // since we already have an optional CPSR def.
8127   bool definesCPSR = false;
8128   bool deadCPSR = false;
8129   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8130        i != e; ++i) {
8131     const MachineOperand &MO = MI->getOperand(i);
8132     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8133       definesCPSR = true;
8134       if (MO.isDead())
8135         deadCPSR = true;
8136       MI->RemoveOperand(i);
8137       break;
8138     }
8139   }
8140   if (!definesCPSR) {
8141     assert(!NewOpc && "Optional cc_out operand required");
8142     return;
8143   }
8144   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8145   if (deadCPSR) {
8146     assert(!MI->getOperand(ccOutIdx).getReg() &&
8147            "expect uninitialized optional cc_out operand");
8148     return;
8149   }
8150
8151   // If this instruction was defined with an optional CPSR def and its dag node
8152   // had a live implicit CPSR def, then activate the optional CPSR def.
8153   MachineOperand &MO = MI->getOperand(ccOutIdx);
8154   MO.setReg(ARM::CPSR);
8155   MO.setIsDef(true);
8156 }
8157
8158 //===----------------------------------------------------------------------===//
8159 //                           ARM Optimization Hooks
8160 //===----------------------------------------------------------------------===//
8161
8162 // Helper function that checks if N is a null or all ones constant.
8163 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8164   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8165   if (!C)
8166     return false;
8167   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8168 }
8169
8170 // Return true if N is conditionally 0 or all ones.
8171 // Detects these expressions where cc is an i1 value:
8172 //
8173 //   (select cc 0, y)   [AllOnes=0]
8174 //   (select cc y, 0)   [AllOnes=0]
8175 //   (zext cc)          [AllOnes=0]
8176 //   (sext cc)          [AllOnes=0/1]
8177 //   (select cc -1, y)  [AllOnes=1]
8178 //   (select cc y, -1)  [AllOnes=1]
8179 //
8180 // Invert is set when N is the null/all ones constant when CC is false.
8181 // OtherOp is set to the alternative value of N.
8182 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8183                                        SDValue &CC, bool &Invert,
8184                                        SDValue &OtherOp,
8185                                        SelectionDAG &DAG) {
8186   switch (N->getOpcode()) {
8187   default: return false;
8188   case ISD::SELECT: {
8189     CC = N->getOperand(0);
8190     SDValue N1 = N->getOperand(1);
8191     SDValue N2 = N->getOperand(2);
8192     if (isZeroOrAllOnes(N1, AllOnes)) {
8193       Invert = false;
8194       OtherOp = N2;
8195       return true;
8196     }
8197     if (isZeroOrAllOnes(N2, AllOnes)) {
8198       Invert = true;
8199       OtherOp = N1;
8200       return true;
8201     }
8202     return false;
8203   }
8204   case ISD::ZERO_EXTEND:
8205     // (zext cc) can never be the all ones value.
8206     if (AllOnes)
8207       return false;
8208     // Fall through.
8209   case ISD::SIGN_EXTEND: {
8210     SDLoc dl(N);
8211     EVT VT = N->getValueType(0);
8212     CC = N->getOperand(0);
8213     if (CC.getValueType() != MVT::i1)
8214       return false;
8215     Invert = !AllOnes;
8216     if (AllOnes)
8217       // When looking for an AllOnes constant, N is an sext, and the 'other'
8218       // value is 0.
8219       OtherOp = DAG.getConstant(0, dl, VT);
8220     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8221       // When looking for a 0 constant, N can be zext or sext.
8222       OtherOp = DAG.getConstant(1, dl, VT);
8223     else
8224       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8225                                 VT);
8226     return true;
8227   }
8228   }
8229 }
8230
8231 // Combine a constant select operand into its use:
8232 //
8233 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8234 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8235 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8236 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8237 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8238 //
8239 // The transform is rejected if the select doesn't have a constant operand that
8240 // is null, or all ones when AllOnes is set.
8241 //
8242 // Also recognize sext/zext from i1:
8243 //
8244 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8245 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8246 //
8247 // These transformations eventually create predicated instructions.
8248 //
8249 // @param N       The node to transform.
8250 // @param Slct    The N operand that is a select.
8251 // @param OtherOp The other N operand (x above).
8252 // @param DCI     Context.
8253 // @param AllOnes Require the select constant to be all ones instead of null.
8254 // @returns The new node, or SDValue() on failure.
8255 static
8256 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8257                             TargetLowering::DAGCombinerInfo &DCI,
8258                             bool AllOnes = false) {
8259   SelectionDAG &DAG = DCI.DAG;
8260   EVT VT = N->getValueType(0);
8261   SDValue NonConstantVal;
8262   SDValue CCOp;
8263   bool SwapSelectOps;
8264   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8265                                   NonConstantVal, DAG))
8266     return SDValue();
8267
8268   // Slct is now know to be the desired identity constant when CC is true.
8269   SDValue TrueVal = OtherOp;
8270   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8271                                  OtherOp, NonConstantVal);
8272   // Unless SwapSelectOps says CC should be false.
8273   if (SwapSelectOps)
8274     std::swap(TrueVal, FalseVal);
8275
8276   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8277                      CCOp, TrueVal, FalseVal);
8278 }
8279
8280 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8281 static
8282 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8283                                        TargetLowering::DAGCombinerInfo &DCI) {
8284   SDValue N0 = N->getOperand(0);
8285   SDValue N1 = N->getOperand(1);
8286   if (N0.getNode()->hasOneUse()) {
8287     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8288     if (Result.getNode())
8289       return Result;
8290   }
8291   if (N1.getNode()->hasOneUse()) {
8292     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8293     if (Result.getNode())
8294       return Result;
8295   }
8296   return SDValue();
8297 }
8298
8299 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8300 // (only after legalization).
8301 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8302                                  TargetLowering::DAGCombinerInfo &DCI,
8303                                  const ARMSubtarget *Subtarget) {
8304
8305   // Only perform optimization if after legalize, and if NEON is available. We
8306   // also expected both operands to be BUILD_VECTORs.
8307   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8308       || N0.getOpcode() != ISD::BUILD_VECTOR
8309       || N1.getOpcode() != ISD::BUILD_VECTOR)
8310     return SDValue();
8311
8312   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8313   EVT VT = N->getValueType(0);
8314   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8315     return SDValue();
8316
8317   // Check that the vector operands are of the right form.
8318   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8319   // operands, where N is the size of the formed vector.
8320   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8321   // index such that we have a pair wise add pattern.
8322
8323   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8324   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8325     return SDValue();
8326   SDValue Vec = N0->getOperand(0)->getOperand(0);
8327   SDNode *V = Vec.getNode();
8328   unsigned nextIndex = 0;
8329
8330   // For each operands to the ADD which are BUILD_VECTORs,
8331   // check to see if each of their operands are an EXTRACT_VECTOR with
8332   // the same vector and appropriate index.
8333   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8334     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8335         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8336
8337       SDValue ExtVec0 = N0->getOperand(i);
8338       SDValue ExtVec1 = N1->getOperand(i);
8339
8340       // First operand is the vector, verify its the same.
8341       if (V != ExtVec0->getOperand(0).getNode() ||
8342           V != ExtVec1->getOperand(0).getNode())
8343         return SDValue();
8344
8345       // Second is the constant, verify its correct.
8346       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8347       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8348
8349       // For the constant, we want to see all the even or all the odd.
8350       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8351           || C1->getZExtValue() != nextIndex+1)
8352         return SDValue();
8353
8354       // Increment index.
8355       nextIndex+=2;
8356     } else
8357       return SDValue();
8358   }
8359
8360   // Create VPADDL node.
8361   SelectionDAG &DAG = DCI.DAG;
8362   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8363
8364   SDLoc dl(N);
8365
8366   // Build operand list.
8367   SmallVector<SDValue, 8> Ops;
8368   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8369                                 TLI.getPointerTy(DAG.getDataLayout())));
8370
8371   // Input is the vector.
8372   Ops.push_back(Vec);
8373
8374   // Get widened type and narrowed type.
8375   MVT widenType;
8376   unsigned numElem = VT.getVectorNumElements();
8377   
8378   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8379   switch (inputLaneType.getSimpleVT().SimpleTy) {
8380     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8381     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8382     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8383     default:
8384       llvm_unreachable("Invalid vector element type for padd optimization.");
8385   }
8386
8387   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8388   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8389   return DAG.getNode(ExtOp, dl, VT, tmp);
8390 }
8391
8392 static SDValue findMUL_LOHI(SDValue V) {
8393   if (V->getOpcode() == ISD::UMUL_LOHI ||
8394       V->getOpcode() == ISD::SMUL_LOHI)
8395     return V;
8396   return SDValue();
8397 }
8398
8399 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8400                                      TargetLowering::DAGCombinerInfo &DCI,
8401                                      const ARMSubtarget *Subtarget) {
8402
8403   if (Subtarget->isThumb1Only()) return SDValue();
8404
8405   // Only perform the checks after legalize when the pattern is available.
8406   if (DCI.isBeforeLegalize()) return SDValue();
8407
8408   // Look for multiply add opportunities.
8409   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8410   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8411   // a glue link from the first add to the second add.
8412   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8413   // a S/UMLAL instruction.
8414   //                  UMUL_LOHI
8415   //                 / :lo    \ :hi
8416   //                /          \          [no multiline comment]
8417   //    loAdd ->  ADDE         |
8418   //                 \ :glue  /
8419   //                  \      /
8420   //                    ADDC   <- hiAdd
8421   //
8422   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8423   SDValue AddcOp0 = AddcNode->getOperand(0);
8424   SDValue AddcOp1 = AddcNode->getOperand(1);
8425
8426   // Check if the two operands are from the same mul_lohi node.
8427   if (AddcOp0.getNode() == AddcOp1.getNode())
8428     return SDValue();
8429
8430   assert(AddcNode->getNumValues() == 2 &&
8431          AddcNode->getValueType(0) == MVT::i32 &&
8432          "Expect ADDC with two result values. First: i32");
8433
8434   // Check that we have a glued ADDC node.
8435   if (AddcNode->getValueType(1) != MVT::Glue)
8436     return SDValue();
8437
8438   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8439   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8440       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8441       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8442       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8443     return SDValue();
8444
8445   // Look for the glued ADDE.
8446   SDNode* AddeNode = AddcNode->getGluedUser();
8447   if (!AddeNode)
8448     return SDValue();
8449
8450   // Make sure it is really an ADDE.
8451   if (AddeNode->getOpcode() != ISD::ADDE)
8452     return SDValue();
8453
8454   assert(AddeNode->getNumOperands() == 3 &&
8455          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8456          "ADDE node has the wrong inputs");
8457
8458   // Check for the triangle shape.
8459   SDValue AddeOp0 = AddeNode->getOperand(0);
8460   SDValue AddeOp1 = AddeNode->getOperand(1);
8461
8462   // Make sure that the ADDE operands are not coming from the same node.
8463   if (AddeOp0.getNode() == AddeOp1.getNode())
8464     return SDValue();
8465
8466   // Find the MUL_LOHI node walking up ADDE's operands.
8467   bool IsLeftOperandMUL = false;
8468   SDValue MULOp = findMUL_LOHI(AddeOp0);
8469   if (MULOp == SDValue())
8470    MULOp = findMUL_LOHI(AddeOp1);
8471   else
8472     IsLeftOperandMUL = true;
8473   if (MULOp == SDValue())
8474     return SDValue();
8475
8476   // Figure out the right opcode.
8477   unsigned Opc = MULOp->getOpcode();
8478   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8479
8480   // Figure out the high and low input values to the MLAL node.
8481   SDValue* HiAdd = nullptr;
8482   SDValue* LoMul = nullptr;
8483   SDValue* LowAdd = nullptr;
8484
8485   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8486   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8487     return SDValue();
8488
8489   if (IsLeftOperandMUL)
8490     HiAdd = &AddeOp1;
8491   else
8492     HiAdd = &AddeOp0;
8493
8494
8495   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8496   // whose low result is fed to the ADDC we are checking.
8497
8498   if (AddcOp0 == MULOp.getValue(0)) {
8499     LoMul = &AddcOp0;
8500     LowAdd = &AddcOp1;
8501   }
8502   if (AddcOp1 == MULOp.getValue(0)) {
8503     LoMul = &AddcOp1;
8504     LowAdd = &AddcOp0;
8505   }
8506
8507   if (!LoMul)
8508     return SDValue();
8509
8510   // Create the merged node.
8511   SelectionDAG &DAG = DCI.DAG;
8512
8513   // Build operand list.
8514   SmallVector<SDValue, 8> Ops;
8515   Ops.push_back(LoMul->getOperand(0));
8516   Ops.push_back(LoMul->getOperand(1));
8517   Ops.push_back(*LowAdd);
8518   Ops.push_back(*HiAdd);
8519
8520   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8521                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8522
8523   // Replace the ADDs' nodes uses by the MLA node's values.
8524   SDValue HiMLALResult(MLALNode.getNode(), 1);
8525   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8526
8527   SDValue LoMLALResult(MLALNode.getNode(), 0);
8528   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8529
8530   // Return original node to notify the driver to stop replacing.
8531   SDValue resNode(AddcNode, 0);
8532   return resNode;
8533 }
8534
8535 /// PerformADDCCombine - Target-specific dag combine transform from
8536 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8537 static SDValue PerformADDCCombine(SDNode *N,
8538                                  TargetLowering::DAGCombinerInfo &DCI,
8539                                  const ARMSubtarget *Subtarget) {
8540
8541   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8542
8543 }
8544
8545 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8546 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8547 /// called with the default operands, and if that fails, with commuted
8548 /// operands.
8549 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8550                                           TargetLowering::DAGCombinerInfo &DCI,
8551                                           const ARMSubtarget *Subtarget){
8552
8553   // Attempt to create vpaddl for this add.
8554   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8555   if (Result.getNode())
8556     return Result;
8557
8558   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8559   if (N0.getNode()->hasOneUse()) {
8560     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8561     if (Result.getNode()) return Result;
8562   }
8563   return SDValue();
8564 }
8565
8566 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8567 ///
8568 static SDValue PerformADDCombine(SDNode *N,
8569                                  TargetLowering::DAGCombinerInfo &DCI,
8570                                  const ARMSubtarget *Subtarget) {
8571   SDValue N0 = N->getOperand(0);
8572   SDValue N1 = N->getOperand(1);
8573
8574   // First try with the default operand order.
8575   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8576   if (Result.getNode())
8577     return Result;
8578
8579   // If that didn't work, try again with the operands commuted.
8580   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8581 }
8582
8583 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8584 ///
8585 static SDValue PerformSUBCombine(SDNode *N,
8586                                  TargetLowering::DAGCombinerInfo &DCI) {
8587   SDValue N0 = N->getOperand(0);
8588   SDValue N1 = N->getOperand(1);
8589
8590   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8591   if (N1.getNode()->hasOneUse()) {
8592     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8593     if (Result.getNode()) return Result;
8594   }
8595
8596   return SDValue();
8597 }
8598
8599 /// PerformVMULCombine
8600 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8601 /// special multiplier accumulator forwarding.
8602 ///   vmul d3, d0, d2
8603 ///   vmla d3, d1, d2
8604 /// is faster than
8605 ///   vadd d3, d0, d1
8606 ///   vmul d3, d3, d2
8607 //  However, for (A + B) * (A + B),
8608 //    vadd d2, d0, d1
8609 //    vmul d3, d0, d2
8610 //    vmla d3, d1, d2
8611 //  is slower than
8612 //    vadd d2, d0, d1
8613 //    vmul d3, d2, d2
8614 static SDValue PerformVMULCombine(SDNode *N,
8615                                   TargetLowering::DAGCombinerInfo &DCI,
8616                                   const ARMSubtarget *Subtarget) {
8617   if (!Subtarget->hasVMLxForwarding())
8618     return SDValue();
8619
8620   SelectionDAG &DAG = DCI.DAG;
8621   SDValue N0 = N->getOperand(0);
8622   SDValue N1 = N->getOperand(1);
8623   unsigned Opcode = N0.getOpcode();
8624   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8625       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8626     Opcode = N1.getOpcode();
8627     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8628         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8629       return SDValue();
8630     std::swap(N0, N1);
8631   }
8632
8633   if (N0 == N1)
8634     return SDValue();
8635
8636   EVT VT = N->getValueType(0);
8637   SDLoc DL(N);
8638   SDValue N00 = N0->getOperand(0);
8639   SDValue N01 = N0->getOperand(1);
8640   return DAG.getNode(Opcode, DL, VT,
8641                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8642                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8643 }
8644
8645 static SDValue PerformMULCombine(SDNode *N,
8646                                  TargetLowering::DAGCombinerInfo &DCI,
8647                                  const ARMSubtarget *Subtarget) {
8648   SelectionDAG &DAG = DCI.DAG;
8649
8650   if (Subtarget->isThumb1Only())
8651     return SDValue();
8652
8653   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8654     return SDValue();
8655
8656   EVT VT = N->getValueType(0);
8657   if (VT.is64BitVector() || VT.is128BitVector())
8658     return PerformVMULCombine(N, DCI, Subtarget);
8659   if (VT != MVT::i32)
8660     return SDValue();
8661
8662   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8663   if (!C)
8664     return SDValue();
8665
8666   int64_t MulAmt = C->getSExtValue();
8667   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8668
8669   ShiftAmt = ShiftAmt & (32 - 1);
8670   SDValue V = N->getOperand(0);
8671   SDLoc DL(N);
8672
8673   SDValue Res;
8674   MulAmt >>= ShiftAmt;
8675
8676   if (MulAmt >= 0) {
8677     if (isPowerOf2_32(MulAmt - 1)) {
8678       // (mul x, 2^N + 1) => (add (shl x, N), x)
8679       Res = DAG.getNode(ISD::ADD, DL, VT,
8680                         V,
8681                         DAG.getNode(ISD::SHL, DL, VT,
8682                                     V,
8683                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8684                                                     MVT::i32)));
8685     } else if (isPowerOf2_32(MulAmt + 1)) {
8686       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8687       Res = DAG.getNode(ISD::SUB, DL, VT,
8688                         DAG.getNode(ISD::SHL, DL, VT,
8689                                     V,
8690                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8691                                                     MVT::i32)),
8692                         V);
8693     } else
8694       return SDValue();
8695   } else {
8696     uint64_t MulAmtAbs = -MulAmt;
8697     if (isPowerOf2_32(MulAmtAbs + 1)) {
8698       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8699       Res = DAG.getNode(ISD::SUB, DL, VT,
8700                         V,
8701                         DAG.getNode(ISD::SHL, DL, VT,
8702                                     V,
8703                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8704                                                     MVT::i32)));
8705     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8706       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8707       Res = DAG.getNode(ISD::ADD, DL, VT,
8708                         V,
8709                         DAG.getNode(ISD::SHL, DL, VT,
8710                                     V,
8711                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8712                                                     MVT::i32)));
8713       Res = DAG.getNode(ISD::SUB, DL, VT,
8714                         DAG.getConstant(0, DL, MVT::i32), Res);
8715
8716     } else
8717       return SDValue();
8718   }
8719
8720   if (ShiftAmt != 0)
8721     Res = DAG.getNode(ISD::SHL, DL, VT,
8722                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8723
8724   // Do not add new nodes to DAG combiner worklist.
8725   DCI.CombineTo(N, Res, false);
8726   return SDValue();
8727 }
8728
8729 static SDValue PerformANDCombine(SDNode *N,
8730                                  TargetLowering::DAGCombinerInfo &DCI,
8731                                  const ARMSubtarget *Subtarget) {
8732
8733   // Attempt to use immediate-form VBIC
8734   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8735   SDLoc dl(N);
8736   EVT VT = N->getValueType(0);
8737   SelectionDAG &DAG = DCI.DAG;
8738
8739   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8740     return SDValue();
8741
8742   APInt SplatBits, SplatUndef;
8743   unsigned SplatBitSize;
8744   bool HasAnyUndefs;
8745   if (BVN &&
8746       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8747     if (SplatBitSize <= 64) {
8748       EVT VbicVT;
8749       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8750                                       SplatUndef.getZExtValue(), SplatBitSize,
8751                                       DAG, dl, VbicVT, VT.is128BitVector(),
8752                                       OtherModImm);
8753       if (Val.getNode()) {
8754         SDValue Input =
8755           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8756         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8757         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8758       }
8759     }
8760   }
8761
8762   if (!Subtarget->isThumb1Only()) {
8763     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8764     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8765     if (Result.getNode())
8766       return Result;
8767   }
8768
8769   return SDValue();
8770 }
8771
8772 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8773 static SDValue PerformORCombine(SDNode *N,
8774                                 TargetLowering::DAGCombinerInfo &DCI,
8775                                 const ARMSubtarget *Subtarget) {
8776   // Attempt to use immediate-form VORR
8777   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8778   SDLoc dl(N);
8779   EVT VT = N->getValueType(0);
8780   SelectionDAG &DAG = DCI.DAG;
8781
8782   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8783     return SDValue();
8784
8785   APInt SplatBits, SplatUndef;
8786   unsigned SplatBitSize;
8787   bool HasAnyUndefs;
8788   if (BVN && Subtarget->hasNEON() &&
8789       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8790     if (SplatBitSize <= 64) {
8791       EVT VorrVT;
8792       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8793                                       SplatUndef.getZExtValue(), SplatBitSize,
8794                                       DAG, dl, VorrVT, VT.is128BitVector(),
8795                                       OtherModImm);
8796       if (Val.getNode()) {
8797         SDValue Input =
8798           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8799         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8800         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8801       }
8802     }
8803   }
8804
8805   if (!Subtarget->isThumb1Only()) {
8806     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8807     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8808     if (Result.getNode())
8809       return Result;
8810   }
8811
8812   // The code below optimizes (or (and X, Y), Z).
8813   // The AND operand needs to have a single user to make these optimizations
8814   // profitable.
8815   SDValue N0 = N->getOperand(0);
8816   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8817     return SDValue();
8818   SDValue N1 = N->getOperand(1);
8819
8820   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8821   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8822       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8823     APInt SplatUndef;
8824     unsigned SplatBitSize;
8825     bool HasAnyUndefs;
8826
8827     APInt SplatBits0, SplatBits1;
8828     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8829     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8830     // Ensure that the second operand of both ands are constants
8831     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8832                                       HasAnyUndefs) && !HasAnyUndefs) {
8833         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8834                                           HasAnyUndefs) && !HasAnyUndefs) {
8835             // Ensure that the bit width of the constants are the same and that
8836             // the splat arguments are logical inverses as per the pattern we
8837             // are trying to simplify.
8838             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8839                 SplatBits0 == ~SplatBits1) {
8840                 // Canonicalize the vector type to make instruction selection
8841                 // simpler.
8842                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8843                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8844                                              N0->getOperand(1),
8845                                              N0->getOperand(0),
8846                                              N1->getOperand(0));
8847                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8848             }
8849         }
8850     }
8851   }
8852
8853   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8854   // reasonable.
8855
8856   // BFI is only available on V6T2+
8857   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8858     return SDValue();
8859
8860   SDLoc DL(N);
8861   // 1) or (and A, mask), val => ARMbfi A, val, mask
8862   //      iff (val & mask) == val
8863   //
8864   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8865   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8866   //          && mask == ~mask2
8867   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8868   //          && ~mask == mask2
8869   //  (i.e., copy a bitfield value into another bitfield of the same width)
8870
8871   if (VT != MVT::i32)
8872     return SDValue();
8873
8874   SDValue N00 = N0.getOperand(0);
8875
8876   // The value and the mask need to be constants so we can verify this is
8877   // actually a bitfield set. If the mask is 0xffff, we can do better
8878   // via a movt instruction, so don't use BFI in that case.
8879   SDValue MaskOp = N0.getOperand(1);
8880   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8881   if (!MaskC)
8882     return SDValue();
8883   unsigned Mask = MaskC->getZExtValue();
8884   if (Mask == 0xffff)
8885     return SDValue();
8886   SDValue Res;
8887   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8888   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8889   if (N1C) {
8890     unsigned Val = N1C->getZExtValue();
8891     if ((Val & ~Mask) != Val)
8892       return SDValue();
8893
8894     if (ARM::isBitFieldInvertedMask(Mask)) {
8895       Val >>= countTrailingZeros(~Mask);
8896
8897       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8898                         DAG.getConstant(Val, DL, MVT::i32),
8899                         DAG.getConstant(Mask, DL, MVT::i32));
8900
8901       // Do not add new nodes to DAG combiner worklist.
8902       DCI.CombineTo(N, Res, false);
8903       return SDValue();
8904     }
8905   } else if (N1.getOpcode() == ISD::AND) {
8906     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8907     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8908     if (!N11C)
8909       return SDValue();
8910     unsigned Mask2 = N11C->getZExtValue();
8911
8912     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8913     // as is to match.
8914     if (ARM::isBitFieldInvertedMask(Mask) &&
8915         (Mask == ~Mask2)) {
8916       // The pack halfword instruction works better for masks that fit it,
8917       // so use that when it's available.
8918       if (Subtarget->hasT2ExtractPack() &&
8919           (Mask == 0xffff || Mask == 0xffff0000))
8920         return SDValue();
8921       // 2a
8922       unsigned amt = countTrailingZeros(Mask2);
8923       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8924                         DAG.getConstant(amt, DL, MVT::i32));
8925       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8926                         DAG.getConstant(Mask, DL, MVT::i32));
8927       // Do not add new nodes to DAG combiner worklist.
8928       DCI.CombineTo(N, Res, false);
8929       return SDValue();
8930     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8931                (~Mask == Mask2)) {
8932       // The pack halfword instruction works better for masks that fit it,
8933       // so use that when it's available.
8934       if (Subtarget->hasT2ExtractPack() &&
8935           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8936         return SDValue();
8937       // 2b
8938       unsigned lsb = countTrailingZeros(Mask);
8939       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8940                         DAG.getConstant(lsb, DL, MVT::i32));
8941       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8942                         DAG.getConstant(Mask2, DL, MVT::i32));
8943       // Do not add new nodes to DAG combiner worklist.
8944       DCI.CombineTo(N, Res, false);
8945       return SDValue();
8946     }
8947   }
8948
8949   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8950       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8951       ARM::isBitFieldInvertedMask(~Mask)) {
8952     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8953     // where lsb(mask) == #shamt and masked bits of B are known zero.
8954     SDValue ShAmt = N00.getOperand(1);
8955     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8956     unsigned LSB = countTrailingZeros(Mask);
8957     if (ShAmtC != LSB)
8958       return SDValue();
8959
8960     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8961                       DAG.getConstant(~Mask, DL, MVT::i32));
8962
8963     // Do not add new nodes to DAG combiner worklist.
8964     DCI.CombineTo(N, Res, false);
8965   }
8966
8967   return SDValue();
8968 }
8969
8970 static SDValue PerformXORCombine(SDNode *N,
8971                                  TargetLowering::DAGCombinerInfo &DCI,
8972                                  const ARMSubtarget *Subtarget) {
8973   EVT VT = N->getValueType(0);
8974   SelectionDAG &DAG = DCI.DAG;
8975
8976   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8977     return SDValue();
8978
8979   if (!Subtarget->isThumb1Only()) {
8980     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8981     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8982     if (Result.getNode())
8983       return Result;
8984   }
8985
8986   return SDValue();
8987 }
8988
8989 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8990 /// the bits being cleared by the AND are not demanded by the BFI.
8991 static SDValue PerformBFICombine(SDNode *N,
8992                                  TargetLowering::DAGCombinerInfo &DCI) {
8993   SDValue N1 = N->getOperand(1);
8994   if (N1.getOpcode() == ISD::AND) {
8995     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8996     if (!N11C)
8997       return SDValue();
8998     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8999     unsigned LSB = countTrailingZeros(~InvMask);
9000     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9001     assert(Width <
9002                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9003            "undefined behavior");
9004     unsigned Mask = (1u << Width) - 1;
9005     unsigned Mask2 = N11C->getZExtValue();
9006     if ((Mask & (~Mask2)) == 0)
9007       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9008                              N->getOperand(0), N1.getOperand(0),
9009                              N->getOperand(2));
9010   }
9011   return SDValue();
9012 }
9013
9014 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9015 /// ARMISD::VMOVRRD.
9016 static SDValue PerformVMOVRRDCombine(SDNode *N,
9017                                      TargetLowering::DAGCombinerInfo &DCI,
9018                                      const ARMSubtarget *Subtarget) {
9019   // vmovrrd(vmovdrr x, y) -> x,y
9020   SDValue InDouble = N->getOperand(0);
9021   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9022     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9023
9024   // vmovrrd(load f64) -> (load i32), (load i32)
9025   SDNode *InNode = InDouble.getNode();
9026   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9027       InNode->getValueType(0) == MVT::f64 &&
9028       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9029       !cast<LoadSDNode>(InNode)->isVolatile()) {
9030     // TODO: Should this be done for non-FrameIndex operands?
9031     LoadSDNode *LD = cast<LoadSDNode>(InNode);
9032
9033     SelectionDAG &DAG = DCI.DAG;
9034     SDLoc DL(LD);
9035     SDValue BasePtr = LD->getBasePtr();
9036     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9037                                  LD->getPointerInfo(), LD->isVolatile(),
9038                                  LD->isNonTemporal(), LD->isInvariant(),
9039                                  LD->getAlignment());
9040
9041     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9042                                     DAG.getConstant(4, DL, MVT::i32));
9043     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9044                                  LD->getPointerInfo(), LD->isVolatile(),
9045                                  LD->isNonTemporal(), LD->isInvariant(),
9046                                  std::min(4U, LD->getAlignment() / 2));
9047
9048     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9049     if (DCI.DAG.getDataLayout().isBigEndian())
9050       std::swap (NewLD1, NewLD2);
9051     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9052     return Result;
9053   }
9054
9055   return SDValue();
9056 }
9057
9058 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9059 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
9060 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9061   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9062   SDValue Op0 = N->getOperand(0);
9063   SDValue Op1 = N->getOperand(1);
9064   if (Op0.getOpcode() == ISD::BITCAST)
9065     Op0 = Op0.getOperand(0);
9066   if (Op1.getOpcode() == ISD::BITCAST)
9067     Op1 = Op1.getOperand(0);
9068   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9069       Op0.getNode() == Op1.getNode() &&
9070       Op0.getResNo() == 0 && Op1.getResNo() == 1)
9071     return DAG.getNode(ISD::BITCAST, SDLoc(N),
9072                        N->getValueType(0), Op0.getOperand(0));
9073   return SDValue();
9074 }
9075
9076 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9077 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9078 /// i64 vector to have f64 elements, since the value can then be loaded
9079 /// directly into a VFP register.
9080 static bool hasNormalLoadOperand(SDNode *N) {
9081   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9082   for (unsigned i = 0; i < NumElts; ++i) {
9083     SDNode *Elt = N->getOperand(i).getNode();
9084     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9085       return true;
9086   }
9087   return false;
9088 }
9089
9090 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9091 /// ISD::BUILD_VECTOR.
9092 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9093                                           TargetLowering::DAGCombinerInfo &DCI,
9094                                           const ARMSubtarget *Subtarget) {
9095   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9096   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9097   // into a pair of GPRs, which is fine when the value is used as a scalar,
9098   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9099   SelectionDAG &DAG = DCI.DAG;
9100   if (N->getNumOperands() == 2) {
9101     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9102     if (RV.getNode())
9103       return RV;
9104   }
9105
9106   // Load i64 elements as f64 values so that type legalization does not split
9107   // them up into i32 values.
9108   EVT VT = N->getValueType(0);
9109   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9110     return SDValue();
9111   SDLoc dl(N);
9112   SmallVector<SDValue, 8> Ops;
9113   unsigned NumElts = VT.getVectorNumElements();
9114   for (unsigned i = 0; i < NumElts; ++i) {
9115     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9116     Ops.push_back(V);
9117     // Make the DAGCombiner fold the bitcast.
9118     DCI.AddToWorklist(V.getNode());
9119   }
9120   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9121   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9122   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9123 }
9124
9125 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9126 static SDValue
9127 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9128   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9129   // At that time, we may have inserted bitcasts from integer to float.
9130   // If these bitcasts have survived DAGCombine, change the lowering of this
9131   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9132   // force to use floating point types.
9133
9134   // Make sure we can change the type of the vector.
9135   // This is possible iff:
9136   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9137   //    1.1. Vector is used only once.
9138   //    1.2. Use is a bit convert to an integer type.
9139   // 2. The size of its operands are 32-bits (64-bits are not legal).
9140   EVT VT = N->getValueType(0);
9141   EVT EltVT = VT.getVectorElementType();
9142
9143   // Check 1.1. and 2.
9144   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9145     return SDValue();
9146
9147   // By construction, the input type must be float.
9148   assert(EltVT == MVT::f32 && "Unexpected type!");
9149
9150   // Check 1.2.
9151   SDNode *Use = *N->use_begin();
9152   if (Use->getOpcode() != ISD::BITCAST ||
9153       Use->getValueType(0).isFloatingPoint())
9154     return SDValue();
9155
9156   // Check profitability.
9157   // Model is, if more than half of the relevant operands are bitcast from
9158   // i32, turn the build_vector into a sequence of insert_vector_elt.
9159   // Relevant operands are everything that is not statically
9160   // (i.e., at compile time) bitcasted.
9161   unsigned NumOfBitCastedElts = 0;
9162   unsigned NumElts = VT.getVectorNumElements();
9163   unsigned NumOfRelevantElts = NumElts;
9164   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9165     SDValue Elt = N->getOperand(Idx);
9166     if (Elt->getOpcode() == ISD::BITCAST) {
9167       // Assume only bit cast to i32 will go away.
9168       if (Elt->getOperand(0).getValueType() == MVT::i32)
9169         ++NumOfBitCastedElts;
9170     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9171       // Constants are statically casted, thus do not count them as
9172       // relevant operands.
9173       --NumOfRelevantElts;
9174   }
9175
9176   // Check if more than half of the elements require a non-free bitcast.
9177   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9178     return SDValue();
9179
9180   SelectionDAG &DAG = DCI.DAG;
9181   // Create the new vector type.
9182   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9183   // Check if the type is legal.
9184   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9185   if (!TLI.isTypeLegal(VecVT))
9186     return SDValue();
9187
9188   // Combine:
9189   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9190   // => BITCAST INSERT_VECTOR_ELT
9191   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9192   //                      (BITCAST EN), N.
9193   SDValue Vec = DAG.getUNDEF(VecVT);
9194   SDLoc dl(N);
9195   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9196     SDValue V = N->getOperand(Idx);
9197     if (V.getOpcode() == ISD::UNDEF)
9198       continue;
9199     if (V.getOpcode() == ISD::BITCAST &&
9200         V->getOperand(0).getValueType() == MVT::i32)
9201       // Fold obvious case.
9202       V = V.getOperand(0);
9203     else {
9204       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9205       // Make the DAGCombiner fold the bitcasts.
9206       DCI.AddToWorklist(V.getNode());
9207     }
9208     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9209     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9210   }
9211   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9212   // Make the DAGCombiner fold the bitcasts.
9213   DCI.AddToWorklist(Vec.getNode());
9214   return Vec;
9215 }
9216
9217 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9218 /// ISD::INSERT_VECTOR_ELT.
9219 static SDValue PerformInsertEltCombine(SDNode *N,
9220                                        TargetLowering::DAGCombinerInfo &DCI) {
9221   // Bitcast an i64 load inserted into a vector to f64.
9222   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9223   EVT VT = N->getValueType(0);
9224   SDNode *Elt = N->getOperand(1).getNode();
9225   if (VT.getVectorElementType() != MVT::i64 ||
9226       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9227     return SDValue();
9228
9229   SelectionDAG &DAG = DCI.DAG;
9230   SDLoc dl(N);
9231   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9232                                  VT.getVectorNumElements());
9233   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9234   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9235   // Make the DAGCombiner fold the bitcasts.
9236   DCI.AddToWorklist(Vec.getNode());
9237   DCI.AddToWorklist(V.getNode());
9238   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9239                                Vec, V, N->getOperand(2));
9240   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9241 }
9242
9243 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9244 /// ISD::VECTOR_SHUFFLE.
9245 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9246   // The LLVM shufflevector instruction does not require the shuffle mask
9247   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9248   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9249   // operands do not match the mask length, they are extended by concatenating
9250   // them with undef vectors.  That is probably the right thing for other
9251   // targets, but for NEON it is better to concatenate two double-register
9252   // size vector operands into a single quad-register size vector.  Do that
9253   // transformation here:
9254   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9255   //   shuffle(concat(v1, v2), undef)
9256   SDValue Op0 = N->getOperand(0);
9257   SDValue Op1 = N->getOperand(1);
9258   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9259       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9260       Op0.getNumOperands() != 2 ||
9261       Op1.getNumOperands() != 2)
9262     return SDValue();
9263   SDValue Concat0Op1 = Op0.getOperand(1);
9264   SDValue Concat1Op1 = Op1.getOperand(1);
9265   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9266       Concat1Op1.getOpcode() != ISD::UNDEF)
9267     return SDValue();
9268   // Skip the transformation if any of the types are illegal.
9269   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9270   EVT VT = N->getValueType(0);
9271   if (!TLI.isTypeLegal(VT) ||
9272       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9273       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9274     return SDValue();
9275
9276   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9277                                   Op0.getOperand(0), Op1.getOperand(0));
9278   // Translate the shuffle mask.
9279   SmallVector<int, 16> NewMask;
9280   unsigned NumElts = VT.getVectorNumElements();
9281   unsigned HalfElts = NumElts/2;
9282   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9283   for (unsigned n = 0; n < NumElts; ++n) {
9284     int MaskElt = SVN->getMaskElt(n);
9285     int NewElt = -1;
9286     if (MaskElt < (int)HalfElts)
9287       NewElt = MaskElt;
9288     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9289       NewElt = HalfElts + MaskElt - NumElts;
9290     NewMask.push_back(NewElt);
9291   }
9292   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9293                               DAG.getUNDEF(VT), NewMask.data());
9294 }
9295
9296 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9297 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9298 /// base address updates.
9299 /// For generic load/stores, the memory type is assumed to be a vector.
9300 /// The caller is assumed to have checked legality.
9301 static SDValue CombineBaseUpdate(SDNode *N,
9302                                  TargetLowering::DAGCombinerInfo &DCI) {
9303   SelectionDAG &DAG = DCI.DAG;
9304   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9305                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9306   const bool isStore = N->getOpcode() == ISD::STORE;
9307   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9308   SDValue Addr = N->getOperand(AddrOpIdx);
9309   MemSDNode *MemN = cast<MemSDNode>(N);
9310   SDLoc dl(N);
9311
9312   // Search for a use of the address operand that is an increment.
9313   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9314          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9315     SDNode *User = *UI;
9316     if (User->getOpcode() != ISD::ADD ||
9317         UI.getUse().getResNo() != Addr.getResNo())
9318       continue;
9319
9320     // Check that the add is independent of the load/store.  Otherwise, folding
9321     // it would create a cycle.
9322     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9323       continue;
9324
9325     // Find the new opcode for the updating load/store.
9326     bool isLoadOp = true;
9327     bool isLaneOp = false;
9328     unsigned NewOpc = 0;
9329     unsigned NumVecs = 0;
9330     if (isIntrinsic) {
9331       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9332       switch (IntNo) {
9333       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9334       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9335         NumVecs = 1; break;
9336       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9337         NumVecs = 2; break;
9338       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9339         NumVecs = 3; break;
9340       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9341         NumVecs = 4; break;
9342       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9343         NumVecs = 2; isLaneOp = true; break;
9344       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9345         NumVecs = 3; isLaneOp = true; break;
9346       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9347         NumVecs = 4; isLaneOp = true; break;
9348       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9349         NumVecs = 1; isLoadOp = false; break;
9350       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9351         NumVecs = 2; isLoadOp = false; break;
9352       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9353         NumVecs = 3; isLoadOp = false; break;
9354       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9355         NumVecs = 4; isLoadOp = false; break;
9356       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9357         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9358       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9359         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9360       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9361         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9362       }
9363     } else {
9364       isLaneOp = true;
9365       switch (N->getOpcode()) {
9366       default: llvm_unreachable("unexpected opcode for Neon base update");
9367       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9368       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9369       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9370       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9371         NumVecs = 1; isLaneOp = false; break;
9372       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9373         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9374       }
9375     }
9376
9377     // Find the size of memory referenced by the load/store.
9378     EVT VecTy;
9379     if (isLoadOp) {
9380       VecTy = N->getValueType(0);
9381     } else if (isIntrinsic) {
9382       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9383     } else {
9384       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9385       VecTy = N->getOperand(1).getValueType();
9386     }
9387
9388     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9389     if (isLaneOp)
9390       NumBytes /= VecTy.getVectorNumElements();
9391
9392     // If the increment is a constant, it must match the memory ref size.
9393     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9394     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9395       uint64_t IncVal = CInc->getZExtValue();
9396       if (IncVal != NumBytes)
9397         continue;
9398     } else if (NumBytes >= 3 * 16) {
9399       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9400       // separate instructions that make it harder to use a non-constant update.
9401       continue;
9402     }
9403
9404     // OK, we found an ADD we can fold into the base update.
9405     // Now, create a _UPD node, taking care of not breaking alignment.
9406
9407     EVT AlignedVecTy = VecTy;
9408     unsigned Alignment = MemN->getAlignment();
9409
9410     // If this is a less-than-standard-aligned load/store, change the type to
9411     // match the standard alignment.
9412     // The alignment is overlooked when selecting _UPD variants; and it's
9413     // easier to introduce bitcasts here than fix that.
9414     // There are 3 ways to get to this base-update combine:
9415     // - intrinsics: they are assumed to be properly aligned (to the standard
9416     //   alignment of the memory type), so we don't need to do anything.
9417     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9418     //   intrinsics, so, likewise, there's nothing to do.
9419     // - generic load/store instructions: the alignment is specified as an
9420     //   explicit operand, rather than implicitly as the standard alignment
9421     //   of the memory type (like the intrisics).  We need to change the
9422     //   memory type to match the explicit alignment.  That way, we don't
9423     //   generate non-standard-aligned ARMISD::VLDx nodes.
9424     if (isa<LSBaseSDNode>(N)) {
9425       if (Alignment == 0)
9426         Alignment = 1;
9427       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9428         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9429         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9430         assert(!isLaneOp && "Unexpected generic load/store lane.");
9431         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9432         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9433       }
9434       // Don't set an explicit alignment on regular load/stores that we want
9435       // to transform to VLD/VST 1_UPD nodes.
9436       // This matches the behavior of regular load/stores, which only get an
9437       // explicit alignment if the MMO alignment is larger than the standard
9438       // alignment of the memory type.
9439       // Intrinsics, however, always get an explicit alignment, set to the
9440       // alignment of the MMO.
9441       Alignment = 1;
9442     }
9443
9444     // Create the new updating load/store node.
9445     // First, create an SDVTList for the new updating node's results.
9446     EVT Tys[6];
9447     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9448     unsigned n;
9449     for (n = 0; n < NumResultVecs; ++n)
9450       Tys[n] = AlignedVecTy;
9451     Tys[n++] = MVT::i32;
9452     Tys[n] = MVT::Other;
9453     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9454
9455     // Then, gather the new node's operands.
9456     SmallVector<SDValue, 8> Ops;
9457     Ops.push_back(N->getOperand(0)); // incoming chain
9458     Ops.push_back(N->getOperand(AddrOpIdx));
9459     Ops.push_back(Inc);
9460
9461     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9462       // Try to match the intrinsic's signature
9463       Ops.push_back(StN->getValue());
9464     } else {
9465       // Loads (and of course intrinsics) match the intrinsics' signature,
9466       // so just add all but the alignment operand.
9467       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9468         Ops.push_back(N->getOperand(i));
9469     }
9470
9471     // For all node types, the alignment operand is always the last one.
9472     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9473
9474     // If this is a non-standard-aligned STORE, the penultimate operand is the
9475     // stored value.  Bitcast it to the aligned type.
9476     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9477       SDValue &StVal = Ops[Ops.size()-2];
9478       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9479     }
9480
9481     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9482                                            Ops, AlignedVecTy,
9483                                            MemN->getMemOperand());
9484
9485     // Update the uses.
9486     SmallVector<SDValue, 5> NewResults;
9487     for (unsigned i = 0; i < NumResultVecs; ++i)
9488       NewResults.push_back(SDValue(UpdN.getNode(), i));
9489
9490     // If this is an non-standard-aligned LOAD, the first result is the loaded
9491     // value.  Bitcast it to the expected result type.
9492     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9493       SDValue &LdVal = NewResults[0];
9494       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9495     }
9496
9497     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9498     DCI.CombineTo(N, NewResults);
9499     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9500
9501     break;
9502   }
9503   return SDValue();
9504 }
9505
9506 static SDValue PerformVLDCombine(SDNode *N,
9507                                  TargetLowering::DAGCombinerInfo &DCI) {
9508   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9509     return SDValue();
9510
9511   return CombineBaseUpdate(N, DCI);
9512 }
9513
9514 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9515 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9516 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9517 /// return true.
9518 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9519   SelectionDAG &DAG = DCI.DAG;
9520   EVT VT = N->getValueType(0);
9521   // vldN-dup instructions only support 64-bit vectors for N > 1.
9522   if (!VT.is64BitVector())
9523     return false;
9524
9525   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9526   SDNode *VLD = N->getOperand(0).getNode();
9527   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9528     return false;
9529   unsigned NumVecs = 0;
9530   unsigned NewOpc = 0;
9531   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9532   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9533     NumVecs = 2;
9534     NewOpc = ARMISD::VLD2DUP;
9535   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9536     NumVecs = 3;
9537     NewOpc = ARMISD::VLD3DUP;
9538   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9539     NumVecs = 4;
9540     NewOpc = ARMISD::VLD4DUP;
9541   } else {
9542     return false;
9543   }
9544
9545   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9546   // numbers match the load.
9547   unsigned VLDLaneNo =
9548     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9549   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9550        UI != UE; ++UI) {
9551     // Ignore uses of the chain result.
9552     if (UI.getUse().getResNo() == NumVecs)
9553       continue;
9554     SDNode *User = *UI;
9555     if (User->getOpcode() != ARMISD::VDUPLANE ||
9556         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9557       return false;
9558   }
9559
9560   // Create the vldN-dup node.
9561   EVT Tys[5];
9562   unsigned n;
9563   for (n = 0; n < NumVecs; ++n)
9564     Tys[n] = VT;
9565   Tys[n] = MVT::Other;
9566   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9567   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9568   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9569   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9570                                            Ops, VLDMemInt->getMemoryVT(),
9571                                            VLDMemInt->getMemOperand());
9572
9573   // Update the uses.
9574   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9575        UI != UE; ++UI) {
9576     unsigned ResNo = UI.getUse().getResNo();
9577     // Ignore uses of the chain result.
9578     if (ResNo == NumVecs)
9579       continue;
9580     SDNode *User = *UI;
9581     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9582   }
9583
9584   // Now the vldN-lane intrinsic is dead except for its chain result.
9585   // Update uses of the chain.
9586   std::vector<SDValue> VLDDupResults;
9587   for (unsigned n = 0; n < NumVecs; ++n)
9588     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9589   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9590   DCI.CombineTo(VLD, VLDDupResults);
9591
9592   return true;
9593 }
9594
9595 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9596 /// ARMISD::VDUPLANE.
9597 static SDValue PerformVDUPLANECombine(SDNode *N,
9598                                       TargetLowering::DAGCombinerInfo &DCI) {
9599   SDValue Op = N->getOperand(0);
9600
9601   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9602   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9603   if (CombineVLDDUP(N, DCI))
9604     return SDValue(N, 0);
9605
9606   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9607   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9608   while (Op.getOpcode() == ISD::BITCAST)
9609     Op = Op.getOperand(0);
9610   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9611     return SDValue();
9612
9613   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9614   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9615   // The canonical VMOV for a zero vector uses a 32-bit element size.
9616   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9617   unsigned EltBits;
9618   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9619     EltSize = 8;
9620   EVT VT = N->getValueType(0);
9621   if (EltSize > VT.getVectorElementType().getSizeInBits())
9622     return SDValue();
9623
9624   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9625 }
9626
9627 static SDValue PerformLOADCombine(SDNode *N,
9628                                   TargetLowering::DAGCombinerInfo &DCI) {
9629   EVT VT = N->getValueType(0);
9630
9631   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9632   if (ISD::isNormalLoad(N) && VT.isVector() &&
9633       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9634     return CombineBaseUpdate(N, DCI);
9635
9636   return SDValue();
9637 }
9638
9639 /// PerformSTORECombine - Target-specific dag combine xforms for
9640 /// ISD::STORE.
9641 static SDValue PerformSTORECombine(SDNode *N,
9642                                    TargetLowering::DAGCombinerInfo &DCI) {
9643   StoreSDNode *St = cast<StoreSDNode>(N);
9644   if (St->isVolatile())
9645     return SDValue();
9646
9647   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9648   // pack all of the elements in one place.  Next, store to memory in fewer
9649   // chunks.
9650   SDValue StVal = St->getValue();
9651   EVT VT = StVal.getValueType();
9652   if (St->isTruncatingStore() && VT.isVector()) {
9653     SelectionDAG &DAG = DCI.DAG;
9654     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9655     EVT StVT = St->getMemoryVT();
9656     unsigned NumElems = VT.getVectorNumElements();
9657     assert(StVT != VT && "Cannot truncate to the same type");
9658     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9659     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9660
9661     // From, To sizes and ElemCount must be pow of two
9662     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9663
9664     // We are going to use the original vector elt for storing.
9665     // Accumulated smaller vector elements must be a multiple of the store size.
9666     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9667
9668     unsigned SizeRatio  = FromEltSz / ToEltSz;
9669     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9670
9671     // Create a type on which we perform the shuffle.
9672     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9673                                      NumElems*SizeRatio);
9674     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9675
9676     SDLoc DL(St);
9677     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9678     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9679     for (unsigned i = 0; i < NumElems; ++i)
9680       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9681                           ? (i + 1) * SizeRatio - 1
9682                           : i * SizeRatio;
9683
9684     // Can't shuffle using an illegal type.
9685     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9686
9687     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9688                                 DAG.getUNDEF(WideVec.getValueType()),
9689                                 ShuffleVec.data());
9690     // At this point all of the data is stored at the bottom of the
9691     // register. We now need to save it to mem.
9692
9693     // Find the largest store unit
9694     MVT StoreType = MVT::i8;
9695     for (MVT Tp : MVT::integer_valuetypes()) {
9696       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9697         StoreType = Tp;
9698     }
9699     // Didn't find a legal store type.
9700     if (!TLI.isTypeLegal(StoreType))
9701       return SDValue();
9702
9703     // Bitcast the original vector into a vector of store-size units
9704     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9705             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9706     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9707     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9708     SmallVector<SDValue, 8> Chains;
9709     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9710                                         TLI.getPointerTy(DAG.getDataLayout()));
9711     SDValue BasePtr = St->getBasePtr();
9712
9713     // Perform one or more big stores into memory.
9714     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9715     for (unsigned I = 0; I < E; I++) {
9716       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9717                                    StoreType, ShuffWide,
9718                                    DAG.getIntPtrConstant(I, DL));
9719       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9720                                 St->getPointerInfo(), St->isVolatile(),
9721                                 St->isNonTemporal(), St->getAlignment());
9722       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9723                             Increment);
9724       Chains.push_back(Ch);
9725     }
9726     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9727   }
9728
9729   if (!ISD::isNormalStore(St))
9730     return SDValue();
9731
9732   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9733   // ARM stores of arguments in the same cache line.
9734   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9735       StVal.getNode()->hasOneUse()) {
9736     SelectionDAG  &DAG = DCI.DAG;
9737     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9738     SDLoc DL(St);
9739     SDValue BasePtr = St->getBasePtr();
9740     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9741                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9742                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9743                                   St->isNonTemporal(), St->getAlignment());
9744
9745     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9746                                     DAG.getConstant(4, DL, MVT::i32));
9747     return DAG.getStore(NewST1.getValue(0), DL,
9748                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9749                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9750                         St->isNonTemporal(),
9751                         std::min(4U, St->getAlignment() / 2));
9752   }
9753
9754   if (StVal.getValueType() == MVT::i64 &&
9755       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9756
9757     // Bitcast an i64 store extracted from a vector to f64.
9758     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9759     SelectionDAG &DAG = DCI.DAG;
9760     SDLoc dl(StVal);
9761     SDValue IntVec = StVal.getOperand(0);
9762     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9763                                    IntVec.getValueType().getVectorNumElements());
9764     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9765     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9766                                  Vec, StVal.getOperand(1));
9767     dl = SDLoc(N);
9768     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9769     // Make the DAGCombiner fold the bitcasts.
9770     DCI.AddToWorklist(Vec.getNode());
9771     DCI.AddToWorklist(ExtElt.getNode());
9772     DCI.AddToWorklist(V.getNode());
9773     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9774                         St->getPointerInfo(), St->isVolatile(),
9775                         St->isNonTemporal(), St->getAlignment(),
9776                         St->getAAInfo());
9777   }
9778
9779   // If this is a legal vector store, try to combine it into a VST1_UPD.
9780   if (ISD::isNormalStore(N) && VT.isVector() &&
9781       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9782     return CombineBaseUpdate(N, DCI);
9783
9784   return SDValue();
9785 }
9786
9787 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9788 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9789 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9790 {
9791   integerPart cN;
9792   integerPart c0 = 0;
9793   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9794        I != E; I++) {
9795     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9796     if (!C)
9797       return false;
9798
9799     bool isExact;
9800     APFloat APF = C->getValueAPF();
9801     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9802         != APFloat::opOK || !isExact)
9803       return false;
9804
9805     c0 = (I == 0) ? cN : c0;
9806     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9807       return false;
9808   }
9809   C = c0;
9810   return true;
9811 }
9812
9813 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9814 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9815 /// when the VMUL has a constant operand that is a power of 2.
9816 ///
9817 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9818 ///  vmul.f32        d16, d17, d16
9819 ///  vcvt.s32.f32    d16, d16
9820 /// becomes:
9821 ///  vcvt.s32.f32    d16, d16, #3
9822 static SDValue PerformVCVTCombine(SDNode *N,
9823                                   TargetLowering::DAGCombinerInfo &DCI,
9824                                   const ARMSubtarget *Subtarget) {
9825   SelectionDAG &DAG = DCI.DAG;
9826   SDValue Op = N->getOperand(0);
9827
9828   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9829       Op.getOpcode() != ISD::FMUL)
9830     return SDValue();
9831
9832   uint64_t C;
9833   SDValue N0 = Op->getOperand(0);
9834   SDValue ConstVec = Op->getOperand(1);
9835   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9836
9837   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9838       !isConstVecPow2(ConstVec, isSigned, C))
9839     return SDValue();
9840
9841   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9842   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9843   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9844   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9845       NumLanes > 4) {
9846     // These instructions only exist converting from f32 to i32. We can handle
9847     // smaller integers by generating an extra truncate, but larger ones would
9848     // be lossy. We also can't handle more then 4 lanes, since these intructions
9849     // only support v2i32/v4i32 types.
9850     return SDValue();
9851   }
9852
9853   SDLoc dl(N);
9854   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9855     Intrinsic::arm_neon_vcvtfp2fxu;
9856   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9857                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9858                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9859                                  N0,
9860                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9861
9862   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9863     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9864
9865   return FixConv;
9866 }
9867
9868 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9869 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9870 /// when the VDIV has a constant operand that is a power of 2.
9871 ///
9872 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9873 ///  vcvt.f32.s32    d16, d16
9874 ///  vdiv.f32        d16, d17, d16
9875 /// becomes:
9876 ///  vcvt.f32.s32    d16, d16, #3
9877 static SDValue PerformVDIVCombine(SDNode *N,
9878                                   TargetLowering::DAGCombinerInfo &DCI,
9879                                   const ARMSubtarget *Subtarget) {
9880   SelectionDAG &DAG = DCI.DAG;
9881   SDValue Op = N->getOperand(0);
9882   unsigned OpOpcode = Op.getNode()->getOpcode();
9883
9884   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9885       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9886     return SDValue();
9887
9888   uint64_t C;
9889   SDValue ConstVec = N->getOperand(1);
9890   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9891
9892   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9893       !isConstVecPow2(ConstVec, isSigned, C))
9894     return SDValue();
9895
9896   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9897   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9898   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9899     // These instructions only exist converting from i32 to f32. We can handle
9900     // smaller integers by generating an extra extend, but larger ones would
9901     // be lossy.
9902     return SDValue();
9903   }
9904
9905   SDLoc dl(N);
9906   SDValue ConvInput = Op.getOperand(0);
9907   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9908   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9909     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9910                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9911                             ConvInput);
9912
9913   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9914     Intrinsic::arm_neon_vcvtfxu2fp;
9915   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9916                      Op.getValueType(),
9917                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9918                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9919 }
9920
9921 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9922 /// operand of a vector shift operation, where all the elements of the
9923 /// build_vector must have the same constant integer value.
9924 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9925   // Ignore bit_converts.
9926   while (Op.getOpcode() == ISD::BITCAST)
9927     Op = Op.getOperand(0);
9928   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9929   APInt SplatBits, SplatUndef;
9930   unsigned SplatBitSize;
9931   bool HasAnyUndefs;
9932   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9933                                       HasAnyUndefs, ElementBits) ||
9934       SplatBitSize > ElementBits)
9935     return false;
9936   Cnt = SplatBits.getSExtValue();
9937   return true;
9938 }
9939
9940 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9941 /// operand of a vector shift left operation.  That value must be in the range:
9942 ///   0 <= Value < ElementBits for a left shift; or
9943 ///   0 <= Value <= ElementBits for a long left shift.
9944 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9945   assert(VT.isVector() && "vector shift count is not a vector type");
9946   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9947   if (! getVShiftImm(Op, ElementBits, Cnt))
9948     return false;
9949   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9950 }
9951
9952 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9953 /// operand of a vector shift right operation.  For a shift opcode, the value
9954 /// is positive, but for an intrinsic the value count must be negative. The
9955 /// absolute value must be in the range:
9956 ///   1 <= |Value| <= ElementBits for a right shift; or
9957 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9958 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9959                          int64_t &Cnt) {
9960   assert(VT.isVector() && "vector shift count is not a vector type");
9961   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9962   if (! getVShiftImm(Op, ElementBits, Cnt))
9963     return false;
9964   if (!isIntrinsic)
9965     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9966   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9967     Cnt = -Cnt;
9968     return true;
9969   }
9970   return false;
9971 }
9972
9973 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9974 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9975   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9976   switch (IntNo) {
9977   default:
9978     // Don't do anything for most intrinsics.
9979     break;
9980
9981   case Intrinsic::arm_neon_vabds:
9982     if (!N->getValueType(0).isInteger())
9983       return SDValue();
9984     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9985                        N->getOperand(1), N->getOperand(2));
9986   case Intrinsic::arm_neon_vabdu:
9987     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9988                        N->getOperand(1), N->getOperand(2));
9989
9990   // Vector shifts: check for immediate versions and lower them.
9991   // Note: This is done during DAG combining instead of DAG legalizing because
9992   // the build_vectors for 64-bit vector element shift counts are generally
9993   // not legal, and it is hard to see their values after they get legalized to
9994   // loads from a constant pool.
9995   case Intrinsic::arm_neon_vshifts:
9996   case Intrinsic::arm_neon_vshiftu:
9997   case Intrinsic::arm_neon_vrshifts:
9998   case Intrinsic::arm_neon_vrshiftu:
9999   case Intrinsic::arm_neon_vrshiftn:
10000   case Intrinsic::arm_neon_vqshifts:
10001   case Intrinsic::arm_neon_vqshiftu:
10002   case Intrinsic::arm_neon_vqshiftsu:
10003   case Intrinsic::arm_neon_vqshiftns:
10004   case Intrinsic::arm_neon_vqshiftnu:
10005   case Intrinsic::arm_neon_vqshiftnsu:
10006   case Intrinsic::arm_neon_vqrshiftns:
10007   case Intrinsic::arm_neon_vqrshiftnu:
10008   case Intrinsic::arm_neon_vqrshiftnsu: {
10009     EVT VT = N->getOperand(1).getValueType();
10010     int64_t Cnt;
10011     unsigned VShiftOpc = 0;
10012
10013     switch (IntNo) {
10014     case Intrinsic::arm_neon_vshifts:
10015     case Intrinsic::arm_neon_vshiftu:
10016       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10017         VShiftOpc = ARMISD::VSHL;
10018         break;
10019       }
10020       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10021         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10022                      ARMISD::VSHRs : ARMISD::VSHRu);
10023         break;
10024       }
10025       return SDValue();
10026
10027     case Intrinsic::arm_neon_vrshifts:
10028     case Intrinsic::arm_neon_vrshiftu:
10029       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10030         break;
10031       return SDValue();
10032
10033     case Intrinsic::arm_neon_vqshifts:
10034     case Intrinsic::arm_neon_vqshiftu:
10035       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10036         break;
10037       return SDValue();
10038
10039     case Intrinsic::arm_neon_vqshiftsu:
10040       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10041         break;
10042       llvm_unreachable("invalid shift count for vqshlu intrinsic");
10043
10044     case Intrinsic::arm_neon_vrshiftn:
10045     case Intrinsic::arm_neon_vqshiftns:
10046     case Intrinsic::arm_neon_vqshiftnu:
10047     case Intrinsic::arm_neon_vqshiftnsu:
10048     case Intrinsic::arm_neon_vqrshiftns:
10049     case Intrinsic::arm_neon_vqrshiftnu:
10050     case Intrinsic::arm_neon_vqrshiftnsu:
10051       // Narrowing shifts require an immediate right shift.
10052       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10053         break;
10054       llvm_unreachable("invalid shift count for narrowing vector shift "
10055                        "intrinsic");
10056
10057     default:
10058       llvm_unreachable("unhandled vector shift");
10059     }
10060
10061     switch (IntNo) {
10062     case Intrinsic::arm_neon_vshifts:
10063     case Intrinsic::arm_neon_vshiftu:
10064       // Opcode already set above.
10065       break;
10066     case Intrinsic::arm_neon_vrshifts:
10067       VShiftOpc = ARMISD::VRSHRs; break;
10068     case Intrinsic::arm_neon_vrshiftu:
10069       VShiftOpc = ARMISD::VRSHRu; break;
10070     case Intrinsic::arm_neon_vrshiftn:
10071       VShiftOpc = ARMISD::VRSHRN; break;
10072     case Intrinsic::arm_neon_vqshifts:
10073       VShiftOpc = ARMISD::VQSHLs; break;
10074     case Intrinsic::arm_neon_vqshiftu:
10075       VShiftOpc = ARMISD::VQSHLu; break;
10076     case Intrinsic::arm_neon_vqshiftsu:
10077       VShiftOpc = ARMISD::VQSHLsu; break;
10078     case Intrinsic::arm_neon_vqshiftns:
10079       VShiftOpc = ARMISD::VQSHRNs; break;
10080     case Intrinsic::arm_neon_vqshiftnu:
10081       VShiftOpc = ARMISD::VQSHRNu; break;
10082     case Intrinsic::arm_neon_vqshiftnsu:
10083       VShiftOpc = ARMISD::VQSHRNsu; break;
10084     case Intrinsic::arm_neon_vqrshiftns:
10085       VShiftOpc = ARMISD::VQRSHRNs; break;
10086     case Intrinsic::arm_neon_vqrshiftnu:
10087       VShiftOpc = ARMISD::VQRSHRNu; break;
10088     case Intrinsic::arm_neon_vqrshiftnsu:
10089       VShiftOpc = ARMISD::VQRSHRNsu; break;
10090     }
10091
10092     SDLoc dl(N);
10093     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10094                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10095   }
10096
10097   case Intrinsic::arm_neon_vshiftins: {
10098     EVT VT = N->getOperand(1).getValueType();
10099     int64_t Cnt;
10100     unsigned VShiftOpc = 0;
10101
10102     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10103       VShiftOpc = ARMISD::VSLI;
10104     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10105       VShiftOpc = ARMISD::VSRI;
10106     else {
10107       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10108     }
10109
10110     SDLoc dl(N);
10111     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10112                        N->getOperand(1), N->getOperand(2),
10113                        DAG.getConstant(Cnt, dl, MVT::i32));
10114   }
10115
10116   case Intrinsic::arm_neon_vqrshifts:
10117   case Intrinsic::arm_neon_vqrshiftu:
10118     // No immediate versions of these to check for.
10119     break;
10120   }
10121
10122   return SDValue();
10123 }
10124
10125 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10126 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
10127 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10128 /// vector element shift counts are generally not legal, and it is hard to see
10129 /// their values after they get legalized to loads from a constant pool.
10130 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10131                                    const ARMSubtarget *ST) {
10132   EVT VT = N->getValueType(0);
10133   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10134     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10135     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10136     SDValue N1 = N->getOperand(1);
10137     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10138       SDValue N0 = N->getOperand(0);
10139       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10140           DAG.MaskedValueIsZero(N0.getOperand(0),
10141                                 APInt::getHighBitsSet(32, 16)))
10142         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10143     }
10144   }
10145
10146   // Nothing to be done for scalar shifts.
10147   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10148   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10149     return SDValue();
10150
10151   assert(ST->hasNEON() && "unexpected vector shift");
10152   int64_t Cnt;
10153
10154   switch (N->getOpcode()) {
10155   default: llvm_unreachable("unexpected shift opcode");
10156
10157   case ISD::SHL:
10158     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10159       SDLoc dl(N);
10160       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10161                          DAG.getConstant(Cnt, dl, MVT::i32));
10162     }
10163     break;
10164
10165   case ISD::SRA:
10166   case ISD::SRL:
10167     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10168       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10169                             ARMISD::VSHRs : ARMISD::VSHRu);
10170       SDLoc dl(N);
10171       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10172                          DAG.getConstant(Cnt, dl, MVT::i32));
10173     }
10174   }
10175   return SDValue();
10176 }
10177
10178 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10179 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10180 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10181                                     const ARMSubtarget *ST) {
10182   SDValue N0 = N->getOperand(0);
10183
10184   // Check for sign- and zero-extensions of vector extract operations of 8-
10185   // and 16-bit vector elements.  NEON supports these directly.  They are
10186   // handled during DAG combining because type legalization will promote them
10187   // to 32-bit types and it is messy to recognize the operations after that.
10188   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10189     SDValue Vec = N0.getOperand(0);
10190     SDValue Lane = N0.getOperand(1);
10191     EVT VT = N->getValueType(0);
10192     EVT EltVT = N0.getValueType();
10193     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10194
10195     if (VT == MVT::i32 &&
10196         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10197         TLI.isTypeLegal(Vec.getValueType()) &&
10198         isa<ConstantSDNode>(Lane)) {
10199
10200       unsigned Opc = 0;
10201       switch (N->getOpcode()) {
10202       default: llvm_unreachable("unexpected opcode");
10203       case ISD::SIGN_EXTEND:
10204         Opc = ARMISD::VGETLANEs;
10205         break;
10206       case ISD::ZERO_EXTEND:
10207       case ISD::ANY_EXTEND:
10208         Opc = ARMISD::VGETLANEu;
10209         break;
10210       }
10211       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10212     }
10213   }
10214
10215   return SDValue();
10216 }
10217
10218 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10219 SDValue
10220 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10221   SDValue Cmp = N->getOperand(4);
10222   if (Cmp.getOpcode() != ARMISD::CMPZ)
10223     // Only looking at EQ and NE cases.
10224     return SDValue();
10225
10226   EVT VT = N->getValueType(0);
10227   SDLoc dl(N);
10228   SDValue LHS = Cmp.getOperand(0);
10229   SDValue RHS = Cmp.getOperand(1);
10230   SDValue FalseVal = N->getOperand(0);
10231   SDValue TrueVal = N->getOperand(1);
10232   SDValue ARMcc = N->getOperand(2);
10233   ARMCC::CondCodes CC =
10234     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10235
10236   // Simplify
10237   //   mov     r1, r0
10238   //   cmp     r1, x
10239   //   mov     r0, y
10240   //   moveq   r0, x
10241   // to
10242   //   cmp     r0, x
10243   //   movne   r0, y
10244   //
10245   //   mov     r1, r0
10246   //   cmp     r1, x
10247   //   mov     r0, x
10248   //   movne   r0, y
10249   // to
10250   //   cmp     r0, x
10251   //   movne   r0, y
10252   /// FIXME: Turn this into a target neutral optimization?
10253   SDValue Res;
10254   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10255     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10256                       N->getOperand(3), Cmp);
10257   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10258     SDValue ARMcc;
10259     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10260     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10261                       N->getOperand(3), NewCmp);
10262   }
10263
10264   if (Res.getNode()) {
10265     APInt KnownZero, KnownOne;
10266     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10267     // Capture demanded bits information that would be otherwise lost.
10268     if (KnownZero == 0xfffffffe)
10269       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10270                         DAG.getValueType(MVT::i1));
10271     else if (KnownZero == 0xffffff00)
10272       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10273                         DAG.getValueType(MVT::i8));
10274     else if (KnownZero == 0xffff0000)
10275       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10276                         DAG.getValueType(MVT::i16));
10277   }
10278
10279   return Res;
10280 }
10281
10282 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10283                                              DAGCombinerInfo &DCI) const {
10284   switch (N->getOpcode()) {
10285   default: break;
10286   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10287   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10288   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10289   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10290   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10291   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10292   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10293   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10294   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10295   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10296   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10297   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10298   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10299   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10300   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10301   case ISD::FP_TO_SINT:
10302   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10303   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10304   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10305   case ISD::SHL:
10306   case ISD::SRA:
10307   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10308   case ISD::SIGN_EXTEND:
10309   case ISD::ZERO_EXTEND:
10310   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10311   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10312   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10313   case ARMISD::VLD2DUP:
10314   case ARMISD::VLD3DUP:
10315   case ARMISD::VLD4DUP:
10316     return PerformVLDCombine(N, DCI);
10317   case ARMISD::BUILD_VECTOR:
10318     return PerformARMBUILD_VECTORCombine(N, DCI);
10319   case ISD::INTRINSIC_VOID:
10320   case ISD::INTRINSIC_W_CHAIN:
10321     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10322     case Intrinsic::arm_neon_vld1:
10323     case Intrinsic::arm_neon_vld2:
10324     case Intrinsic::arm_neon_vld3:
10325     case Intrinsic::arm_neon_vld4:
10326     case Intrinsic::arm_neon_vld2lane:
10327     case Intrinsic::arm_neon_vld3lane:
10328     case Intrinsic::arm_neon_vld4lane:
10329     case Intrinsic::arm_neon_vst1:
10330     case Intrinsic::arm_neon_vst2:
10331     case Intrinsic::arm_neon_vst3:
10332     case Intrinsic::arm_neon_vst4:
10333     case Intrinsic::arm_neon_vst2lane:
10334     case Intrinsic::arm_neon_vst3lane:
10335     case Intrinsic::arm_neon_vst4lane:
10336       return PerformVLDCombine(N, DCI);
10337     default: break;
10338     }
10339     break;
10340   }
10341   return SDValue();
10342 }
10343
10344 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10345                                                           EVT VT) const {
10346   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10347 }
10348
10349 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10350                                                        unsigned,
10351                                                        unsigned,
10352                                                        bool *Fast) const {
10353   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10354   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10355
10356   switch (VT.getSimpleVT().SimpleTy) {
10357   default:
10358     return false;
10359   case MVT::i8:
10360   case MVT::i16:
10361   case MVT::i32: {
10362     // Unaligned access can use (for example) LRDB, LRDH, LDR
10363     if (AllowsUnaligned) {
10364       if (Fast)
10365         *Fast = Subtarget->hasV7Ops();
10366       return true;
10367     }
10368     return false;
10369   }
10370   case MVT::f64:
10371   case MVT::v2f64: {
10372     // For any little-endian targets with neon, we can support unaligned ld/st
10373     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10374     // A big-endian target may also explicitly support unaligned accesses
10375     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10376       if (Fast)
10377         *Fast = true;
10378       return true;
10379     }
10380     return false;
10381   }
10382   }
10383 }
10384
10385 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10386                        unsigned AlignCheck) {
10387   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10388           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10389 }
10390
10391 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10392                                            unsigned DstAlign, unsigned SrcAlign,
10393                                            bool IsMemset, bool ZeroMemset,
10394                                            bool MemcpyStrSrc,
10395                                            MachineFunction &MF) const {
10396   const Function *F = MF.getFunction();
10397
10398   // See if we can use NEON instructions for this...
10399   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10400       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10401     bool Fast;
10402     if (Size >= 16 &&
10403         (memOpAlign(SrcAlign, DstAlign, 16) ||
10404          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10405       return MVT::v2f64;
10406     } else if (Size >= 8 &&
10407                (memOpAlign(SrcAlign, DstAlign, 8) ||
10408                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10409                  Fast))) {
10410       return MVT::f64;
10411     }
10412   }
10413
10414   // Lowering to i32/i16 if the size permits.
10415   if (Size >= 4)
10416     return MVT::i32;
10417   else if (Size >= 2)
10418     return MVT::i16;
10419
10420   // Let the target-independent logic figure it out.
10421   return MVT::Other;
10422 }
10423
10424 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10425   if (Val.getOpcode() != ISD::LOAD)
10426     return false;
10427
10428   EVT VT1 = Val.getValueType();
10429   if (!VT1.isSimple() || !VT1.isInteger() ||
10430       !VT2.isSimple() || !VT2.isInteger())
10431     return false;
10432
10433   switch (VT1.getSimpleVT().SimpleTy) {
10434   default: break;
10435   case MVT::i1:
10436   case MVT::i8:
10437   case MVT::i16:
10438     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10439     return true;
10440   }
10441
10442   return false;
10443 }
10444
10445 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10446   EVT VT = ExtVal.getValueType();
10447
10448   if (!isTypeLegal(VT))
10449     return false;
10450
10451   // Don't create a loadext if we can fold the extension into a wide/long
10452   // instruction.
10453   // If there's more than one user instruction, the loadext is desirable no
10454   // matter what.  There can be two uses by the same instruction.
10455   if (ExtVal->use_empty() ||
10456       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10457     return true;
10458
10459   SDNode *U = *ExtVal->use_begin();
10460   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10461        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10462     return false;
10463
10464   return true;
10465 }
10466
10467 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10468   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10469     return false;
10470
10471   if (!isTypeLegal(EVT::getEVT(Ty1)))
10472     return false;
10473
10474   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10475
10476   // Assuming the caller doesn't have a zeroext or signext return parameter,
10477   // truncation all the way down to i1 is valid.
10478   return true;
10479 }
10480
10481
10482 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10483   if (V < 0)
10484     return false;
10485
10486   unsigned Scale = 1;
10487   switch (VT.getSimpleVT().SimpleTy) {
10488   default: return false;
10489   case MVT::i1:
10490   case MVT::i8:
10491     // Scale == 1;
10492     break;
10493   case MVT::i16:
10494     // Scale == 2;
10495     Scale = 2;
10496     break;
10497   case MVT::i32:
10498     // Scale == 4;
10499     Scale = 4;
10500     break;
10501   }
10502
10503   if ((V & (Scale - 1)) != 0)
10504     return false;
10505   V /= Scale;
10506   return V == (V & ((1LL << 5) - 1));
10507 }
10508
10509 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10510                                       const ARMSubtarget *Subtarget) {
10511   bool isNeg = false;
10512   if (V < 0) {
10513     isNeg = true;
10514     V = - V;
10515   }
10516
10517   switch (VT.getSimpleVT().SimpleTy) {
10518   default: return false;
10519   case MVT::i1:
10520   case MVT::i8:
10521   case MVT::i16:
10522   case MVT::i32:
10523     // + imm12 or - imm8
10524     if (isNeg)
10525       return V == (V & ((1LL << 8) - 1));
10526     return V == (V & ((1LL << 12) - 1));
10527   case MVT::f32:
10528   case MVT::f64:
10529     // Same as ARM mode. FIXME: NEON?
10530     if (!Subtarget->hasVFP2())
10531       return false;
10532     if ((V & 3) != 0)
10533       return false;
10534     V >>= 2;
10535     return V == (V & ((1LL << 8) - 1));
10536   }
10537 }
10538
10539 /// isLegalAddressImmediate - Return true if the integer value can be used
10540 /// as the offset of the target addressing mode for load / store of the
10541 /// given type.
10542 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10543                                     const ARMSubtarget *Subtarget) {
10544   if (V == 0)
10545     return true;
10546
10547   if (!VT.isSimple())
10548     return false;
10549
10550   if (Subtarget->isThumb1Only())
10551     return isLegalT1AddressImmediate(V, VT);
10552   else if (Subtarget->isThumb2())
10553     return isLegalT2AddressImmediate(V, VT, Subtarget);
10554
10555   // ARM mode.
10556   if (V < 0)
10557     V = - V;
10558   switch (VT.getSimpleVT().SimpleTy) {
10559   default: return false;
10560   case MVT::i1:
10561   case MVT::i8:
10562   case MVT::i32:
10563     // +- imm12
10564     return V == (V & ((1LL << 12) - 1));
10565   case MVT::i16:
10566     // +- imm8
10567     return V == (V & ((1LL << 8) - 1));
10568   case MVT::f32:
10569   case MVT::f64:
10570     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10571       return false;
10572     if ((V & 3) != 0)
10573       return false;
10574     V >>= 2;
10575     return V == (V & ((1LL << 8) - 1));
10576   }
10577 }
10578
10579 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10580                                                       EVT VT) const {
10581   int Scale = AM.Scale;
10582   if (Scale < 0)
10583     return false;
10584
10585   switch (VT.getSimpleVT().SimpleTy) {
10586   default: return false;
10587   case MVT::i1:
10588   case MVT::i8:
10589   case MVT::i16:
10590   case MVT::i32:
10591     if (Scale == 1)
10592       return true;
10593     // r + r << imm
10594     Scale = Scale & ~1;
10595     return Scale == 2 || Scale == 4 || Scale == 8;
10596   case MVT::i64:
10597     // r + r
10598     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10599       return true;
10600     return false;
10601   case MVT::isVoid:
10602     // Note, we allow "void" uses (basically, uses that aren't loads or
10603     // stores), because arm allows folding a scale into many arithmetic
10604     // operations.  This should be made more precise and revisited later.
10605
10606     // Allow r << imm, but the imm has to be a multiple of two.
10607     if (Scale & 1) return false;
10608     return isPowerOf2_32(Scale);
10609   }
10610 }
10611
10612 /// isLegalAddressingMode - Return true if the addressing mode represented
10613 /// by AM is legal for this target, for a load/store of the specified type.
10614 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10615                                               const AddrMode &AM, Type *Ty,
10616                                               unsigned AS) const {
10617   EVT VT = getValueType(DL, Ty, true);
10618   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10619     return false;
10620
10621   // Can never fold addr of global into load/store.
10622   if (AM.BaseGV)
10623     return false;
10624
10625   switch (AM.Scale) {
10626   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10627     break;
10628   case 1:
10629     if (Subtarget->isThumb1Only())
10630       return false;
10631     // FALL THROUGH.
10632   default:
10633     // ARM doesn't support any R+R*scale+imm addr modes.
10634     if (AM.BaseOffs)
10635       return false;
10636
10637     if (!VT.isSimple())
10638       return false;
10639
10640     if (Subtarget->isThumb2())
10641       return isLegalT2ScaledAddressingMode(AM, VT);
10642
10643     int Scale = AM.Scale;
10644     switch (VT.getSimpleVT().SimpleTy) {
10645     default: return false;
10646     case MVT::i1:
10647     case MVT::i8:
10648     case MVT::i32:
10649       if (Scale < 0) Scale = -Scale;
10650       if (Scale == 1)
10651         return true;
10652       // r + r << imm
10653       return isPowerOf2_32(Scale & ~1);
10654     case MVT::i16:
10655     case MVT::i64:
10656       // r + r
10657       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10658         return true;
10659       return false;
10660
10661     case MVT::isVoid:
10662       // Note, we allow "void" uses (basically, uses that aren't loads or
10663       // stores), because arm allows folding a scale into many arithmetic
10664       // operations.  This should be made more precise and revisited later.
10665
10666       // Allow r << imm, but the imm has to be a multiple of two.
10667       if (Scale & 1) return false;
10668       return isPowerOf2_32(Scale);
10669     }
10670   }
10671   return true;
10672 }
10673
10674 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10675 /// icmp immediate, that is the target has icmp instructions which can compare
10676 /// a register against the immediate without having to materialize the
10677 /// immediate into a register.
10678 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10679   // Thumb2 and ARM modes can use cmn for negative immediates.
10680   if (!Subtarget->isThumb())
10681     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10682   if (Subtarget->isThumb2())
10683     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10684   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10685   return Imm >= 0 && Imm <= 255;
10686 }
10687
10688 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10689 /// *or sub* immediate, that is the target has add or sub instructions which can
10690 /// add a register with the immediate without having to materialize the
10691 /// immediate into a register.
10692 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10693   // Same encoding for add/sub, just flip the sign.
10694   int64_t AbsImm = std::abs(Imm);
10695   if (!Subtarget->isThumb())
10696     return ARM_AM::getSOImmVal(AbsImm) != -1;
10697   if (Subtarget->isThumb2())
10698     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10699   // Thumb1 only has 8-bit unsigned immediate.
10700   return AbsImm >= 0 && AbsImm <= 255;
10701 }
10702
10703 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10704                                       bool isSEXTLoad, SDValue &Base,
10705                                       SDValue &Offset, bool &isInc,
10706                                       SelectionDAG &DAG) {
10707   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10708     return false;
10709
10710   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10711     // AddressingMode 3
10712     Base = Ptr->getOperand(0);
10713     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10714       int RHSC = (int)RHS->getZExtValue();
10715       if (RHSC < 0 && RHSC > -256) {
10716         assert(Ptr->getOpcode() == ISD::ADD);
10717         isInc = false;
10718         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10719         return true;
10720       }
10721     }
10722     isInc = (Ptr->getOpcode() == ISD::ADD);
10723     Offset = Ptr->getOperand(1);
10724     return true;
10725   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10726     // AddressingMode 2
10727     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10728       int RHSC = (int)RHS->getZExtValue();
10729       if (RHSC < 0 && RHSC > -0x1000) {
10730         assert(Ptr->getOpcode() == ISD::ADD);
10731         isInc = false;
10732         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10733         Base = Ptr->getOperand(0);
10734         return true;
10735       }
10736     }
10737
10738     if (Ptr->getOpcode() == ISD::ADD) {
10739       isInc = true;
10740       ARM_AM::ShiftOpc ShOpcVal=
10741         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10742       if (ShOpcVal != ARM_AM::no_shift) {
10743         Base = Ptr->getOperand(1);
10744         Offset = Ptr->getOperand(0);
10745       } else {
10746         Base = Ptr->getOperand(0);
10747         Offset = Ptr->getOperand(1);
10748       }
10749       return true;
10750     }
10751
10752     isInc = (Ptr->getOpcode() == ISD::ADD);
10753     Base = Ptr->getOperand(0);
10754     Offset = Ptr->getOperand(1);
10755     return true;
10756   }
10757
10758   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10759   return false;
10760 }
10761
10762 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10763                                      bool isSEXTLoad, SDValue &Base,
10764                                      SDValue &Offset, bool &isInc,
10765                                      SelectionDAG &DAG) {
10766   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10767     return false;
10768
10769   Base = Ptr->getOperand(0);
10770   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10771     int RHSC = (int)RHS->getZExtValue();
10772     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10773       assert(Ptr->getOpcode() == ISD::ADD);
10774       isInc = false;
10775       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10776       return true;
10777     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10778       isInc = Ptr->getOpcode() == ISD::ADD;
10779       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10780       return true;
10781     }
10782   }
10783
10784   return false;
10785 }
10786
10787 /// getPreIndexedAddressParts - returns true by value, base pointer and
10788 /// offset pointer and addressing mode by reference if the node's address
10789 /// can be legally represented as pre-indexed load / store address.
10790 bool
10791 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10792                                              SDValue &Offset,
10793                                              ISD::MemIndexedMode &AM,
10794                                              SelectionDAG &DAG) const {
10795   if (Subtarget->isThumb1Only())
10796     return false;
10797
10798   EVT VT;
10799   SDValue Ptr;
10800   bool isSEXTLoad = false;
10801   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10802     Ptr = LD->getBasePtr();
10803     VT  = LD->getMemoryVT();
10804     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10805   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10806     Ptr = ST->getBasePtr();
10807     VT  = ST->getMemoryVT();
10808   } else
10809     return false;
10810
10811   bool isInc;
10812   bool isLegal = false;
10813   if (Subtarget->isThumb2())
10814     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10815                                        Offset, isInc, DAG);
10816   else
10817     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10818                                         Offset, isInc, DAG);
10819   if (!isLegal)
10820     return false;
10821
10822   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10823   return true;
10824 }
10825
10826 /// getPostIndexedAddressParts - returns true by value, base pointer and
10827 /// offset pointer and addressing mode by reference if this node can be
10828 /// combined with a load / store to form a post-indexed load / store.
10829 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10830                                                    SDValue &Base,
10831                                                    SDValue &Offset,
10832                                                    ISD::MemIndexedMode &AM,
10833                                                    SelectionDAG &DAG) const {
10834   if (Subtarget->isThumb1Only())
10835     return false;
10836
10837   EVT VT;
10838   SDValue Ptr;
10839   bool isSEXTLoad = false;
10840   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10841     VT  = LD->getMemoryVT();
10842     Ptr = LD->getBasePtr();
10843     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10844   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10845     VT  = ST->getMemoryVT();
10846     Ptr = ST->getBasePtr();
10847   } else
10848     return false;
10849
10850   bool isInc;
10851   bool isLegal = false;
10852   if (Subtarget->isThumb2())
10853     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10854                                        isInc, DAG);
10855   else
10856     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10857                                         isInc, DAG);
10858   if (!isLegal)
10859     return false;
10860
10861   if (Ptr != Base) {
10862     // Swap base ptr and offset to catch more post-index load / store when
10863     // it's legal. In Thumb2 mode, offset must be an immediate.
10864     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10865         !Subtarget->isThumb2())
10866       std::swap(Base, Offset);
10867
10868     // Post-indexed load / store update the base pointer.
10869     if (Ptr != Base)
10870       return false;
10871   }
10872
10873   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10874   return true;
10875 }
10876
10877 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10878                                                       APInt &KnownZero,
10879                                                       APInt &KnownOne,
10880                                                       const SelectionDAG &DAG,
10881                                                       unsigned Depth) const {
10882   unsigned BitWidth = KnownOne.getBitWidth();
10883   KnownZero = KnownOne = APInt(BitWidth, 0);
10884   switch (Op.getOpcode()) {
10885   default: break;
10886   case ARMISD::ADDC:
10887   case ARMISD::ADDE:
10888   case ARMISD::SUBC:
10889   case ARMISD::SUBE:
10890     // These nodes' second result is a boolean
10891     if (Op.getResNo() == 0)
10892       break;
10893     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10894     break;
10895   case ARMISD::CMOV: {
10896     // Bits are known zero/one if known on the LHS and RHS.
10897     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10898     if (KnownZero == 0 && KnownOne == 0) return;
10899
10900     APInt KnownZeroRHS, KnownOneRHS;
10901     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10902     KnownZero &= KnownZeroRHS;
10903     KnownOne  &= KnownOneRHS;
10904     return;
10905   }
10906   case ISD::INTRINSIC_W_CHAIN: {
10907     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10908     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10909     switch (IntID) {
10910     default: return;
10911     case Intrinsic::arm_ldaex:
10912     case Intrinsic::arm_ldrex: {
10913       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10914       unsigned MemBits = VT.getScalarType().getSizeInBits();
10915       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10916       return;
10917     }
10918     }
10919   }
10920   }
10921 }
10922
10923 //===----------------------------------------------------------------------===//
10924 //                           ARM Inline Assembly Support
10925 //===----------------------------------------------------------------------===//
10926
10927 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10928   // Looking for "rev" which is V6+.
10929   if (!Subtarget->hasV6Ops())
10930     return false;
10931
10932   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10933   std::string AsmStr = IA->getAsmString();
10934   SmallVector<StringRef, 4> AsmPieces;
10935   SplitString(AsmStr, AsmPieces, ";\n");
10936
10937   switch (AsmPieces.size()) {
10938   default: return false;
10939   case 1:
10940     AsmStr = AsmPieces[0];
10941     AsmPieces.clear();
10942     SplitString(AsmStr, AsmPieces, " \t,");
10943
10944     // rev $0, $1
10945     if (AsmPieces.size() == 3 &&
10946         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10947         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10948       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10949       if (Ty && Ty->getBitWidth() == 32)
10950         return IntrinsicLowering::LowerToByteSwap(CI);
10951     }
10952     break;
10953   }
10954
10955   return false;
10956 }
10957
10958 /// getConstraintType - Given a constraint letter, return the type of
10959 /// constraint it is for this target.
10960 ARMTargetLowering::ConstraintType
10961 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10962   if (Constraint.size() == 1) {
10963     switch (Constraint[0]) {
10964     default:  break;
10965     case 'l': return C_RegisterClass;
10966     case 'w': return C_RegisterClass;
10967     case 'h': return C_RegisterClass;
10968     case 'x': return C_RegisterClass;
10969     case 't': return C_RegisterClass;
10970     case 'j': return C_Other; // Constant for movw.
10971       // An address with a single base register. Due to the way we
10972       // currently handle addresses it is the same as an 'r' memory constraint.
10973     case 'Q': return C_Memory;
10974     }
10975   } else if (Constraint.size() == 2) {
10976     switch (Constraint[0]) {
10977     default: break;
10978     // All 'U+' constraints are addresses.
10979     case 'U': return C_Memory;
10980     }
10981   }
10982   return TargetLowering::getConstraintType(Constraint);
10983 }
10984
10985 /// Examine constraint type and operand type and determine a weight value.
10986 /// This object must already have been set up with the operand type
10987 /// and the current alternative constraint selected.
10988 TargetLowering::ConstraintWeight
10989 ARMTargetLowering::getSingleConstraintMatchWeight(
10990     AsmOperandInfo &info, const char *constraint) const {
10991   ConstraintWeight weight = CW_Invalid;
10992   Value *CallOperandVal = info.CallOperandVal;
10993     // If we don't have a value, we can't do a match,
10994     // but allow it at the lowest weight.
10995   if (!CallOperandVal)
10996     return CW_Default;
10997   Type *type = CallOperandVal->getType();
10998   // Look at the constraint type.
10999   switch (*constraint) {
11000   default:
11001     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11002     break;
11003   case 'l':
11004     if (type->isIntegerTy()) {
11005       if (Subtarget->isThumb())
11006         weight = CW_SpecificReg;
11007       else
11008         weight = CW_Register;
11009     }
11010     break;
11011   case 'w':
11012     if (type->isFloatingPointTy())
11013       weight = CW_Register;
11014     break;
11015   }
11016   return weight;
11017 }
11018
11019 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11020 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11021     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11022   if (Constraint.size() == 1) {
11023     // GCC ARM Constraint Letters
11024     switch (Constraint[0]) {
11025     case 'l': // Low regs or general regs.
11026       if (Subtarget->isThumb())
11027         return RCPair(0U, &ARM::tGPRRegClass);
11028       return RCPair(0U, &ARM::GPRRegClass);
11029     case 'h': // High regs or no regs.
11030       if (Subtarget->isThumb())
11031         return RCPair(0U, &ARM::hGPRRegClass);
11032       break;
11033     case 'r':
11034       if (Subtarget->isThumb1Only())
11035         return RCPair(0U, &ARM::tGPRRegClass);
11036       return RCPair(0U, &ARM::GPRRegClass);
11037     case 'w':
11038       if (VT == MVT::Other)
11039         break;
11040       if (VT == MVT::f32)
11041         return RCPair(0U, &ARM::SPRRegClass);
11042       if (VT.getSizeInBits() == 64)
11043         return RCPair(0U, &ARM::DPRRegClass);
11044       if (VT.getSizeInBits() == 128)
11045         return RCPair(0U, &ARM::QPRRegClass);
11046       break;
11047     case 'x':
11048       if (VT == MVT::Other)
11049         break;
11050       if (VT == MVT::f32)
11051         return RCPair(0U, &ARM::SPR_8RegClass);
11052       if (VT.getSizeInBits() == 64)
11053         return RCPair(0U, &ARM::DPR_8RegClass);
11054       if (VT.getSizeInBits() == 128)
11055         return RCPair(0U, &ARM::QPR_8RegClass);
11056       break;
11057     case 't':
11058       if (VT == MVT::f32)
11059         return RCPair(0U, &ARM::SPRRegClass);
11060       break;
11061     }
11062   }
11063   if (StringRef("{cc}").equals_lower(Constraint))
11064     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11065
11066   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11067 }
11068
11069 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11070 /// vector.  If it is invalid, don't add anything to Ops.
11071 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11072                                                      std::string &Constraint,
11073                                                      std::vector<SDValue>&Ops,
11074                                                      SelectionDAG &DAG) const {
11075   SDValue Result;
11076
11077   // Currently only support length 1 constraints.
11078   if (Constraint.length() != 1) return;
11079
11080   char ConstraintLetter = Constraint[0];
11081   switch (ConstraintLetter) {
11082   default: break;
11083   case 'j':
11084   case 'I': case 'J': case 'K': case 'L':
11085   case 'M': case 'N': case 'O':
11086     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11087     if (!C)
11088       return;
11089
11090     int64_t CVal64 = C->getSExtValue();
11091     int CVal = (int) CVal64;
11092     // None of these constraints allow values larger than 32 bits.  Check
11093     // that the value fits in an int.
11094     if (CVal != CVal64)
11095       return;
11096
11097     switch (ConstraintLetter) {
11098       case 'j':
11099         // Constant suitable for movw, must be between 0 and
11100         // 65535.
11101         if (Subtarget->hasV6T2Ops())
11102           if (CVal >= 0 && CVal <= 65535)
11103             break;
11104         return;
11105       case 'I':
11106         if (Subtarget->isThumb1Only()) {
11107           // This must be a constant between 0 and 255, for ADD
11108           // immediates.
11109           if (CVal >= 0 && CVal <= 255)
11110             break;
11111         } else if (Subtarget->isThumb2()) {
11112           // A constant that can be used as an immediate value in a
11113           // data-processing instruction.
11114           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11115             break;
11116         } else {
11117           // A constant that can be used as an immediate value in a
11118           // data-processing instruction.
11119           if (ARM_AM::getSOImmVal(CVal) != -1)
11120             break;
11121         }
11122         return;
11123
11124       case 'J':
11125         if (Subtarget->isThumb()) {  // FIXME thumb2
11126           // This must be a constant between -255 and -1, for negated ADD
11127           // immediates. This can be used in GCC with an "n" modifier that
11128           // prints the negated value, for use with SUB instructions. It is
11129           // not useful otherwise but is implemented for compatibility.
11130           if (CVal >= -255 && CVal <= -1)
11131             break;
11132         } else {
11133           // This must be a constant between -4095 and 4095. It is not clear
11134           // what this constraint is intended for. Implemented for
11135           // compatibility with GCC.
11136           if (CVal >= -4095 && CVal <= 4095)
11137             break;
11138         }
11139         return;
11140
11141       case 'K':
11142         if (Subtarget->isThumb1Only()) {
11143           // A 32-bit value where only one byte has a nonzero value. Exclude
11144           // zero to match GCC. This constraint is used by GCC internally for
11145           // constants that can be loaded with a move/shift combination.
11146           // It is not useful otherwise but is implemented for compatibility.
11147           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11148             break;
11149         } else if (Subtarget->isThumb2()) {
11150           // A constant whose bitwise inverse can be used as an immediate
11151           // value in a data-processing instruction. This can be used in GCC
11152           // with a "B" modifier that prints the inverted value, for use with
11153           // BIC and MVN instructions. It is not useful otherwise but is
11154           // implemented for compatibility.
11155           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11156             break;
11157         } else {
11158           // A constant whose bitwise inverse can be used as an immediate
11159           // value in a data-processing instruction. This can be used in GCC
11160           // with a "B" modifier that prints the inverted value, for use with
11161           // BIC and MVN instructions. It is not useful otherwise but is
11162           // implemented for compatibility.
11163           if (ARM_AM::getSOImmVal(~CVal) != -1)
11164             break;
11165         }
11166         return;
11167
11168       case 'L':
11169         if (Subtarget->isThumb1Only()) {
11170           // This must be a constant between -7 and 7,
11171           // for 3-operand ADD/SUB immediate instructions.
11172           if (CVal >= -7 && CVal < 7)
11173             break;
11174         } else if (Subtarget->isThumb2()) {
11175           // A constant whose negation can be used as an immediate value in a
11176           // data-processing instruction. This can be used in GCC with an "n"
11177           // modifier that prints the negated value, for use with SUB
11178           // instructions. It is not useful otherwise but is implemented for
11179           // compatibility.
11180           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11181             break;
11182         } else {
11183           // A constant whose negation can be used as an immediate value in a
11184           // data-processing instruction. This can be used in GCC with an "n"
11185           // modifier that prints the negated value, for use with SUB
11186           // instructions. It is not useful otherwise but is implemented for
11187           // compatibility.
11188           if (ARM_AM::getSOImmVal(-CVal) != -1)
11189             break;
11190         }
11191         return;
11192
11193       case 'M':
11194         if (Subtarget->isThumb()) { // FIXME thumb2
11195           // This must be a multiple of 4 between 0 and 1020, for
11196           // ADD sp + immediate.
11197           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11198             break;
11199         } else {
11200           // A power of two or a constant between 0 and 32.  This is used in
11201           // GCC for the shift amount on shifted register operands, but it is
11202           // useful in general for any shift amounts.
11203           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11204             break;
11205         }
11206         return;
11207
11208       case 'N':
11209         if (Subtarget->isThumb()) {  // FIXME thumb2
11210           // This must be a constant between 0 and 31, for shift amounts.
11211           if (CVal >= 0 && CVal <= 31)
11212             break;
11213         }
11214         return;
11215
11216       case 'O':
11217         if (Subtarget->isThumb()) {  // FIXME thumb2
11218           // This must be a multiple of 4 between -508 and 508, for
11219           // ADD/SUB sp = sp + immediate.
11220           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11221             break;
11222         }
11223         return;
11224     }
11225     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11226     break;
11227   }
11228
11229   if (Result.getNode()) {
11230     Ops.push_back(Result);
11231     return;
11232   }
11233   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11234 }
11235
11236 static RTLIB::Libcall getDivRemLibcall(
11237     const SDNode *N, MVT::SimpleValueType SVT) {
11238   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11239           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11240          "Unhandled Opcode in getDivRemLibcall");
11241   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11242                   N->getOpcode() == ISD::SREM;
11243   RTLIB::Libcall LC;
11244   switch (SVT) {
11245   default: llvm_unreachable("Unexpected request for libcall!");
11246   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11247   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11248   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11249   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11250   }
11251   return LC;
11252 }
11253
11254 static TargetLowering::ArgListTy getDivRemArgList(
11255     const SDNode *N, LLVMContext *Context) {
11256   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11257           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11258          "Unhandled Opcode in getDivRemArgList");
11259   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11260                   N->getOpcode() == ISD::SREM;
11261   TargetLowering::ArgListTy Args;
11262   TargetLowering::ArgListEntry Entry;
11263   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11264     EVT ArgVT = N->getOperand(i).getValueType();
11265     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11266     Entry.Node = N->getOperand(i);
11267     Entry.Ty = ArgTy;
11268     Entry.isSExt = isSigned;
11269     Entry.isZExt = !isSigned;
11270     Args.push_back(Entry);
11271   }
11272   return Args;
11273 }
11274
11275 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11276   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11277          "Register-based DivRem lowering only");
11278   unsigned Opcode = Op->getOpcode();
11279   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11280          "Invalid opcode for Div/Rem lowering");
11281   bool isSigned = (Opcode == ISD::SDIVREM);
11282   EVT VT = Op->getValueType(0);
11283   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11284
11285   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11286                                        VT.getSimpleVT().SimpleTy);
11287   SDValue InChain = DAG.getEntryNode();
11288
11289   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11290                                                     DAG.getContext());
11291
11292   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11293                                          getPointerTy(DAG.getDataLayout()));
11294
11295   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11296
11297   SDLoc dl(Op);
11298   TargetLowering::CallLoweringInfo CLI(DAG);
11299   CLI.setDebugLoc(dl).setChain(InChain)
11300     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11301     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11302
11303   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11304   return CallInfo.first;
11305 }
11306
11307 // Lowers REM using divmod helpers
11308 // see RTABI section 4.2/4.3
11309 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11310   // Build return types (div and rem)
11311   std::vector<Type*> RetTyParams;
11312   Type *RetTyElement;
11313
11314   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11315   default: llvm_unreachable("Unexpected request for libcall!");
11316   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
11317   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11318   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11319   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11320   }
11321
11322   RetTyParams.push_back(RetTyElement);
11323   RetTyParams.push_back(RetTyElement);
11324   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11325   Type *RetTy = StructType::get(*DAG.getContext(), ret);
11326
11327   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11328                                                              SimpleTy);
11329   SDValue InChain = DAG.getEntryNode();
11330   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11331   bool isSigned = N->getOpcode() == ISD::SREM;
11332   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11333                                          getPointerTy(DAG.getDataLayout()));
11334
11335   // Lower call
11336   CallLoweringInfo CLI(DAG);
11337   CLI.setChain(InChain)
11338      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11339      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11340   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11341
11342   // Return second (rem) result operand (first contains div)
11343   SDNode *ResNode = CallResult.first.getNode();
11344   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11345   return ResNode->getOperand(1);
11346 }
11347
11348 SDValue
11349 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11350   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11351   SDLoc DL(Op);
11352
11353   // Get the inputs.
11354   SDValue Chain = Op.getOperand(0);
11355   SDValue Size  = Op.getOperand(1);
11356
11357   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11358                               DAG.getConstant(2, DL, MVT::i32));
11359
11360   SDValue Flag;
11361   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11362   Flag = Chain.getValue(1);
11363
11364   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11365   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11366
11367   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11368   Chain = NewSP.getValue(1);
11369
11370   SDValue Ops[2] = { NewSP, Chain };
11371   return DAG.getMergeValues(Ops, DL);
11372 }
11373
11374 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11375   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11376          "Unexpected type for custom-lowering FP_EXTEND");
11377
11378   RTLIB::Libcall LC;
11379   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11380
11381   SDValue SrcVal = Op.getOperand(0);
11382   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11383                      /*isSigned*/ false, SDLoc(Op)).first;
11384 }
11385
11386 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11387   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11388          Subtarget->isFPOnlySP() &&
11389          "Unexpected type for custom-lowering FP_ROUND");
11390
11391   RTLIB::Libcall LC;
11392   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11393
11394   SDValue SrcVal = Op.getOperand(0);
11395   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11396                      /*isSigned*/ false, SDLoc(Op)).first;
11397 }
11398
11399 bool
11400 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11401   // The ARM target isn't yet aware of offsets.
11402   return false;
11403 }
11404
11405 bool ARM::isBitFieldInvertedMask(unsigned v) {
11406   if (v == 0xffffffff)
11407     return false;
11408
11409   // there can be 1's on either or both "outsides", all the "inside"
11410   // bits must be 0's
11411   return isShiftedMask_32(~v);
11412 }
11413
11414 /// isFPImmLegal - Returns true if the target can instruction select the
11415 /// specified FP immediate natively. If false, the legalizer will
11416 /// materialize the FP immediate as a load from a constant pool.
11417 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11418   if (!Subtarget->hasVFP3())
11419     return false;
11420   if (VT == MVT::f32)
11421     return ARM_AM::getFP32Imm(Imm) != -1;
11422   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11423     return ARM_AM::getFP64Imm(Imm) != -1;
11424   return false;
11425 }
11426
11427 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11428 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11429 /// specified in the intrinsic calls.
11430 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11431                                            const CallInst &I,
11432                                            unsigned Intrinsic) const {
11433   switch (Intrinsic) {
11434   case Intrinsic::arm_neon_vld1:
11435   case Intrinsic::arm_neon_vld2:
11436   case Intrinsic::arm_neon_vld3:
11437   case Intrinsic::arm_neon_vld4:
11438   case Intrinsic::arm_neon_vld2lane:
11439   case Intrinsic::arm_neon_vld3lane:
11440   case Intrinsic::arm_neon_vld4lane: {
11441     Info.opc = ISD::INTRINSIC_W_CHAIN;
11442     // Conservatively set memVT to the entire set of vectors loaded.
11443     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11444     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11445     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11446     Info.ptrVal = I.getArgOperand(0);
11447     Info.offset = 0;
11448     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11449     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11450     Info.vol = false; // volatile loads with NEON intrinsics not supported
11451     Info.readMem = true;
11452     Info.writeMem = false;
11453     return true;
11454   }
11455   case Intrinsic::arm_neon_vst1:
11456   case Intrinsic::arm_neon_vst2:
11457   case Intrinsic::arm_neon_vst3:
11458   case Intrinsic::arm_neon_vst4:
11459   case Intrinsic::arm_neon_vst2lane:
11460   case Intrinsic::arm_neon_vst3lane:
11461   case Intrinsic::arm_neon_vst4lane: {
11462     Info.opc = ISD::INTRINSIC_VOID;
11463     // Conservatively set memVT to the entire set of vectors stored.
11464     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11465     unsigned NumElts = 0;
11466     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11467       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11468       if (!ArgTy->isVectorTy())
11469         break;
11470       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11471     }
11472     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11473     Info.ptrVal = I.getArgOperand(0);
11474     Info.offset = 0;
11475     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11476     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11477     Info.vol = false; // volatile stores with NEON intrinsics not supported
11478     Info.readMem = false;
11479     Info.writeMem = true;
11480     return true;
11481   }
11482   case Intrinsic::arm_ldaex:
11483   case Intrinsic::arm_ldrex: {
11484     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11485     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11486     Info.opc = ISD::INTRINSIC_W_CHAIN;
11487     Info.memVT = MVT::getVT(PtrTy->getElementType());
11488     Info.ptrVal = I.getArgOperand(0);
11489     Info.offset = 0;
11490     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11491     Info.vol = true;
11492     Info.readMem = true;
11493     Info.writeMem = false;
11494     return true;
11495   }
11496   case Intrinsic::arm_stlex:
11497   case Intrinsic::arm_strex: {
11498     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11499     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11500     Info.opc = ISD::INTRINSIC_W_CHAIN;
11501     Info.memVT = MVT::getVT(PtrTy->getElementType());
11502     Info.ptrVal = I.getArgOperand(1);
11503     Info.offset = 0;
11504     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11505     Info.vol = true;
11506     Info.readMem = false;
11507     Info.writeMem = true;
11508     return true;
11509   }
11510   case Intrinsic::arm_stlexd:
11511   case Intrinsic::arm_strexd: {
11512     Info.opc = ISD::INTRINSIC_W_CHAIN;
11513     Info.memVT = MVT::i64;
11514     Info.ptrVal = I.getArgOperand(2);
11515     Info.offset = 0;
11516     Info.align = 8;
11517     Info.vol = true;
11518     Info.readMem = false;
11519     Info.writeMem = true;
11520     return true;
11521   }
11522   case Intrinsic::arm_ldaexd:
11523   case Intrinsic::arm_ldrexd: {
11524     Info.opc = ISD::INTRINSIC_W_CHAIN;
11525     Info.memVT = MVT::i64;
11526     Info.ptrVal = I.getArgOperand(0);
11527     Info.offset = 0;
11528     Info.align = 8;
11529     Info.vol = true;
11530     Info.readMem = true;
11531     Info.writeMem = false;
11532     return true;
11533   }
11534   default:
11535     break;
11536   }
11537
11538   return false;
11539 }
11540
11541 /// \brief Returns true if it is beneficial to convert a load of a constant
11542 /// to just the constant itself.
11543 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11544                                                           Type *Ty) const {
11545   assert(Ty->isIntegerTy());
11546
11547   unsigned Bits = Ty->getPrimitiveSizeInBits();
11548   if (Bits == 0 || Bits > 32)
11549     return false;
11550   return true;
11551 }
11552
11553 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11554                                         ARM_MB::MemBOpt Domain) const {
11555   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11556
11557   // First, if the target has no DMB, see what fallback we can use.
11558   if (!Subtarget->hasDataBarrier()) {
11559     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11560     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11561     // here.
11562     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11563       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11564       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11565                         Builder.getInt32(0), Builder.getInt32(7),
11566                         Builder.getInt32(10), Builder.getInt32(5)};
11567       return Builder.CreateCall(MCR, args);
11568     } else {
11569       // Instead of using barriers, atomic accesses on these subtargets use
11570       // libcalls.
11571       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11572     }
11573   } else {
11574     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11575     // Only a full system barrier exists in the M-class architectures.
11576     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11577     Constant *CDomain = Builder.getInt32(Domain);
11578     return Builder.CreateCall(DMB, CDomain);
11579   }
11580 }
11581
11582 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11583 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11584                                          AtomicOrdering Ord, bool IsStore,
11585                                          bool IsLoad) const {
11586   if (!getInsertFencesForAtomic())
11587     return nullptr;
11588
11589   switch (Ord) {
11590   case NotAtomic:
11591   case Unordered:
11592     llvm_unreachable("Invalid fence: unordered/non-atomic");
11593   case Monotonic:
11594   case Acquire:
11595     return nullptr; // Nothing to do
11596   case SequentiallyConsistent:
11597     if (!IsStore)
11598       return nullptr; // Nothing to do
11599     /*FALLTHROUGH*/
11600   case Release:
11601   case AcquireRelease:
11602     if (Subtarget->isSwift())
11603       return makeDMB(Builder, ARM_MB::ISHST);
11604     // FIXME: add a comment with a link to documentation justifying this.
11605     else
11606       return makeDMB(Builder, ARM_MB::ISH);
11607   }
11608   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11609 }
11610
11611 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11612                                           AtomicOrdering Ord, bool IsStore,
11613                                           bool IsLoad) const {
11614   if (!getInsertFencesForAtomic())
11615     return nullptr;
11616
11617   switch (Ord) {
11618   case NotAtomic:
11619   case Unordered:
11620     llvm_unreachable("Invalid fence: unordered/not-atomic");
11621   case Monotonic:
11622   case Release:
11623     return nullptr; // Nothing to do
11624   case Acquire:
11625   case AcquireRelease:
11626   case SequentiallyConsistent:
11627     return makeDMB(Builder, ARM_MB::ISH);
11628   }
11629   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11630 }
11631
11632 // Loads and stores less than 64-bits are already atomic; ones above that
11633 // are doomed anyway, so defer to the default libcall and blame the OS when
11634 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11635 // anything for those.
11636 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11637   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11638   return (Size == 64) && !Subtarget->isMClass();
11639 }
11640
11641 // Loads and stores less than 64-bits are already atomic; ones above that
11642 // are doomed anyway, so defer to the default libcall and blame the OS when
11643 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11644 // anything for those.
11645 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11646 // guarantee, see DDI0406C ARM architecture reference manual,
11647 // sections A8.8.72-74 LDRD)
11648 TargetLowering::AtomicExpansionKind
11649 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11650   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11651   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLSC
11652                                                   : AtomicExpansionKind::None;
11653 }
11654
11655 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11656 // and up to 64 bits on the non-M profiles
11657 TargetLowering::AtomicExpansionKind
11658 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11659   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11660   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11661              ? AtomicExpansionKind::LLSC
11662              : AtomicExpansionKind::None;
11663 }
11664
11665 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
11666     AtomicCmpXchgInst *AI) const {
11667   return true;
11668 }
11669
11670 // This has so far only been implemented for MachO.
11671 bool ARMTargetLowering::useLoadStackGuardNode() const {
11672   return Subtarget->isTargetMachO();
11673 }
11674
11675 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11676                                                   unsigned &Cost) const {
11677   // If we do not have NEON, vector types are not natively supported.
11678   if (!Subtarget->hasNEON())
11679     return false;
11680
11681   // Floating point values and vector values map to the same register file.
11682   // Therefore, although we could do a store extract of a vector type, this is
11683   // better to leave at float as we have more freedom in the addressing mode for
11684   // those.
11685   if (VectorTy->isFPOrFPVectorTy())
11686     return false;
11687
11688   // If the index is unknown at compile time, this is very expensive to lower
11689   // and it is not possible to combine the store with the extract.
11690   if (!isa<ConstantInt>(Idx))
11691     return false;
11692
11693   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11694   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11695   // We can do a store + vector extract on any vector that fits perfectly in a D
11696   // or Q register.
11697   if (BitWidth == 64 || BitWidth == 128) {
11698     Cost = 0;
11699     return true;
11700   }
11701   return false;
11702 }
11703
11704 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11705                                          AtomicOrdering Ord) const {
11706   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11707   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11708   bool IsAcquire = isAtLeastAcquire(Ord);
11709
11710   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11711   // intrinsic must return {i32, i32} and we have to recombine them into a
11712   // single i64 here.
11713   if (ValTy->getPrimitiveSizeInBits() == 64) {
11714     Intrinsic::ID Int =
11715         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11716     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11717
11718     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11719     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11720
11721     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11722     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11723     if (!Subtarget->isLittle())
11724       std::swap (Lo, Hi);
11725     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11726     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11727     return Builder.CreateOr(
11728         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11729   }
11730
11731   Type *Tys[] = { Addr->getType() };
11732   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11733   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11734
11735   return Builder.CreateTruncOrBitCast(
11736       Builder.CreateCall(Ldrex, Addr),
11737       cast<PointerType>(Addr->getType())->getElementType());
11738 }
11739
11740 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11741     IRBuilder<> &Builder) const {
11742   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11743   Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
11744 }
11745
11746 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11747                                                Value *Addr,
11748                                                AtomicOrdering Ord) const {
11749   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11750   bool IsRelease = isAtLeastRelease(Ord);
11751
11752   // Since the intrinsics must have legal type, the i64 intrinsics take two
11753   // parameters: "i32, i32". We must marshal Val into the appropriate form
11754   // before the call.
11755   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11756     Intrinsic::ID Int =
11757         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11758     Function *Strex = Intrinsic::getDeclaration(M, Int);
11759     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11760
11761     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11762     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11763     if (!Subtarget->isLittle())
11764       std::swap (Lo, Hi);
11765     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11766     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11767   }
11768
11769   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11770   Type *Tys[] = { Addr->getType() };
11771   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11772
11773   return Builder.CreateCall(
11774       Strex, {Builder.CreateZExtOrBitCast(
11775                   Val, Strex->getFunctionType()->getParamType(0)),
11776               Addr});
11777 }
11778
11779 /// \brief Lower an interleaved load into a vldN intrinsic.
11780 ///
11781 /// E.g. Lower an interleaved load (Factor = 2):
11782 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11783 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11784 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11785 ///
11786 ///      Into:
11787 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11788 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11789 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11790 bool ARMTargetLowering::lowerInterleavedLoad(
11791     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11792     ArrayRef<unsigned> Indices, unsigned Factor) const {
11793   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11794          "Invalid interleave factor");
11795   assert(!Shuffles.empty() && "Empty shufflevector input");
11796   assert(Shuffles.size() == Indices.size() &&
11797          "Unmatched number of shufflevectors and indices");
11798
11799   VectorType *VecTy = Shuffles[0]->getType();
11800   Type *EltTy = VecTy->getVectorElementType();
11801
11802   const DataLayout &DL = LI->getModule()->getDataLayout();
11803   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11804   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11805
11806   // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11807   // support i64/f64 element).
11808   if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11809     return false;
11810
11811   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11812   // load integer vectors first and then convert to pointer vectors.
11813   if (EltTy->isPointerTy())
11814     VecTy =
11815         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11816
11817   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11818                                             Intrinsic::arm_neon_vld3,
11819                                             Intrinsic::arm_neon_vld4};
11820
11821   Function *VldnFunc =
11822       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11823
11824   IRBuilder<> Builder(LI);
11825   SmallVector<Value *, 2> Ops;
11826
11827   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11828   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11829   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11830
11831   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11832
11833   // Replace uses of each shufflevector with the corresponding vector loaded
11834   // by ldN.
11835   for (unsigned i = 0; i < Shuffles.size(); i++) {
11836     ShuffleVectorInst *SV = Shuffles[i];
11837     unsigned Index = Indices[i];
11838
11839     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11840
11841     // Convert the integer vector to pointer vector if the element is pointer.
11842     if (EltTy->isPointerTy())
11843       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11844
11845     SV->replaceAllUsesWith(SubVec);
11846   }
11847
11848   return true;
11849 }
11850
11851 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11852 ///
11853 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11854 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11855                                    unsigned NumElts) {
11856   SmallVector<Constant *, 16> Mask;
11857   for (unsigned i = 0; i < NumElts; i++)
11858     Mask.push_back(Builder.getInt32(Start + i));
11859
11860   return ConstantVector::get(Mask);
11861 }
11862
11863 /// \brief Lower an interleaved store into a vstN intrinsic.
11864 ///
11865 /// E.g. Lower an interleaved store (Factor = 3):
11866 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11867 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11868 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11869 ///
11870 ///      Into:
11871 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11872 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11873 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11874 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11875 ///
11876 /// Note that the new shufflevectors will be removed and we'll only generate one
11877 /// vst3 instruction in CodeGen.
11878 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11879                                               ShuffleVectorInst *SVI,
11880                                               unsigned Factor) const {
11881   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11882          "Invalid interleave factor");
11883
11884   VectorType *VecTy = SVI->getType();
11885   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11886          "Invalid interleaved store");
11887
11888   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11889   Type *EltTy = VecTy->getVectorElementType();
11890   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11891
11892   const DataLayout &DL = SI->getModule()->getDataLayout();
11893   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11894   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11895
11896   // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11897   // doesn't support i64/f64 element).
11898   if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11899     return false;
11900
11901   Value *Op0 = SVI->getOperand(0);
11902   Value *Op1 = SVI->getOperand(1);
11903   IRBuilder<> Builder(SI);
11904
11905   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11906   // vectors to integer vectors.
11907   if (EltTy->isPointerTy()) {
11908     Type *IntTy = DL.getIntPtrType(EltTy);
11909
11910     // Convert to the corresponding integer vector.
11911     Type *IntVecTy =
11912         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11913     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11914     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11915
11916     SubVecTy = VectorType::get(IntTy, NumSubElts);
11917   }
11918
11919   static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11920                                        Intrinsic::arm_neon_vst3,
11921                                        Intrinsic::arm_neon_vst4};
11922   Function *VstNFunc = Intrinsic::getDeclaration(
11923       SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11924
11925   SmallVector<Value *, 6> Ops;
11926
11927   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11928   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11929
11930   // Split the shufflevector operands into sub vectors for the new vstN call.
11931   for (unsigned i = 0; i < Factor; i++)
11932     Ops.push_back(Builder.CreateShuffleVector(
11933         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11934
11935   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11936   Builder.CreateCall(VstNFunc, Ops);
11937   return true;
11938 }
11939
11940 enum HABaseType {
11941   HA_UNKNOWN = 0,
11942   HA_FLOAT,
11943   HA_DOUBLE,
11944   HA_VECT64,
11945   HA_VECT128
11946 };
11947
11948 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11949                                    uint64_t &Members) {
11950   if (auto *ST = dyn_cast<StructType>(Ty)) {
11951     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11952       uint64_t SubMembers = 0;
11953       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11954         return false;
11955       Members += SubMembers;
11956     }
11957   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11958     uint64_t SubMembers = 0;
11959     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11960       return false;
11961     Members += SubMembers * AT->getNumElements();
11962   } else if (Ty->isFloatTy()) {
11963     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11964       return false;
11965     Members = 1;
11966     Base = HA_FLOAT;
11967   } else if (Ty->isDoubleTy()) {
11968     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11969       return false;
11970     Members = 1;
11971     Base = HA_DOUBLE;
11972   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11973     Members = 1;
11974     switch (Base) {
11975     case HA_FLOAT:
11976     case HA_DOUBLE:
11977       return false;
11978     case HA_VECT64:
11979       return VT->getBitWidth() == 64;
11980     case HA_VECT128:
11981       return VT->getBitWidth() == 128;
11982     case HA_UNKNOWN:
11983       switch (VT->getBitWidth()) {
11984       case 64:
11985         Base = HA_VECT64;
11986         return true;
11987       case 128:
11988         Base = HA_VECT128;
11989         return true;
11990       default:
11991         return false;
11992       }
11993     }
11994   }
11995
11996   return (Members > 0 && Members <= 4);
11997 }
11998
11999 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
12000 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
12001 /// passing according to AAPCS rules.
12002 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
12003     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12004   if (getEffectiveCallingConv(CallConv, isVarArg) !=
12005       CallingConv::ARM_AAPCS_VFP)
12006     return false;
12007
12008   HABaseType Base = HA_UNKNOWN;
12009   uint64_t Members = 0;
12010   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12011   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12012
12013   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12014   return IsHA || IsIntArray;
12015 }