[ARM] Expand ROTL and ROTR of vector value types
[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   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
400   // a __gnu_ prefix (which is the default).
401   if (Subtarget->isTargetAEABI()) {
402     setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h");
403     setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h");
404     setLibcallName(RTLIB::FPEXT_F16_F32,   "__aeabi_h2f");
405   }
406
407   if (Subtarget->isThumb1Only())
408     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
409   else
410     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
411   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
412       !Subtarget->isThumb1Only()) {
413     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
414     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
415   }
416
417   for (MVT VT : MVT::vector_valuetypes()) {
418     for (MVT InnerVT : MVT::vector_valuetypes()) {
419       setTruncStoreAction(VT, InnerVT, Expand);
420       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
421       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
422       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
423     }
424
425     setOperationAction(ISD::MULHS, VT, Expand);
426     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
427     setOperationAction(ISD::MULHU, VT, Expand);
428     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
429
430     setOperationAction(ISD::BSWAP, VT, Expand);
431   }
432
433   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
434   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
435
436   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
437   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
438
439   if (Subtarget->hasNEON()) {
440     addDRTypeForNEON(MVT::v2f32);
441     addDRTypeForNEON(MVT::v8i8);
442     addDRTypeForNEON(MVT::v4i16);
443     addDRTypeForNEON(MVT::v2i32);
444     addDRTypeForNEON(MVT::v1i64);
445
446     addQRTypeForNEON(MVT::v4f32);
447     addQRTypeForNEON(MVT::v2f64);
448     addQRTypeForNEON(MVT::v16i8);
449     addQRTypeForNEON(MVT::v8i16);
450     addQRTypeForNEON(MVT::v4i32);
451     addQRTypeForNEON(MVT::v2i64);
452
453     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
454     // neither Neon nor VFP support any arithmetic operations on it.
455     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
456     // supported for v4f32.
457     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
458     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
459     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
460     // FIXME: Code duplication: FDIV and FREM are expanded always, see
461     // ARMTargetLowering::addTypeForNEON method for details.
462     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
463     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
464     // FIXME: Create unittest.
465     // In another words, find a way when "copysign" appears in DAG with vector
466     // operands.
467     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
468     // FIXME: Code duplication: SETCC has custom operation action, see
469     // ARMTargetLowering::addTypeForNEON method for details.
470     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
471     // FIXME: Create unittest for FNEG and for FABS.
472     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
473     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
474     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
475     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
476     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
477     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
478     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
479     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
480     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
481     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
482     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
483     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
484     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
485     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
486     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
487     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
488     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
489     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
490     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
491
492     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
493     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
494     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
495     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
496     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
497     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
498     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
499     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
500     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
501     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
502     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
503     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
504     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
505     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
506     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
507
508     // Mark v2f32 intrinsics.
509     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
510     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
511     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
512     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
513     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
514     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
515     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
516     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
517     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
518     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
519     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
520     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
521     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
522     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
523     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
524
525     // Neon does not support some operations on v1i64 and v2i64 types.
526     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
527     // Custom handling for some quad-vector types to detect VMULL.
528     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
529     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
530     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
531     // Custom handling for some vector types to avoid expensive expansions
532     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
533     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
534     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
535     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
536     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
537     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
538     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
539     // a destination type that is wider than the source, and nor does
540     // it have a FP_TO_[SU]INT instruction with a narrower destination than
541     // source.
542     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
543     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
544     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
545     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
546
547     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
548     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
549
550     // NEON does not have single instruction CTPOP for vectors with element
551     // types wider than 8-bits.  However, custom lowering can leverage the
552     // v8i8/v16i8 vcnt instruction.
553     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
554     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
555     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
556     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
557
558     // NEON does not have single instruction CTTZ for vectors.
559     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
560     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
561     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
562     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
563
564     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
565     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
566     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
567     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
568
569     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
570     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
571     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
572     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
573
574     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
575     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
576     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
577     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
578
579     // NEON only has FMA instructions as of VFP4.
580     if (!Subtarget->hasVFP4()) {
581       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
582       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
583     }
584
585     setTargetDAGCombine(ISD::INTRINSIC_VOID);
586     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
587     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
588     setTargetDAGCombine(ISD::SHL);
589     setTargetDAGCombine(ISD::SRL);
590     setTargetDAGCombine(ISD::SRA);
591     setTargetDAGCombine(ISD::SIGN_EXTEND);
592     setTargetDAGCombine(ISD::ZERO_EXTEND);
593     setTargetDAGCombine(ISD::ANY_EXTEND);
594     setTargetDAGCombine(ISD::BUILD_VECTOR);
595     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
596     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
597     setTargetDAGCombine(ISD::STORE);
598     setTargetDAGCombine(ISD::FP_TO_SINT);
599     setTargetDAGCombine(ISD::FP_TO_UINT);
600     setTargetDAGCombine(ISD::FDIV);
601     setTargetDAGCombine(ISD::LOAD);
602
603     // It is legal to extload from v4i8 to v4i16 or v4i32.
604     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
605                    MVT::v2i32}) {
606       for (MVT VT : MVT::integer_vector_valuetypes()) {
607         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
608         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
609         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
610       }
611     }
612   }
613
614   // ARM and Thumb2 support UMLAL/SMLAL.
615   if (!Subtarget->isThumb1Only())
616     setTargetDAGCombine(ISD::ADDC);
617
618   if (Subtarget->isFPOnlySP()) {
619     // When targeting a floating-point unit with only single-precision
620     // operations, f64 is legal for the few double-precision instructions which
621     // are present However, no double-precision operations other than moves,
622     // loads and stores are provided by the hardware.
623     setOperationAction(ISD::FADD,       MVT::f64, Expand);
624     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
625     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
626     setOperationAction(ISD::FMA,        MVT::f64, Expand);
627     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
628     setOperationAction(ISD::FREM,       MVT::f64, Expand);
629     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
630     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
631     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
632     setOperationAction(ISD::FABS,       MVT::f64, Expand);
633     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
634     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
635     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
636     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
637     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
638     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
639     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
640     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
641     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
642     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
643     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
644     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
645     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
646     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
647     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
648     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
649     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
650     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
651     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
652     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
653     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
654     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
655     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
656   }
657
658   computeRegisterProperties(Subtarget->getRegisterInfo());
659
660   // ARM does not have floating-point extending loads.
661   for (MVT VT : MVT::fp_valuetypes()) {
662     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
663     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
664   }
665
666   // ... or truncating stores
667   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
668   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
669   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
670
671   // ARM does not have i1 sign extending load.
672   for (MVT VT : MVT::integer_valuetypes())
673     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
674
675   // ARM supports all 4 flavors of integer indexed load / store.
676   if (!Subtarget->isThumb1Only()) {
677     for (unsigned im = (unsigned)ISD::PRE_INC;
678          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
679       setIndexedLoadAction(im,  MVT::i1,  Legal);
680       setIndexedLoadAction(im,  MVT::i8,  Legal);
681       setIndexedLoadAction(im,  MVT::i16, Legal);
682       setIndexedLoadAction(im,  MVT::i32, Legal);
683       setIndexedStoreAction(im, MVT::i1,  Legal);
684       setIndexedStoreAction(im, MVT::i8,  Legal);
685       setIndexedStoreAction(im, MVT::i16, Legal);
686       setIndexedStoreAction(im, MVT::i32, Legal);
687     }
688   }
689
690   setOperationAction(ISD::SADDO, MVT::i32, Custom);
691   setOperationAction(ISD::UADDO, MVT::i32, Custom);
692   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
693   setOperationAction(ISD::USUBO, MVT::i32, Custom);
694
695   // i64 operation support.
696   setOperationAction(ISD::MUL,     MVT::i64, Expand);
697   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
698   if (Subtarget->isThumb1Only()) {
699     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
700     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
701   }
702   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
703       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
704     setOperationAction(ISD::MULHS, MVT::i32, Expand);
705
706   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
707   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
708   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
709   setOperationAction(ISD::SRL,       MVT::i64, Custom);
710   setOperationAction(ISD::SRA,       MVT::i64, Custom);
711
712   if (!Subtarget->isThumb1Only()) {
713     // FIXME: We should do this for Thumb1 as well.
714     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
715     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
716     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
717     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
718   }
719
720   // ARM does not have ROTL.
721   setOperationAction(ISD::ROTL, MVT::i32, Expand);
722   for (MVT VT : MVT::vector_valuetypes()) {
723     setOperationAction(ISD::ROTL, VT, Expand);
724     setOperationAction(ISD::ROTR, VT, Expand);
725   }
726   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
727   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
728   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
729     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
730
731   // These just redirect to CTTZ and CTLZ on ARM.
732   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
733   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
734
735   // @llvm.readcyclecounter requires the Performance Monitors extension.
736   // Default to the 0 expansion on unsupported platforms.
737   // FIXME: Technically there are older ARM CPUs that have
738   // implementation-specific ways of obtaining this information.
739   if (Subtarget->hasPerfMon())
740     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
741
742   // Only ARMv6 has BSWAP.
743   if (!Subtarget->hasV6Ops())
744     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
745
746   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
747       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
748     // These are expanded into libcalls if the cpu doesn't have HW divider.
749     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
750     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
751   }
752
753   if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
754     setOperationAction(ISD::SDIV, MVT::i32, Custom);
755     setOperationAction(ISD::UDIV, MVT::i32, Custom);
756
757     setOperationAction(ISD::SDIV, MVT::i64, Custom);
758     setOperationAction(ISD::UDIV, MVT::i64, Custom);
759   }
760
761   setOperationAction(ISD::SREM,  MVT::i32, Expand);
762   setOperationAction(ISD::UREM,  MVT::i32, Expand);
763   // Register based DivRem for AEABI (RTABI 4.2)
764   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
765     setOperationAction(ISD::SREM, MVT::i64, Custom);
766     setOperationAction(ISD::UREM, MVT::i64, Custom);
767
768     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
769     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
770     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
771     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
772     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
773     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
774     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
775     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
776
777     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
778     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
779     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
780     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
781     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
782     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
783     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
784     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
785
786     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
787     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
788   } else {
789     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
790     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
791   }
792
793   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
794   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
795   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
796   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
797
798   setOperationAction(ISD::TRAP, MVT::Other, Legal);
799
800   // Use the default implementation.
801   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
802   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
803   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
804   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
805   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
806   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
807
808   if (!Subtarget->isTargetMachO()) {
809     // Non-MachO platforms may return values in these registers via the
810     // personality function.
811     setExceptionPointerRegister(ARM::R0);
812     setExceptionSelectorRegister(ARM::R1);
813   }
814
815   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
816     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
817   else
818     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
819
820   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
821   // the default expansion. If we are targeting a single threaded system,
822   // then set them all for expand so we can lower them later into their
823   // non-atomic form.
824   if (TM.Options.ThreadModel == ThreadModel::Single)
825     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
826   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
827     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
828     // to ldrex/strex loops already.
829     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
830
831     // On v8, we have particularly efficient implementations of atomic fences
832     // if they can be combined with nearby atomic loads and stores.
833     if (!Subtarget->hasV8Ops()) {
834       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
835       setInsertFencesForAtomic(true);
836     }
837   } else {
838     // If there's anything we can use as a barrier, go through custom lowering
839     // for ATOMIC_FENCE.
840     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
841                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
842
843     // Set them all for expansion, which will force libcalls.
844     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
845     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
846     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
847     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
848     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
849     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
850     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
851     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
852     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
853     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
854     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
855     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
856     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
857     // Unordered/Monotonic case.
858     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
859     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
860   }
861
862   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
863
864   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
865   if (!Subtarget->hasV6Ops()) {
866     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
867     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
868   }
869   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
870
871   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
872       !Subtarget->isThumb1Only()) {
873     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
874     // iff target supports vfp2.
875     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
876     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
877   }
878
879   // We want to custom lower some of our intrinsics.
880   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
881   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
882   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
883   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
884   if (Subtarget->isTargetDarwin())
885     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
886
887   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
888   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
889   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
890   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
891   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
892   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
893   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
894   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
895   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
896
897   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
898   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
899   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
900   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
901   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
902
903   // We don't support sin/cos/fmod/copysign/pow
904   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
905   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
906   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
907   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
908   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
909   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
910   setOperationAction(ISD::FREM,      MVT::f64, Expand);
911   setOperationAction(ISD::FREM,      MVT::f32, Expand);
912   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
913       !Subtarget->isThumb1Only()) {
914     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
915     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
916   }
917   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
918   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
919
920   if (!Subtarget->hasVFP4()) {
921     setOperationAction(ISD::FMA, MVT::f64, Expand);
922     setOperationAction(ISD::FMA, MVT::f32, Expand);
923   }
924
925   // Various VFP goodness
926   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
927     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
928     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
929       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
930       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
931     }
932
933     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
934     if (!Subtarget->hasFP16()) {
935       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
936       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
937     }
938   }
939
940   // Combine sin / cos into one node or libcall if possible.
941   if (Subtarget->hasSinCos()) {
942     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
943     setLibcallName(RTLIB::SINCOS_F64, "sincos");
944     if (Subtarget->getTargetTriple().isiOS()) {
945       // For iOS, we don't want to the normal expansion of a libcall to
946       // sincos. We want to issue a libcall to __sincos_stret.
947       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
948       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
949     }
950   }
951
952   // FP-ARMv8 implements a lot of rounding-like FP operations.
953   if (Subtarget->hasFPARMv8()) {
954     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
955     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
956     setOperationAction(ISD::FROUND, MVT::f32, Legal);
957     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
958     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
959     setOperationAction(ISD::FRINT, MVT::f32, Legal);
960     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
961     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
962     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
963     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
964     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
965     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
966
967     if (!Subtarget->isFPOnlySP()) {
968       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
969       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
970       setOperationAction(ISD::FROUND, MVT::f64, Legal);
971       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
972       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
973       setOperationAction(ISD::FRINT, MVT::f64, Legal);
974       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
975       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
976     }
977   }
978
979   if (Subtarget->hasNEON()) {
980     // vmin and vmax aren't available in a scalar form, so we use
981     // a NEON instruction with an undef lane instead.
982     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
983     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
984     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
985     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
986     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
987     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
988   }
989
990   // We have target-specific dag combine patterns for the following nodes:
991   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
992   setTargetDAGCombine(ISD::ADD);
993   setTargetDAGCombine(ISD::SUB);
994   setTargetDAGCombine(ISD::MUL);
995   setTargetDAGCombine(ISD::AND);
996   setTargetDAGCombine(ISD::OR);
997   setTargetDAGCombine(ISD::XOR);
998
999   if (Subtarget->hasV6Ops())
1000     setTargetDAGCombine(ISD::SRL);
1001
1002   setStackPointerRegisterToSaveRestore(ARM::SP);
1003
1004   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1005       !Subtarget->hasVFP2())
1006     setSchedulingPreference(Sched::RegPressure);
1007   else
1008     setSchedulingPreference(Sched::Hybrid);
1009
1010   //// temporary - rewrite interface to use type
1011   MaxStoresPerMemset = 8;
1012   MaxStoresPerMemsetOptSize = 4;
1013   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1014   MaxStoresPerMemcpyOptSize = 2;
1015   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1016   MaxStoresPerMemmoveOptSize = 2;
1017
1018   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1019   // are at least 4 bytes aligned.
1020   setMinStackArgumentAlignment(4);
1021
1022   // Prefer likely predicted branches to selects on out-of-order cores.
1023   PredictableSelectIsExpensive = Subtarget->isLikeA9();
1024
1025   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1026 }
1027
1028 bool ARMTargetLowering::useSoftFloat() const {
1029   return Subtarget->useSoftFloat();
1030 }
1031
1032 // FIXME: It might make sense to define the representative register class as the
1033 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1034 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1035 // SPR's representative would be DPR_VFP2. This should work well if register
1036 // pressure tracking were modified such that a register use would increment the
1037 // pressure of the register class's representative and all of it's super
1038 // classes' representatives transitively. We have not implemented this because
1039 // of the difficulty prior to coalescing of modeling operand register classes
1040 // due to the common occurrence of cross class copies and subregister insertions
1041 // and extractions.
1042 std::pair<const TargetRegisterClass *, uint8_t>
1043 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1044                                            MVT VT) const {
1045   const TargetRegisterClass *RRC = nullptr;
1046   uint8_t Cost = 1;
1047   switch (VT.SimpleTy) {
1048   default:
1049     return TargetLowering::findRepresentativeClass(TRI, VT);
1050   // Use DPR as representative register class for all floating point
1051   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1052   // the cost is 1 for both f32 and f64.
1053   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1054   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1055     RRC = &ARM::DPRRegClass;
1056     // When NEON is used for SP, only half of the register file is available
1057     // because operations that define both SP and DP results will be constrained
1058     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1059     // coalescing by double-counting the SP regs. See the FIXME above.
1060     if (Subtarget->useNEONForSinglePrecisionFP())
1061       Cost = 2;
1062     break;
1063   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1064   case MVT::v4f32: case MVT::v2f64:
1065     RRC = &ARM::DPRRegClass;
1066     Cost = 2;
1067     break;
1068   case MVT::v4i64:
1069     RRC = &ARM::DPRRegClass;
1070     Cost = 4;
1071     break;
1072   case MVT::v8i64:
1073     RRC = &ARM::DPRRegClass;
1074     Cost = 8;
1075     break;
1076   }
1077   return std::make_pair(RRC, Cost);
1078 }
1079
1080 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1081   switch ((ARMISD::NodeType)Opcode) {
1082   case ARMISD::FIRST_NUMBER:  break;
1083   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1084   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1085   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1086   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1087   case ARMISD::CALL:          return "ARMISD::CALL";
1088   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1089   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1090   case ARMISD::tCALL:         return "ARMISD::tCALL";
1091   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1092   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1093   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1094   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1095   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1096   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1097   case ARMISD::CMP:           return "ARMISD::CMP";
1098   case ARMISD::CMN:           return "ARMISD::CMN";
1099   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1100   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1101   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1102   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1103   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1104
1105   case ARMISD::CMOV:          return "ARMISD::CMOV";
1106
1107   case ARMISD::RBIT:          return "ARMISD::RBIT";
1108
1109   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1110   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1111   case ARMISD::RRX:           return "ARMISD::RRX";
1112
1113   case ARMISD::ADDC:          return "ARMISD::ADDC";
1114   case ARMISD::ADDE:          return "ARMISD::ADDE";
1115   case ARMISD::SUBC:          return "ARMISD::SUBC";
1116   case ARMISD::SUBE:          return "ARMISD::SUBE";
1117
1118   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1119   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1120
1121   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1122   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1123   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1124
1125   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1126
1127   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1128
1129   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1130
1131   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1132
1133   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1134
1135   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1136   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1137
1138   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1139   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1140   case ARMISD::VCGE:          return "ARMISD::VCGE";
1141   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1142   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1143   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1144   case ARMISD::VCGT:          return "ARMISD::VCGT";
1145   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1146   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1147   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1148   case ARMISD::VTST:          return "ARMISD::VTST";
1149
1150   case ARMISD::VSHL:          return "ARMISD::VSHL";
1151   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1152   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1153   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1154   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1155   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1156   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1157   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1158   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1159   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1160   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1161   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1162   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1163   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1164   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1165   case ARMISD::VSLI:          return "ARMISD::VSLI";
1166   case ARMISD::VSRI:          return "ARMISD::VSRI";
1167   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1168   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1169   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1170   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1171   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1172   case ARMISD::VDUP:          return "ARMISD::VDUP";
1173   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1174   case ARMISD::VEXT:          return "ARMISD::VEXT";
1175   case ARMISD::VREV64:        return "ARMISD::VREV64";
1176   case ARMISD::VREV32:        return "ARMISD::VREV32";
1177   case ARMISD::VREV16:        return "ARMISD::VREV16";
1178   case ARMISD::VZIP:          return "ARMISD::VZIP";
1179   case ARMISD::VUZP:          return "ARMISD::VUZP";
1180   case ARMISD::VTRN:          return "ARMISD::VTRN";
1181   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1182   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1183   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1184   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1185   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1186   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1187   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1188   case ARMISD::BFI:           return "ARMISD::BFI";
1189   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1190   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1191   case ARMISD::VBSL:          return "ARMISD::VBSL";
1192   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1193   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1194   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1195   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1196   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1197   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1198   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1199   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1200   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1201   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1202   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1203   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1204   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1205   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1206   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1207   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1208   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1209   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1210   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1211   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1212   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1213   }
1214   return nullptr;
1215 }
1216
1217 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1218                                           EVT VT) const {
1219   if (!VT.isVector())
1220     return getPointerTy(DL);
1221   return VT.changeVectorElementTypeToInteger();
1222 }
1223
1224 /// getRegClassFor - Return the register class that should be used for the
1225 /// specified value type.
1226 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1227   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1228   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1229   // load / store 4 to 8 consecutive D registers.
1230   if (Subtarget->hasNEON()) {
1231     if (VT == MVT::v4i64)
1232       return &ARM::QQPRRegClass;
1233     if (VT == MVT::v8i64)
1234       return &ARM::QQQQPRRegClass;
1235   }
1236   return TargetLowering::getRegClassFor(VT);
1237 }
1238
1239 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1240 // source/dest is aligned and the copy size is large enough. We therefore want
1241 // to align such objects passed to memory intrinsics.
1242 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1243                                                unsigned &PrefAlign) const {
1244   if (!isa<MemIntrinsic>(CI))
1245     return false;
1246   MinSize = 8;
1247   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1248   // cycle faster than 4-byte aligned LDM.
1249   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1250   return true;
1251 }
1252
1253 // Create a fast isel object.
1254 FastISel *
1255 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1256                                   const TargetLibraryInfo *libInfo) const {
1257   return ARM::createFastISel(funcInfo, libInfo);
1258 }
1259
1260 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1261   unsigned NumVals = N->getNumValues();
1262   if (!NumVals)
1263     return Sched::RegPressure;
1264
1265   for (unsigned i = 0; i != NumVals; ++i) {
1266     EVT VT = N->getValueType(i);
1267     if (VT == MVT::Glue || VT == MVT::Other)
1268       continue;
1269     if (VT.isFloatingPoint() || VT.isVector())
1270       return Sched::ILP;
1271   }
1272
1273   if (!N->isMachineOpcode())
1274     return Sched::RegPressure;
1275
1276   // Load are scheduled for latency even if there instruction itinerary
1277   // is not available.
1278   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1279   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1280
1281   if (MCID.getNumDefs() == 0)
1282     return Sched::RegPressure;
1283   if (!Itins->isEmpty() &&
1284       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1285     return Sched::ILP;
1286
1287   return Sched::RegPressure;
1288 }
1289
1290 //===----------------------------------------------------------------------===//
1291 // Lowering Code
1292 //===----------------------------------------------------------------------===//
1293
1294 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1295 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1296   switch (CC) {
1297   default: llvm_unreachable("Unknown condition code!");
1298   case ISD::SETNE:  return ARMCC::NE;
1299   case ISD::SETEQ:  return ARMCC::EQ;
1300   case ISD::SETGT:  return ARMCC::GT;
1301   case ISD::SETGE:  return ARMCC::GE;
1302   case ISD::SETLT:  return ARMCC::LT;
1303   case ISD::SETLE:  return ARMCC::LE;
1304   case ISD::SETUGT: return ARMCC::HI;
1305   case ISD::SETUGE: return ARMCC::HS;
1306   case ISD::SETULT: return ARMCC::LO;
1307   case ISD::SETULE: return ARMCC::LS;
1308   }
1309 }
1310
1311 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1312 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1313                         ARMCC::CondCodes &CondCode2) {
1314   CondCode2 = ARMCC::AL;
1315   switch (CC) {
1316   default: llvm_unreachable("Unknown FP condition!");
1317   case ISD::SETEQ:
1318   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1319   case ISD::SETGT:
1320   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1321   case ISD::SETGE:
1322   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1323   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1324   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1325   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1326   case ISD::SETO:   CondCode = ARMCC::VC; break;
1327   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1328   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1329   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1330   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1331   case ISD::SETLT:
1332   case ISD::SETULT: CondCode = ARMCC::LT; break;
1333   case ISD::SETLE:
1334   case ISD::SETULE: CondCode = ARMCC::LE; break;
1335   case ISD::SETNE:
1336   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1337   }
1338 }
1339
1340 //===----------------------------------------------------------------------===//
1341 //                      Calling Convention Implementation
1342 //===----------------------------------------------------------------------===//
1343
1344 #include "ARMGenCallingConv.inc"
1345
1346 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1347 /// account presence of floating point hardware and calling convention
1348 /// limitations, such as support for variadic functions.
1349 CallingConv::ID
1350 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1351                                            bool isVarArg) const {
1352   switch (CC) {
1353   default:
1354     llvm_unreachable("Unsupported calling convention");
1355   case CallingConv::ARM_AAPCS:
1356   case CallingConv::ARM_APCS:
1357   case CallingConv::GHC:
1358     return CC;
1359   case CallingConv::ARM_AAPCS_VFP:
1360     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1361   case CallingConv::C:
1362     if (!Subtarget->isAAPCS_ABI())
1363       return CallingConv::ARM_APCS;
1364     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1365              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1366              !isVarArg)
1367       return CallingConv::ARM_AAPCS_VFP;
1368     else
1369       return CallingConv::ARM_AAPCS;
1370   case CallingConv::Fast:
1371     if (!Subtarget->isAAPCS_ABI()) {
1372       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1373         return CallingConv::Fast;
1374       return CallingConv::ARM_APCS;
1375     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1376       return CallingConv::ARM_AAPCS_VFP;
1377     else
1378       return CallingConv::ARM_AAPCS;
1379   }
1380 }
1381
1382 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1383 /// CallingConvention.
1384 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1385                                                  bool Return,
1386                                                  bool isVarArg) const {
1387   switch (getEffectiveCallingConv(CC, isVarArg)) {
1388   default:
1389     llvm_unreachable("Unsupported calling convention");
1390   case CallingConv::ARM_APCS:
1391     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1392   case CallingConv::ARM_AAPCS:
1393     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1394   case CallingConv::ARM_AAPCS_VFP:
1395     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1396   case CallingConv::Fast:
1397     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1398   case CallingConv::GHC:
1399     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1400   }
1401 }
1402
1403 /// LowerCallResult - Lower the result values of a call into the
1404 /// appropriate copies out of appropriate physical registers.
1405 SDValue
1406 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1407                                    CallingConv::ID CallConv, bool isVarArg,
1408                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1409                                    SDLoc dl, SelectionDAG &DAG,
1410                                    SmallVectorImpl<SDValue> &InVals,
1411                                    bool isThisReturn, SDValue ThisVal) const {
1412
1413   // Assign locations to each value returned by this call.
1414   SmallVector<CCValAssign, 16> RVLocs;
1415   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1416                     *DAG.getContext(), Call);
1417   CCInfo.AnalyzeCallResult(Ins,
1418                            CCAssignFnForNode(CallConv, /* Return*/ true,
1419                                              isVarArg));
1420
1421   // Copy all of the result registers out of their specified physreg.
1422   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1423     CCValAssign VA = RVLocs[i];
1424
1425     // Pass 'this' value directly from the argument to return value, to avoid
1426     // reg unit interference
1427     if (i == 0 && isThisReturn) {
1428       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1429              "unexpected return calling convention register assignment");
1430       InVals.push_back(ThisVal);
1431       continue;
1432     }
1433
1434     SDValue Val;
1435     if (VA.needsCustom()) {
1436       // Handle f64 or half of a v2f64.
1437       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1438                                       InFlag);
1439       Chain = Lo.getValue(1);
1440       InFlag = Lo.getValue(2);
1441       VA = RVLocs[++i]; // skip ahead to next loc
1442       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1443                                       InFlag);
1444       Chain = Hi.getValue(1);
1445       InFlag = Hi.getValue(2);
1446       if (!Subtarget->isLittle())
1447         std::swap (Lo, Hi);
1448       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1449
1450       if (VA.getLocVT() == MVT::v2f64) {
1451         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1452         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1453                           DAG.getConstant(0, dl, MVT::i32));
1454
1455         VA = RVLocs[++i]; // skip ahead to next loc
1456         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1457         Chain = Lo.getValue(1);
1458         InFlag = Lo.getValue(2);
1459         VA = RVLocs[++i]; // skip ahead to next loc
1460         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1461         Chain = Hi.getValue(1);
1462         InFlag = Hi.getValue(2);
1463         if (!Subtarget->isLittle())
1464           std::swap (Lo, Hi);
1465         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1466         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1467                           DAG.getConstant(1, dl, MVT::i32));
1468       }
1469     } else {
1470       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1471                                InFlag);
1472       Chain = Val.getValue(1);
1473       InFlag = Val.getValue(2);
1474     }
1475
1476     switch (VA.getLocInfo()) {
1477     default: llvm_unreachable("Unknown loc info!");
1478     case CCValAssign::Full: break;
1479     case CCValAssign::BCvt:
1480       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1481       break;
1482     }
1483
1484     InVals.push_back(Val);
1485   }
1486
1487   return Chain;
1488 }
1489
1490 /// LowerMemOpCallTo - Store the argument to the stack.
1491 SDValue
1492 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1493                                     SDValue StackPtr, SDValue Arg,
1494                                     SDLoc dl, SelectionDAG &DAG,
1495                                     const CCValAssign &VA,
1496                                     ISD::ArgFlagsTy Flags) const {
1497   unsigned LocMemOffset = VA.getLocMemOffset();
1498   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1499   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1500                        StackPtr, PtrOff);
1501   return DAG.getStore(
1502       Chain, dl, Arg, PtrOff,
1503       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1504       false, false, 0);
1505 }
1506
1507 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1508                                          SDValue Chain, SDValue &Arg,
1509                                          RegsToPassVector &RegsToPass,
1510                                          CCValAssign &VA, CCValAssign &NextVA,
1511                                          SDValue &StackPtr,
1512                                          SmallVectorImpl<SDValue> &MemOpChains,
1513                                          ISD::ArgFlagsTy Flags) const {
1514
1515   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1516                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1517   unsigned id = Subtarget->isLittle() ? 0 : 1;
1518   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1519
1520   if (NextVA.isRegLoc())
1521     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1522   else {
1523     assert(NextVA.isMemLoc());
1524     if (!StackPtr.getNode())
1525       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1526                                     getPointerTy(DAG.getDataLayout()));
1527
1528     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1529                                            dl, DAG, NextVA,
1530                                            Flags));
1531   }
1532 }
1533
1534 /// LowerCall - Lowering a call into a callseq_start <-
1535 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1536 /// nodes.
1537 SDValue
1538 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1539                              SmallVectorImpl<SDValue> &InVals) const {
1540   SelectionDAG &DAG                     = CLI.DAG;
1541   SDLoc &dl                             = CLI.DL;
1542   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1543   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1544   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1545   SDValue Chain                         = CLI.Chain;
1546   SDValue Callee                        = CLI.Callee;
1547   bool &isTailCall                      = CLI.IsTailCall;
1548   CallingConv::ID CallConv              = CLI.CallConv;
1549   bool doesNotRet                       = CLI.DoesNotReturn;
1550   bool isVarArg                         = CLI.IsVarArg;
1551
1552   MachineFunction &MF = DAG.getMachineFunction();
1553   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1554   bool isThisReturn   = false;
1555   bool isSibCall      = false;
1556   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1557
1558   // Disable tail calls if they're not supported.
1559   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1560     isTailCall = false;
1561
1562   if (isTailCall) {
1563     // Check if it's really possible to do a tail call.
1564     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1565                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1566                                                    Outs, OutVals, Ins, DAG);
1567     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1568       report_fatal_error("failed to perform tail call elimination on a call "
1569                          "site marked musttail");
1570     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1571     // detected sibcalls.
1572     if (isTailCall) {
1573       ++NumTailCalls;
1574       isSibCall = true;
1575     }
1576   }
1577
1578   // Analyze operands of the call, assigning locations to each operand.
1579   SmallVector<CCValAssign, 16> ArgLocs;
1580   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1581                     *DAG.getContext(), Call);
1582   CCInfo.AnalyzeCallOperands(Outs,
1583                              CCAssignFnForNode(CallConv, /* Return*/ false,
1584                                                isVarArg));
1585
1586   // Get a count of how many bytes are to be pushed on the stack.
1587   unsigned NumBytes = CCInfo.getNextStackOffset();
1588
1589   // For tail calls, memory operands are available in our caller's stack.
1590   if (isSibCall)
1591     NumBytes = 0;
1592
1593   // Adjust the stack pointer for the new arguments...
1594   // These operations are automatically eliminated by the prolog/epilog pass
1595   if (!isSibCall)
1596     Chain = DAG.getCALLSEQ_START(Chain,
1597                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1598
1599   SDValue StackPtr =
1600       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1601
1602   RegsToPassVector RegsToPass;
1603   SmallVector<SDValue, 8> MemOpChains;
1604
1605   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1606   // of tail call optimization, arguments are handled later.
1607   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1608        i != e;
1609        ++i, ++realArgIdx) {
1610     CCValAssign &VA = ArgLocs[i];
1611     SDValue Arg = OutVals[realArgIdx];
1612     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1613     bool isByVal = Flags.isByVal();
1614
1615     // Promote the value if needed.
1616     switch (VA.getLocInfo()) {
1617     default: llvm_unreachable("Unknown loc info!");
1618     case CCValAssign::Full: break;
1619     case CCValAssign::SExt:
1620       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1621       break;
1622     case CCValAssign::ZExt:
1623       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1624       break;
1625     case CCValAssign::AExt:
1626       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1627       break;
1628     case CCValAssign::BCvt:
1629       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1630       break;
1631     }
1632
1633     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1634     if (VA.needsCustom()) {
1635       if (VA.getLocVT() == MVT::v2f64) {
1636         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1637                                   DAG.getConstant(0, dl, MVT::i32));
1638         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1639                                   DAG.getConstant(1, dl, MVT::i32));
1640
1641         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1642                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1643
1644         VA = ArgLocs[++i]; // skip ahead to next loc
1645         if (VA.isRegLoc()) {
1646           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1647                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1648         } else {
1649           assert(VA.isMemLoc());
1650
1651           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1652                                                  dl, DAG, VA, Flags));
1653         }
1654       } else {
1655         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1656                          StackPtr, MemOpChains, Flags);
1657       }
1658     } else if (VA.isRegLoc()) {
1659       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1660         assert(VA.getLocVT() == MVT::i32 &&
1661                "unexpected calling convention register assignment");
1662         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1663                "unexpected use of 'returned'");
1664         isThisReturn = true;
1665       }
1666       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1667     } else if (isByVal) {
1668       assert(VA.isMemLoc());
1669       unsigned offset = 0;
1670
1671       // True if this byval aggregate will be split between registers
1672       // and memory.
1673       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1674       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1675
1676       if (CurByValIdx < ByValArgsCount) {
1677
1678         unsigned RegBegin, RegEnd;
1679         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1680
1681         EVT PtrVT =
1682             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1683         unsigned int i, j;
1684         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1685           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1686           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1687           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1688                                      MachinePointerInfo(),
1689                                      false, false, false,
1690                                      DAG.InferPtrAlignment(AddArg));
1691           MemOpChains.push_back(Load.getValue(1));
1692           RegsToPass.push_back(std::make_pair(j, Load));
1693         }
1694
1695         // If parameter size outsides register area, "offset" value
1696         // helps us to calculate stack slot for remained part properly.
1697         offset = RegEnd - RegBegin;
1698
1699         CCInfo.nextInRegsParam();
1700       }
1701
1702       if (Flags.getByValSize() > 4*offset) {
1703         auto PtrVT = getPointerTy(DAG.getDataLayout());
1704         unsigned LocMemOffset = VA.getLocMemOffset();
1705         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1706         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1707         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1708         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1709         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1710                                            MVT::i32);
1711         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1712                                             MVT::i32);
1713
1714         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1715         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1716         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1717                                           Ops));
1718       }
1719     } else if (!isSibCall) {
1720       assert(VA.isMemLoc());
1721
1722       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1723                                              dl, DAG, VA, Flags));
1724     }
1725   }
1726
1727   if (!MemOpChains.empty())
1728     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1729
1730   // Build a sequence of copy-to-reg nodes chained together with token chain
1731   // and flag operands which copy the outgoing args into the appropriate regs.
1732   SDValue InFlag;
1733   // Tail call byval lowering might overwrite argument registers so in case of
1734   // tail call optimization the copies to registers are lowered later.
1735   if (!isTailCall)
1736     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1737       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1738                                RegsToPass[i].second, InFlag);
1739       InFlag = Chain.getValue(1);
1740     }
1741
1742   // For tail calls lower the arguments to the 'real' stack slot.
1743   if (isTailCall) {
1744     // Force all the incoming stack arguments to be loaded from the stack
1745     // before any new outgoing arguments are stored to the stack, because the
1746     // outgoing stack slots may alias the incoming argument stack slots, and
1747     // the alias isn't otherwise explicit. This is slightly more conservative
1748     // than necessary, because it means that each store effectively depends
1749     // on every argument instead of just those arguments it would clobber.
1750
1751     // Do not flag preceding copytoreg stuff together with the following stuff.
1752     InFlag = SDValue();
1753     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1754       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1755                                RegsToPass[i].second, InFlag);
1756       InFlag = Chain.getValue(1);
1757     }
1758     InFlag = SDValue();
1759   }
1760
1761   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1762   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1763   // node so that legalize doesn't hack it.
1764   bool isDirect = false;
1765   bool isARMFunc = false;
1766   bool isLocalARMFunc = false;
1767   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1768   auto PtrVt = getPointerTy(DAG.getDataLayout());
1769
1770   if (Subtarget->genLongCalls()) {
1771     assert((Subtarget->isTargetWindows() ||
1772             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1773            "long-calls with non-static relocation model!");
1774     // Handle a global address or an external symbol. If it's not one of
1775     // those, the target's already in a register, so we don't need to do
1776     // anything extra.
1777     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1778       const GlobalValue *GV = G->getGlobal();
1779       // Create a constant pool entry for the callee address
1780       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1781       ARMConstantPoolValue *CPV =
1782         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1783
1784       // Get the address of the callee into a register
1785       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1786       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1787       Callee = DAG.getLoad(
1788           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1789           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1790           false, false, 0);
1791     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1792       const char *Sym = S->getSymbol();
1793
1794       // Create a constant pool entry for the callee address
1795       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1796       ARMConstantPoolValue *CPV =
1797         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1798                                       ARMPCLabelIndex, 0);
1799       // Get the address of the callee into a register
1800       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1801       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1802       Callee = DAG.getLoad(
1803           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1804           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1805           false, false, 0);
1806     }
1807   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1808     const GlobalValue *GV = G->getGlobal();
1809     isDirect = true;
1810     bool isDef = GV->isStrongDefinitionForLinker();
1811     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1812                    getTargetMachine().getRelocationModel() != Reloc::Static;
1813     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1814     // ARM call to a local ARM function is predicable.
1815     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1816     // tBX takes a register source operand.
1817     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1818       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1819       Callee = DAG.getNode(
1820           ARMISD::WrapperPIC, dl, PtrVt,
1821           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1822       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1823                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1824                            false, false, true, 0);
1825     } else if (Subtarget->isTargetCOFF()) {
1826       assert(Subtarget->isTargetWindows() &&
1827              "Windows is the only supported COFF target");
1828       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1829                                  ? ARMII::MO_DLLIMPORT
1830                                  : ARMII::MO_NO_FLAG;
1831       Callee =
1832           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1833       if (GV->hasDLLImportStorageClass())
1834         Callee =
1835             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1836                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1837                         MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1838                         false, false, false, 0);
1839     } else {
1840       // On ELF targets for PIC code, direct calls should go through the PLT
1841       unsigned OpFlags = 0;
1842       if (Subtarget->isTargetELF() &&
1843           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1844         OpFlags = ARMII::MO_PLT;
1845       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1846     }
1847   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1848     isDirect = true;
1849     bool isStub = Subtarget->isTargetMachO() &&
1850                   getTargetMachine().getRelocationModel() != Reloc::Static;
1851     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1852     // tBX takes a register source operand.
1853     const char *Sym = S->getSymbol();
1854     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1855       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1856       ARMConstantPoolValue *CPV =
1857         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1858                                       ARMPCLabelIndex, 4);
1859       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1860       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1861       Callee = DAG.getLoad(
1862           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1863           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1864           false, false, 0);
1865       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1866       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1867     } else {
1868       unsigned OpFlags = 0;
1869       // On ELF targets for PIC code, direct calls should go through the PLT
1870       if (Subtarget->isTargetELF() &&
1871                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1872         OpFlags = ARMII::MO_PLT;
1873       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1874     }
1875   }
1876
1877   // FIXME: handle tail calls differently.
1878   unsigned CallOpc;
1879   if (Subtarget->isThumb()) {
1880     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1881       CallOpc = ARMISD::CALL_NOLINK;
1882     else
1883       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1884   } else {
1885     if (!isDirect && !Subtarget->hasV5TOps())
1886       CallOpc = ARMISD::CALL_NOLINK;
1887     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1888              // Emit regular call when code size is the priority
1889              !MF.getFunction()->optForMinSize())
1890       // "mov lr, pc; b _foo" to avoid confusing the RSP
1891       CallOpc = ARMISD::CALL_NOLINK;
1892     else
1893       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1894   }
1895
1896   std::vector<SDValue> Ops;
1897   Ops.push_back(Chain);
1898   Ops.push_back(Callee);
1899
1900   // Add argument registers to the end of the list so that they are known live
1901   // into the call.
1902   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1903     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1904                                   RegsToPass[i].second.getValueType()));
1905
1906   // Add a register mask operand representing the call-preserved registers.
1907   if (!isTailCall) {
1908     const uint32_t *Mask;
1909     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1910     if (isThisReturn) {
1911       // For 'this' returns, use the R0-preserving mask if applicable
1912       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1913       if (!Mask) {
1914         // Set isThisReturn to false if the calling convention is not one that
1915         // allows 'returned' to be modeled in this way, so LowerCallResult does
1916         // not try to pass 'this' straight through
1917         isThisReturn = false;
1918         Mask = ARI->getCallPreservedMask(MF, CallConv);
1919       }
1920     } else
1921       Mask = ARI->getCallPreservedMask(MF, CallConv);
1922
1923     assert(Mask && "Missing call preserved mask for calling convention");
1924     Ops.push_back(DAG.getRegisterMask(Mask));
1925   }
1926
1927   if (InFlag.getNode())
1928     Ops.push_back(InFlag);
1929
1930   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1931   if (isTailCall) {
1932     MF.getFrameInfo()->setHasTailCall();
1933     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1934   }
1935
1936   // Returns a chain and a flag for retval copy to use.
1937   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1938   InFlag = Chain.getValue(1);
1939
1940   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1941                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1942   if (!Ins.empty())
1943     InFlag = Chain.getValue(1);
1944
1945   // Handle result values, copying them out of physregs into vregs that we
1946   // return.
1947   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1948                          InVals, isThisReturn,
1949                          isThisReturn ? OutVals[0] : SDValue());
1950 }
1951
1952 /// HandleByVal - Every parameter *after* a byval parameter is passed
1953 /// on the stack.  Remember the next parameter register to allocate,
1954 /// and then confiscate the rest of the parameter registers to insure
1955 /// this.
1956 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1957                                     unsigned Align) const {
1958   assert((State->getCallOrPrologue() == Prologue ||
1959           State->getCallOrPrologue() == Call) &&
1960          "unhandled ParmContext");
1961
1962   // Byval (as with any stack) slots are always at least 4 byte aligned.
1963   Align = std::max(Align, 4U);
1964
1965   unsigned Reg = State->AllocateReg(GPRArgRegs);
1966   if (!Reg)
1967     return;
1968
1969   unsigned AlignInRegs = Align / 4;
1970   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1971   for (unsigned i = 0; i < Waste; ++i)
1972     Reg = State->AllocateReg(GPRArgRegs);
1973
1974   if (!Reg)
1975     return;
1976
1977   unsigned Excess = 4 * (ARM::R4 - Reg);
1978
1979   // Special case when NSAA != SP and parameter size greater than size of
1980   // all remained GPR regs. In that case we can't split parameter, we must
1981   // send it to stack. We also must set NCRN to R4, so waste all
1982   // remained registers.
1983   const unsigned NSAAOffset = State->getNextStackOffset();
1984   if (NSAAOffset != 0 && Size > Excess) {
1985     while (State->AllocateReg(GPRArgRegs))
1986       ;
1987     return;
1988   }
1989
1990   // First register for byval parameter is the first register that wasn't
1991   // allocated before this method call, so it would be "reg".
1992   // If parameter is small enough to be saved in range [reg, r4), then
1993   // the end (first after last) register would be reg + param-size-in-regs,
1994   // else parameter would be splitted between registers and stack,
1995   // end register would be r4 in this case.
1996   unsigned ByValRegBegin = Reg;
1997   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1998   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1999   // Note, first register is allocated in the beginning of function already,
2000   // allocate remained amount of registers we need.
2001   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2002     State->AllocateReg(GPRArgRegs);
2003   // A byval parameter that is split between registers and memory needs its
2004   // size truncated here.
2005   // In the case where the entire structure fits in registers, we set the
2006   // size in memory to zero.
2007   Size = std::max<int>(Size - Excess, 0);
2008 }
2009
2010 /// MatchingStackOffset - Return true if the given stack call argument is
2011 /// already available in the same position (relatively) of the caller's
2012 /// incoming argument stack.
2013 static
2014 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2015                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2016                          const TargetInstrInfo *TII) {
2017   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2018   int FI = INT_MAX;
2019   if (Arg.getOpcode() == ISD::CopyFromReg) {
2020     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2021     if (!TargetRegisterInfo::isVirtualRegister(VR))
2022       return false;
2023     MachineInstr *Def = MRI->getVRegDef(VR);
2024     if (!Def)
2025       return false;
2026     if (!Flags.isByVal()) {
2027       if (!TII->isLoadFromStackSlot(Def, FI))
2028         return false;
2029     } else {
2030       return false;
2031     }
2032   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2033     if (Flags.isByVal())
2034       // ByVal argument is passed in as a pointer but it's now being
2035       // dereferenced. e.g.
2036       // define @foo(%struct.X* %A) {
2037       //   tail call @bar(%struct.X* byval %A)
2038       // }
2039       return false;
2040     SDValue Ptr = Ld->getBasePtr();
2041     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2042     if (!FINode)
2043       return false;
2044     FI = FINode->getIndex();
2045   } else
2046     return false;
2047
2048   assert(FI != INT_MAX);
2049   if (!MFI->isFixedObjectIndex(FI))
2050     return false;
2051   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2052 }
2053
2054 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2055 /// for tail call optimization. Targets which want to do tail call
2056 /// optimization should implement this function.
2057 bool
2058 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2059                                                      CallingConv::ID CalleeCC,
2060                                                      bool isVarArg,
2061                                                      bool isCalleeStructRet,
2062                                                      bool isCallerStructRet,
2063                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2064                                     const SmallVectorImpl<SDValue> &OutVals,
2065                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2066                                                      SelectionDAG& DAG) const {
2067   const Function *CallerF = DAG.getMachineFunction().getFunction();
2068   CallingConv::ID CallerCC = CallerF->getCallingConv();
2069   bool CCMatch = CallerCC == CalleeCC;
2070
2071   assert(Subtarget->supportsTailCall());
2072
2073   // Look for obvious safe cases to perform tail call optimization that do not
2074   // require ABI changes. This is what gcc calls sibcall.
2075
2076   // Do not sibcall optimize vararg calls unless the call site is not passing
2077   // any arguments.
2078   if (isVarArg && !Outs.empty())
2079     return false;
2080
2081   // Exception-handling functions need a special set of instructions to indicate
2082   // a return to the hardware. Tail-calling another function would probably
2083   // break this.
2084   if (CallerF->hasFnAttribute("interrupt"))
2085     return false;
2086
2087   // Also avoid sibcall optimization if either caller or callee uses struct
2088   // return semantics.
2089   if (isCalleeStructRet || isCallerStructRet)
2090     return false;
2091
2092   // Externally-defined functions with weak linkage should not be
2093   // tail-called on ARM when the OS does not support dynamic
2094   // pre-emption of symbols, as the AAELF spec requires normal calls
2095   // to undefined weak functions to be replaced with a NOP or jump to the
2096   // next instruction. The behaviour of branch instructions in this
2097   // situation (as used for tail calls) is implementation-defined, so we
2098   // cannot rely on the linker replacing the tail call with a return.
2099   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2100     const GlobalValue *GV = G->getGlobal();
2101     const Triple &TT = getTargetMachine().getTargetTriple();
2102     if (GV->hasExternalWeakLinkage() &&
2103         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2104       return false;
2105   }
2106
2107   // If the calling conventions do not match, then we'd better make sure the
2108   // results are returned in the same way as what the caller expects.
2109   if (!CCMatch) {
2110     SmallVector<CCValAssign, 16> RVLocs1;
2111     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2112                        *DAG.getContext(), Call);
2113     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2114
2115     SmallVector<CCValAssign, 16> RVLocs2;
2116     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2117                        *DAG.getContext(), Call);
2118     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2119
2120     if (RVLocs1.size() != RVLocs2.size())
2121       return false;
2122     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2123       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2124         return false;
2125       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2126         return false;
2127       if (RVLocs1[i].isRegLoc()) {
2128         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2129           return false;
2130       } else {
2131         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2132           return false;
2133       }
2134     }
2135   }
2136
2137   // If Caller's vararg or byval argument has been split between registers and
2138   // stack, do not perform tail call, since part of the argument is in caller's
2139   // local frame.
2140   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2141                                       getInfo<ARMFunctionInfo>();
2142   if (AFI_Caller->getArgRegsSaveSize())
2143     return false;
2144
2145   // If the callee takes no arguments then go on to check the results of the
2146   // call.
2147   if (!Outs.empty()) {
2148     // Check if stack adjustment is needed. For now, do not do this if any
2149     // argument is passed on the stack.
2150     SmallVector<CCValAssign, 16> ArgLocs;
2151     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2152                       *DAG.getContext(), Call);
2153     CCInfo.AnalyzeCallOperands(Outs,
2154                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2155     if (CCInfo.getNextStackOffset()) {
2156       MachineFunction &MF = DAG.getMachineFunction();
2157
2158       // Check if the arguments are already laid out in the right way as
2159       // the caller's fixed stack objects.
2160       MachineFrameInfo *MFI = MF.getFrameInfo();
2161       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2162       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2163       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2164            i != e;
2165            ++i, ++realArgIdx) {
2166         CCValAssign &VA = ArgLocs[i];
2167         EVT RegVT = VA.getLocVT();
2168         SDValue Arg = OutVals[realArgIdx];
2169         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2170         if (VA.getLocInfo() == CCValAssign::Indirect)
2171           return false;
2172         if (VA.needsCustom()) {
2173           // f64 and vector types are split into multiple registers or
2174           // register/stack-slot combinations.  The types will not match
2175           // the registers; give up on memory f64 refs until we figure
2176           // out what to do about this.
2177           if (!VA.isRegLoc())
2178             return false;
2179           if (!ArgLocs[++i].isRegLoc())
2180             return false;
2181           if (RegVT == MVT::v2f64) {
2182             if (!ArgLocs[++i].isRegLoc())
2183               return false;
2184             if (!ArgLocs[++i].isRegLoc())
2185               return false;
2186           }
2187         } else if (!VA.isRegLoc()) {
2188           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2189                                    MFI, MRI, TII))
2190             return false;
2191         }
2192       }
2193     }
2194   }
2195
2196   return true;
2197 }
2198
2199 bool
2200 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2201                                   MachineFunction &MF, bool isVarArg,
2202                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2203                                   LLVMContext &Context) const {
2204   SmallVector<CCValAssign, 16> RVLocs;
2205   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2206   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2207                                                     isVarArg));
2208 }
2209
2210 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2211                                     SDLoc DL, SelectionDAG &DAG) {
2212   const MachineFunction &MF = DAG.getMachineFunction();
2213   const Function *F = MF.getFunction();
2214
2215   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2216
2217   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2218   // version of the "preferred return address". These offsets affect the return
2219   // instruction if this is a return from PL1 without hypervisor extensions.
2220   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2221   //    SWI:     0      "subs pc, lr, #0"
2222   //    ABORT:   +4     "subs pc, lr, #4"
2223   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2224   // UNDEF varies depending on where the exception came from ARM or Thumb
2225   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2226
2227   int64_t LROffset;
2228   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2229       IntKind == "ABORT")
2230     LROffset = 4;
2231   else if (IntKind == "SWI" || IntKind == "UNDEF")
2232     LROffset = 0;
2233   else
2234     report_fatal_error("Unsupported interrupt attribute. If present, value "
2235                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2236
2237   RetOps.insert(RetOps.begin() + 1,
2238                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2239
2240   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2241 }
2242
2243 SDValue
2244 ARMTargetLowering::LowerReturn(SDValue Chain,
2245                                CallingConv::ID CallConv, bool isVarArg,
2246                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2247                                const SmallVectorImpl<SDValue> &OutVals,
2248                                SDLoc dl, SelectionDAG &DAG) const {
2249
2250   // CCValAssign - represent the assignment of the return value to a location.
2251   SmallVector<CCValAssign, 16> RVLocs;
2252
2253   // CCState - Info about the registers and stack slots.
2254   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2255                     *DAG.getContext(), Call);
2256
2257   // Analyze outgoing return values.
2258   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2259                                                isVarArg));
2260
2261   SDValue Flag;
2262   SmallVector<SDValue, 4> RetOps;
2263   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2264   bool isLittleEndian = Subtarget->isLittle();
2265
2266   MachineFunction &MF = DAG.getMachineFunction();
2267   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2268   AFI->setReturnRegsCount(RVLocs.size());
2269
2270   // Copy the result values into the output registers.
2271   for (unsigned i = 0, realRVLocIdx = 0;
2272        i != RVLocs.size();
2273        ++i, ++realRVLocIdx) {
2274     CCValAssign &VA = RVLocs[i];
2275     assert(VA.isRegLoc() && "Can only return in registers!");
2276
2277     SDValue Arg = OutVals[realRVLocIdx];
2278
2279     switch (VA.getLocInfo()) {
2280     default: llvm_unreachable("Unknown loc info!");
2281     case CCValAssign::Full: break;
2282     case CCValAssign::BCvt:
2283       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2284       break;
2285     }
2286
2287     if (VA.needsCustom()) {
2288       if (VA.getLocVT() == MVT::v2f64) {
2289         // Extract the first half and return it in two registers.
2290         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2291                                    DAG.getConstant(0, dl, MVT::i32));
2292         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2293                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2294
2295         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2296                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2297                                  Flag);
2298         Flag = Chain.getValue(1);
2299         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2300         VA = RVLocs[++i]; // skip ahead to next loc
2301         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2302                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
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
2308         // Extract the 2nd half and fall through to handle it as an f64 value.
2309         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2310                           DAG.getConstant(1, dl, MVT::i32));
2311       }
2312       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2313       // available.
2314       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2315                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2316       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2317                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2318                                Flag);
2319       Flag = Chain.getValue(1);
2320       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2321       VA = RVLocs[++i]; // skip ahead to next loc
2322       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2323                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2324                                Flag);
2325     } else
2326       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2327
2328     // Guarantee that all emitted copies are
2329     // stuck together, avoiding something bad.
2330     Flag = Chain.getValue(1);
2331     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2332   }
2333
2334   // Update chain and glue.
2335   RetOps[0] = Chain;
2336   if (Flag.getNode())
2337     RetOps.push_back(Flag);
2338
2339   // CPUs which aren't M-class use a special sequence to return from
2340   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2341   // though we use "subs pc, lr, #N").
2342   //
2343   // M-class CPUs actually use a normal return sequence with a special
2344   // (hardware-provided) value in LR, so the normal code path works.
2345   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2346       !Subtarget->isMClass()) {
2347     if (Subtarget->isThumb1Only())
2348       report_fatal_error("interrupt attribute is not supported in Thumb1");
2349     return LowerInterruptReturn(RetOps, dl, DAG);
2350   }
2351
2352   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2353 }
2354
2355 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2356   if (N->getNumValues() != 1)
2357     return false;
2358   if (!N->hasNUsesOfValue(1, 0))
2359     return false;
2360
2361   SDValue TCChain = Chain;
2362   SDNode *Copy = *N->use_begin();
2363   if (Copy->getOpcode() == ISD::CopyToReg) {
2364     // If the copy has a glue operand, we conservatively assume it isn't safe to
2365     // perform a tail call.
2366     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2367       return false;
2368     TCChain = Copy->getOperand(0);
2369   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2370     SDNode *VMov = Copy;
2371     // f64 returned in a pair of GPRs.
2372     SmallPtrSet<SDNode*, 2> Copies;
2373     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2374          UI != UE; ++UI) {
2375       if (UI->getOpcode() != ISD::CopyToReg)
2376         return false;
2377       Copies.insert(*UI);
2378     }
2379     if (Copies.size() > 2)
2380       return false;
2381
2382     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2383          UI != UE; ++UI) {
2384       SDValue UseChain = UI->getOperand(0);
2385       if (Copies.count(UseChain.getNode()))
2386         // Second CopyToReg
2387         Copy = *UI;
2388       else {
2389         // We are at the top of this chain.
2390         // If the copy has a glue operand, we conservatively assume it
2391         // isn't safe to perform a tail call.
2392         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2393           return false;
2394         // First CopyToReg
2395         TCChain = UseChain;
2396       }
2397     }
2398   } else if (Copy->getOpcode() == ISD::BITCAST) {
2399     // f32 returned in a single GPR.
2400     if (!Copy->hasOneUse())
2401       return false;
2402     Copy = *Copy->use_begin();
2403     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2404       return false;
2405     // If the copy has a glue operand, we conservatively assume it isn't safe to
2406     // perform a tail call.
2407     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2408       return false;
2409     TCChain = Copy->getOperand(0);
2410   } else {
2411     return false;
2412   }
2413
2414   bool HasRet = false;
2415   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2416        UI != UE; ++UI) {
2417     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2418         UI->getOpcode() != ARMISD::INTRET_FLAG)
2419       return false;
2420     HasRet = true;
2421   }
2422
2423   if (!HasRet)
2424     return false;
2425
2426   Chain = TCChain;
2427   return true;
2428 }
2429
2430 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2431   if (!Subtarget->supportsTailCall())
2432     return false;
2433
2434   auto Attr =
2435       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2436   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2437     return false;
2438
2439   return true;
2440 }
2441
2442 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2443 // and pass the lower and high parts through.
2444 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2445   SDLoc DL(Op);
2446   SDValue WriteValue = Op->getOperand(2);
2447
2448   // This function is only supposed to be called for i64 type argument.
2449   assert(WriteValue.getValueType() == MVT::i64
2450           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2451
2452   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2453                            DAG.getConstant(0, DL, MVT::i32));
2454   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2455                            DAG.getConstant(1, DL, MVT::i32));
2456   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2457   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2458 }
2459
2460 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2461 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2462 // one of the above mentioned nodes. It has to be wrapped because otherwise
2463 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2464 // be used to form addressing mode. These wrapped nodes will be selected
2465 // into MOVi.
2466 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2467   EVT PtrVT = Op.getValueType();
2468   // FIXME there is no actual debug info here
2469   SDLoc dl(Op);
2470   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2471   SDValue Res;
2472   if (CP->isMachineConstantPoolEntry())
2473     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2474                                     CP->getAlignment());
2475   else
2476     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2477                                     CP->getAlignment());
2478   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2479 }
2480
2481 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2482   return MachineJumpTableInfo::EK_Inline;
2483 }
2484
2485 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2486                                              SelectionDAG &DAG) const {
2487   MachineFunction &MF = DAG.getMachineFunction();
2488   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2489   unsigned ARMPCLabelIndex = 0;
2490   SDLoc DL(Op);
2491   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2492   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2493   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2494   SDValue CPAddr;
2495   if (RelocM == Reloc::Static) {
2496     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2497   } else {
2498     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2499     ARMPCLabelIndex = AFI->createPICLabelUId();
2500     ARMConstantPoolValue *CPV =
2501       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2502                                       ARMCP::CPBlockAddress, PCAdj);
2503     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2504   }
2505   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2506   SDValue Result =
2507       DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2508                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2509                   false, false, false, 0);
2510   if (RelocM == Reloc::Static)
2511     return Result;
2512   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2513   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2514 }
2515
2516 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2517 SDValue
2518 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2519                                                  SelectionDAG &DAG) const {
2520   SDLoc dl(GA);
2521   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2522   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2523   MachineFunction &MF = DAG.getMachineFunction();
2524   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2525   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2526   ARMConstantPoolValue *CPV =
2527     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2528                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2529   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2530   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2531   Argument =
2532       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2533                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2534                   false, false, false, 0);
2535   SDValue Chain = Argument.getValue(1);
2536
2537   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2538   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2539
2540   // call __tls_get_addr.
2541   ArgListTy Args;
2542   ArgListEntry Entry;
2543   Entry.Node = Argument;
2544   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2545   Args.push_back(Entry);
2546
2547   // FIXME: is there useful debug info available here?
2548   TargetLowering::CallLoweringInfo CLI(DAG);
2549   CLI.setDebugLoc(dl).setChain(Chain)
2550     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2551                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2552                0);
2553
2554   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2555   return CallResult.first;
2556 }
2557
2558 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2559 // "local exec" model.
2560 SDValue
2561 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2562                                         SelectionDAG &DAG,
2563                                         TLSModel::Model model) const {
2564   const GlobalValue *GV = GA->getGlobal();
2565   SDLoc dl(GA);
2566   SDValue Offset;
2567   SDValue Chain = DAG.getEntryNode();
2568   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2569   // Get the Thread Pointer
2570   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2571
2572   if (model == TLSModel::InitialExec) {
2573     MachineFunction &MF = DAG.getMachineFunction();
2574     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2575     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2576     // Initial exec model.
2577     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2578     ARMConstantPoolValue *CPV =
2579       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2580                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2581                                       true);
2582     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2583     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2584     Offset = DAG.getLoad(
2585         PtrVT, dl, Chain, Offset,
2586         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2587         false, false, 0);
2588     Chain = Offset.getValue(1);
2589
2590     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2591     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2592
2593     Offset = DAG.getLoad(
2594         PtrVT, dl, Chain, Offset,
2595         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2596         false, false, 0);
2597   } else {
2598     // local exec model
2599     assert(model == TLSModel::LocalExec);
2600     ARMConstantPoolValue *CPV =
2601       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2602     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2603     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2604     Offset = DAG.getLoad(
2605         PtrVT, dl, Chain, Offset,
2606         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2607         false, false, 0);
2608   }
2609
2610   // The address of the thread local variable is the add of the thread
2611   // pointer with the offset of the variable.
2612   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2613 }
2614
2615 SDValue
2616 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2617   // TODO: implement the "local dynamic" model
2618   assert(Subtarget->isTargetELF() &&
2619          "TLS not implemented for non-ELF targets");
2620   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2621   if (DAG.getTarget().Options.EmulatedTLS)
2622     return LowerToTLSEmulatedModel(GA, DAG);
2623
2624   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2625
2626   switch (model) {
2627     case TLSModel::GeneralDynamic:
2628     case TLSModel::LocalDynamic:
2629       return LowerToTLSGeneralDynamicModel(GA, DAG);
2630     case TLSModel::InitialExec:
2631     case TLSModel::LocalExec:
2632       return LowerToTLSExecModels(GA, DAG, model);
2633   }
2634   llvm_unreachable("bogus TLS model");
2635 }
2636
2637 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2638                                                  SelectionDAG &DAG) const {
2639   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2640   SDLoc dl(Op);
2641   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2642   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2643     bool UseGOT_PREL =
2644         !(GV->hasHiddenVisibility() || GV->hasLocalLinkage());
2645
2646     MachineFunction &MF = DAG.getMachineFunction();
2647     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2648     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2649     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2650     SDLoc dl(Op);
2651     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2652     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2653         GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2654         UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2655         /*AddCurrentAddress=*/UseGOT_PREL);
2656     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2657     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2658     SDValue Result = DAG.getLoad(
2659         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2660         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2661         false, false, 0);
2662     SDValue Chain = Result.getValue(1);
2663     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2664     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2665     if (UseGOT_PREL)
2666       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2667                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2668                            false, false, false, 0);
2669     return Result;
2670   }
2671
2672   // If we have T2 ops, we can materialize the address directly via movt/movw
2673   // pair. This is always cheaper.
2674   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2675     ++NumMovwMovt;
2676     // FIXME: Once remat is capable of dealing with instructions with register
2677     // operands, expand this into two nodes.
2678     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2679                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2680   } else {
2681     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2682     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2683     return DAG.getLoad(
2684         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2685         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2686         false, false, 0);
2687   }
2688 }
2689
2690 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2691                                                     SelectionDAG &DAG) const {
2692   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2693   SDLoc dl(Op);
2694   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2695   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2696
2697   if (Subtarget->useMovt(DAG.getMachineFunction()))
2698     ++NumMovwMovt;
2699
2700   // FIXME: Once remat is capable of dealing with instructions with register
2701   // operands, expand this into multiple nodes
2702   unsigned Wrapper =
2703       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2704
2705   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2706   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2707
2708   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2709     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2710                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2711                          false, false, false, 0);
2712   return Result;
2713 }
2714
2715 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2716                                                      SelectionDAG &DAG) const {
2717   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2718   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2719          "Windows on ARM expects to use movw/movt");
2720
2721   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2722   const ARMII::TOF TargetFlags =
2723     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2724   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2725   SDValue Result;
2726   SDLoc DL(Op);
2727
2728   ++NumMovwMovt;
2729
2730   // FIXME: Once remat is capable of dealing with instructions with register
2731   // operands, expand this into two nodes.
2732   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2733                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2734                                                   TargetFlags));
2735   if (GV->hasDLLImportStorageClass())
2736     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2737                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2738                          false, false, false, 0);
2739   return Result;
2740 }
2741
2742 SDValue
2743 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2744   SDLoc dl(Op);
2745   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2746   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2747                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2748                      Op.getOperand(1), Val);
2749 }
2750
2751 SDValue
2752 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2753   SDLoc dl(Op);
2754   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2755                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2756 }
2757
2758 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2759                                                       SelectionDAG &DAG) const {
2760   SDLoc dl(Op);
2761   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2762                      Op.getOperand(0));
2763 }
2764
2765 SDValue
2766 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2767                                           const ARMSubtarget *Subtarget) const {
2768   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2769   SDLoc dl(Op);
2770   switch (IntNo) {
2771   default: return SDValue();    // Don't custom lower most intrinsics.
2772   case Intrinsic::arm_rbit: {
2773     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2774            "RBIT intrinsic must have i32 type!");
2775     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2776   }
2777   case Intrinsic::arm_thread_pointer: {
2778     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2779     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2780   }
2781   case Intrinsic::eh_sjlj_lsda: {
2782     MachineFunction &MF = DAG.getMachineFunction();
2783     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2784     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2785     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2786     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2787     SDValue CPAddr;
2788     unsigned PCAdj = (RelocM != Reloc::PIC_)
2789       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2790     ARMConstantPoolValue *CPV =
2791       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2792                                       ARMCP::CPLSDA, PCAdj);
2793     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2794     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2795     SDValue Result = DAG.getLoad(
2796         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2797         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2798         false, false, 0);
2799
2800     if (RelocM == Reloc::PIC_) {
2801       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2802       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2803     }
2804     return Result;
2805   }
2806   case Intrinsic::arm_neon_vmulls:
2807   case Intrinsic::arm_neon_vmullu: {
2808     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2809       ? ARMISD::VMULLs : ARMISD::VMULLu;
2810     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2811                        Op.getOperand(1), Op.getOperand(2));
2812   }
2813   case Intrinsic::arm_neon_vminnm:
2814   case Intrinsic::arm_neon_vmaxnm: {
2815     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2816       ? ISD::FMINNUM : ISD::FMAXNUM;
2817     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2818                        Op.getOperand(1), Op.getOperand(2));
2819   }
2820   case Intrinsic::arm_neon_vminu:
2821   case Intrinsic::arm_neon_vmaxu: {
2822     if (Op.getValueType().isFloatingPoint())
2823       return SDValue();
2824     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2825       ? ISD::UMIN : ISD::UMAX;
2826     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2827                          Op.getOperand(1), Op.getOperand(2));
2828   }
2829   case Intrinsic::arm_neon_vmins:
2830   case Intrinsic::arm_neon_vmaxs: {
2831     // v{min,max}s is overloaded between signed integers and floats.
2832     if (!Op.getValueType().isFloatingPoint()) {
2833       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2834         ? ISD::SMIN : ISD::SMAX;
2835       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2836                          Op.getOperand(1), Op.getOperand(2));
2837     }
2838     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2839       ? ISD::FMINNAN : ISD::FMAXNAN;
2840     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2841                        Op.getOperand(1), Op.getOperand(2));
2842   }
2843   }
2844 }
2845
2846 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2847                                  const ARMSubtarget *Subtarget) {
2848   // FIXME: handle "fence singlethread" more efficiently.
2849   SDLoc dl(Op);
2850   if (!Subtarget->hasDataBarrier()) {
2851     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2852     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2853     // here.
2854     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2855            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2856     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2857                        DAG.getConstant(0, dl, MVT::i32));
2858   }
2859
2860   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2861   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2862   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2863   if (Subtarget->isMClass()) {
2864     // Only a full system barrier exists in the M-class architectures.
2865     Domain = ARM_MB::SY;
2866   } else if (Subtarget->isSwift() && Ord == Release) {
2867     // Swift happens to implement ISHST barriers in a way that's compatible with
2868     // Release semantics but weaker than ISH so we'd be fools not to use
2869     // it. Beware: other processors probably don't!
2870     Domain = ARM_MB::ISHST;
2871   }
2872
2873   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2874                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2875                      DAG.getConstant(Domain, dl, MVT::i32));
2876 }
2877
2878 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2879                              const ARMSubtarget *Subtarget) {
2880   // ARM pre v5TE and Thumb1 does not have preload instructions.
2881   if (!(Subtarget->isThumb2() ||
2882         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2883     // Just preserve the chain.
2884     return Op.getOperand(0);
2885
2886   SDLoc dl(Op);
2887   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2888   if (!isRead &&
2889       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2890     // ARMv7 with MP extension has PLDW.
2891     return Op.getOperand(0);
2892
2893   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2894   if (Subtarget->isThumb()) {
2895     // Invert the bits.
2896     isRead = ~isRead & 1;
2897     isData = ~isData & 1;
2898   }
2899
2900   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2901                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2902                      DAG.getConstant(isData, dl, MVT::i32));
2903 }
2904
2905 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2906   MachineFunction &MF = DAG.getMachineFunction();
2907   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2908
2909   // vastart just stores the address of the VarArgsFrameIndex slot into the
2910   // memory location argument.
2911   SDLoc dl(Op);
2912   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2913   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2914   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2915   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2916                       MachinePointerInfo(SV), false, false, 0);
2917 }
2918
2919 SDValue
2920 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2921                                         SDValue &Root, SelectionDAG &DAG,
2922                                         SDLoc dl) const {
2923   MachineFunction &MF = DAG.getMachineFunction();
2924   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2925
2926   const TargetRegisterClass *RC;
2927   if (AFI->isThumb1OnlyFunction())
2928     RC = &ARM::tGPRRegClass;
2929   else
2930     RC = &ARM::GPRRegClass;
2931
2932   // Transform the arguments stored in physical registers into virtual ones.
2933   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2934   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2935
2936   SDValue ArgValue2;
2937   if (NextVA.isMemLoc()) {
2938     MachineFrameInfo *MFI = MF.getFrameInfo();
2939     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2940
2941     // Create load node to retrieve arguments from the stack.
2942     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2943     ArgValue2 = DAG.getLoad(
2944         MVT::i32, dl, Root, FIN,
2945         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2946         false, false, 0);
2947   } else {
2948     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2949     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2950   }
2951   if (!Subtarget->isLittle())
2952     std::swap (ArgValue, ArgValue2);
2953   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2954 }
2955
2956 // The remaining GPRs hold either the beginning of variable-argument
2957 // data, or the beginning of an aggregate passed by value (usually
2958 // byval).  Either way, we allocate stack slots adjacent to the data
2959 // provided by our caller, and store the unallocated registers there.
2960 // If this is a variadic function, the va_list pointer will begin with
2961 // these values; otherwise, this reassembles a (byval) structure that
2962 // was split between registers and memory.
2963 // Return: The frame index registers were stored into.
2964 int
2965 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2966                                   SDLoc dl, SDValue &Chain,
2967                                   const Value *OrigArg,
2968                                   unsigned InRegsParamRecordIdx,
2969                                   int ArgOffset,
2970                                   unsigned ArgSize) const {
2971   // Currently, two use-cases possible:
2972   // Case #1. Non-var-args function, and we meet first byval parameter.
2973   //          Setup first unallocated register as first byval register;
2974   //          eat all remained registers
2975   //          (these two actions are performed by HandleByVal method).
2976   //          Then, here, we initialize stack frame with
2977   //          "store-reg" instructions.
2978   // Case #2. Var-args function, that doesn't contain byval parameters.
2979   //          The same: eat all remained unallocated registers,
2980   //          initialize stack frame.
2981
2982   MachineFunction &MF = DAG.getMachineFunction();
2983   MachineFrameInfo *MFI = MF.getFrameInfo();
2984   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2985   unsigned RBegin, REnd;
2986   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2987     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2988   } else {
2989     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2990     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2991     REnd = ARM::R4;
2992   }
2993
2994   if (REnd != RBegin)
2995     ArgOffset = -4 * (ARM::R4 - RBegin);
2996
2997   auto PtrVT = getPointerTy(DAG.getDataLayout());
2998   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2999   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3000
3001   SmallVector<SDValue, 4> MemOps;
3002   const TargetRegisterClass *RC =
3003       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3004
3005   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3006     unsigned VReg = MF.addLiveIn(Reg, RC);
3007     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3008     SDValue Store =
3009         DAG.getStore(Val.getValue(1), dl, Val, FIN,
3010                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3011     MemOps.push_back(Store);
3012     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3013   }
3014
3015   if (!MemOps.empty())
3016     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3017   return FrameIndex;
3018 }
3019
3020 // Setup stack frame, the va_list pointer will start from.
3021 void
3022 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3023                                         SDLoc dl, SDValue &Chain,
3024                                         unsigned ArgOffset,
3025                                         unsigned TotalArgRegsSaveSize,
3026                                         bool ForceMutable) const {
3027   MachineFunction &MF = DAG.getMachineFunction();
3028   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3029
3030   // Try to store any remaining integer argument regs
3031   // to their spots on the stack so that they may be loaded by deferencing
3032   // the result of va_next.
3033   // If there is no regs to be stored, just point address after last
3034   // argument passed via stack.
3035   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3036                                   CCInfo.getInRegsParamsCount(),
3037                                   CCInfo.getNextStackOffset(), 4);
3038   AFI->setVarArgsFrameIndex(FrameIndex);
3039 }
3040
3041 SDValue
3042 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3043                                         CallingConv::ID CallConv, bool isVarArg,
3044                                         const SmallVectorImpl<ISD::InputArg>
3045                                           &Ins,
3046                                         SDLoc dl, SelectionDAG &DAG,
3047                                         SmallVectorImpl<SDValue> &InVals)
3048                                           const {
3049   MachineFunction &MF = DAG.getMachineFunction();
3050   MachineFrameInfo *MFI = MF.getFrameInfo();
3051
3052   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3053
3054   // Assign locations to all of the incoming arguments.
3055   SmallVector<CCValAssign, 16> ArgLocs;
3056   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3057                     *DAG.getContext(), Prologue);
3058   CCInfo.AnalyzeFormalArguments(Ins,
3059                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3060                                                   isVarArg));
3061
3062   SmallVector<SDValue, 16> ArgValues;
3063   SDValue ArgValue;
3064   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3065   unsigned CurArgIdx = 0;
3066
3067   // Initially ArgRegsSaveSize is zero.
3068   // Then we increase this value each time we meet byval parameter.
3069   // We also increase this value in case of varargs function.
3070   AFI->setArgRegsSaveSize(0);
3071
3072   // Calculate the amount of stack space that we need to allocate to store
3073   // byval and variadic arguments that are passed in registers.
3074   // We need to know this before we allocate the first byval or variadic
3075   // argument, as they will be allocated a stack slot below the CFA (Canonical
3076   // Frame Address, the stack pointer at entry to the function).
3077   unsigned ArgRegBegin = ARM::R4;
3078   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3079     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3080       break;
3081
3082     CCValAssign &VA = ArgLocs[i];
3083     unsigned Index = VA.getValNo();
3084     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3085     if (!Flags.isByVal())
3086       continue;
3087
3088     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3089     unsigned RBegin, REnd;
3090     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3091     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3092
3093     CCInfo.nextInRegsParam();
3094   }
3095   CCInfo.rewindByValRegsInfo();
3096
3097   int lastInsIndex = -1;
3098   if (isVarArg && MFI->hasVAStart()) {
3099     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3100     if (RegIdx != array_lengthof(GPRArgRegs))
3101       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3102   }
3103
3104   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3105   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3106   auto PtrVT = getPointerTy(DAG.getDataLayout());
3107
3108   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3109     CCValAssign &VA = ArgLocs[i];
3110     if (Ins[VA.getValNo()].isOrigArg()) {
3111       std::advance(CurOrigArg,
3112                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3113       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3114     }
3115     // Arguments stored in registers.
3116     if (VA.isRegLoc()) {
3117       EVT RegVT = VA.getLocVT();
3118
3119       if (VA.needsCustom()) {
3120         // f64 and vector types are split up into multiple registers or
3121         // combinations of registers and stack slots.
3122         if (VA.getLocVT() == MVT::v2f64) {
3123           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3124                                                    Chain, DAG, dl);
3125           VA = ArgLocs[++i]; // skip ahead to next loc
3126           SDValue ArgValue2;
3127           if (VA.isMemLoc()) {
3128             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3129             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3130             ArgValue2 = DAG.getLoad(
3131                 MVT::f64, dl, Chain, FIN,
3132                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3133                 false, false, false, 0);
3134           } else {
3135             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3136                                              Chain, DAG, dl);
3137           }
3138           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3139           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3140                                  ArgValue, ArgValue1,
3141                                  DAG.getIntPtrConstant(0, dl));
3142           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3143                                  ArgValue, ArgValue2,
3144                                  DAG.getIntPtrConstant(1, dl));
3145         } else
3146           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3147
3148       } else {
3149         const TargetRegisterClass *RC;
3150
3151         if (RegVT == MVT::f32)
3152           RC = &ARM::SPRRegClass;
3153         else if (RegVT == MVT::f64)
3154           RC = &ARM::DPRRegClass;
3155         else if (RegVT == MVT::v2f64)
3156           RC = &ARM::QPRRegClass;
3157         else if (RegVT == MVT::i32)
3158           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3159                                            : &ARM::GPRRegClass;
3160         else
3161           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3162
3163         // Transform the arguments in physical registers into virtual ones.
3164         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3165         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3166       }
3167
3168       // If this is an 8 or 16-bit value, it is really passed promoted
3169       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3170       // truncate to the right size.
3171       switch (VA.getLocInfo()) {
3172       default: llvm_unreachable("Unknown loc info!");
3173       case CCValAssign::Full: break;
3174       case CCValAssign::BCvt:
3175         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3176         break;
3177       case CCValAssign::SExt:
3178         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3179                                DAG.getValueType(VA.getValVT()));
3180         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3181         break;
3182       case CCValAssign::ZExt:
3183         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3184                                DAG.getValueType(VA.getValVT()));
3185         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3186         break;
3187       }
3188
3189       InVals.push_back(ArgValue);
3190
3191     } else { // VA.isRegLoc()
3192
3193       // sanity check
3194       assert(VA.isMemLoc());
3195       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3196
3197       int index = VA.getValNo();
3198
3199       // Some Ins[] entries become multiple ArgLoc[] entries.
3200       // Process them only once.
3201       if (index != lastInsIndex)
3202         {
3203           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3204           // FIXME: For now, all byval parameter objects are marked mutable.
3205           // This can be changed with more analysis.
3206           // In case of tail call optimization mark all arguments mutable.
3207           // Since they could be overwritten by lowering of arguments in case of
3208           // a tail call.
3209           if (Flags.isByVal()) {
3210             assert(Ins[index].isOrigArg() &&
3211                    "Byval arguments cannot be implicit");
3212             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3213
3214             int FrameIndex = StoreByValRegs(
3215                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3216                 VA.getLocMemOffset(), Flags.getByValSize());
3217             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3218             CCInfo.nextInRegsParam();
3219           } else {
3220             unsigned FIOffset = VA.getLocMemOffset();
3221             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3222                                             FIOffset, true);
3223
3224             // Create load nodes to retrieve arguments from the stack.
3225             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3226             InVals.push_back(DAG.getLoad(
3227                 VA.getValVT(), dl, Chain, FIN,
3228                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3229                 false, false, false, 0));
3230           }
3231           lastInsIndex = index;
3232         }
3233     }
3234   }
3235
3236   // varargs
3237   if (isVarArg && MFI->hasVAStart())
3238     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3239                          CCInfo.getNextStackOffset(),
3240                          TotalArgRegsSaveSize);
3241
3242   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3243
3244   return Chain;
3245 }
3246
3247 /// isFloatingPointZero - Return true if this is +0.0.
3248 static bool isFloatingPointZero(SDValue Op) {
3249   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3250     return CFP->getValueAPF().isPosZero();
3251   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3252     // Maybe this has already been legalized into the constant pool?
3253     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3254       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3255       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3256         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3257           return CFP->getValueAPF().isPosZero();
3258     }
3259   } else if (Op->getOpcode() == ISD::BITCAST &&
3260              Op->getValueType(0) == MVT::f64) {
3261     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3262     // created by LowerConstantFP().
3263     SDValue BitcastOp = Op->getOperand(0);
3264     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3265       SDValue MoveOp = BitcastOp->getOperand(0);
3266       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3267           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3268         return true;
3269       }
3270     }
3271   }
3272   return false;
3273 }
3274
3275 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3276 /// the given operands.
3277 SDValue
3278 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3279                              SDValue &ARMcc, SelectionDAG &DAG,
3280                              SDLoc dl) const {
3281   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3282     unsigned C = RHSC->getZExtValue();
3283     if (!isLegalICmpImmediate(C)) {
3284       // Constant does not fit, try adjusting it by one?
3285       switch (CC) {
3286       default: break;
3287       case ISD::SETLT:
3288       case ISD::SETGE:
3289         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3290           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3291           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3292         }
3293         break;
3294       case ISD::SETULT:
3295       case ISD::SETUGE:
3296         if (C != 0 && isLegalICmpImmediate(C-1)) {
3297           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3298           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3299         }
3300         break;
3301       case ISD::SETLE:
3302       case ISD::SETGT:
3303         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3304           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3305           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3306         }
3307         break;
3308       case ISD::SETULE:
3309       case ISD::SETUGT:
3310         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3311           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3312           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3313         }
3314         break;
3315       }
3316     }
3317   }
3318
3319   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3320   ARMISD::NodeType CompareType;
3321   switch (CondCode) {
3322   default:
3323     CompareType = ARMISD::CMP;
3324     break;
3325   case ARMCC::EQ:
3326   case ARMCC::NE:
3327     // Uses only Z Flag
3328     CompareType = ARMISD::CMPZ;
3329     break;
3330   }
3331   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3332   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3333 }
3334
3335 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3336 SDValue
3337 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3338                              SDLoc dl) const {
3339   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3340   SDValue Cmp;
3341   if (!isFloatingPointZero(RHS))
3342     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3343   else
3344     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3345   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3346 }
3347
3348 /// duplicateCmp - Glue values can have only one use, so this function
3349 /// duplicates a comparison node.
3350 SDValue
3351 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3352   unsigned Opc = Cmp.getOpcode();
3353   SDLoc DL(Cmp);
3354   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3355     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3356
3357   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3358   Cmp = Cmp.getOperand(0);
3359   Opc = Cmp.getOpcode();
3360   if (Opc == ARMISD::CMPFP)
3361     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3362   else {
3363     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3364     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3365   }
3366   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3367 }
3368
3369 std::pair<SDValue, SDValue>
3370 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3371                                  SDValue &ARMcc) const {
3372   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3373
3374   SDValue Value, OverflowCmp;
3375   SDValue LHS = Op.getOperand(0);
3376   SDValue RHS = Op.getOperand(1);
3377   SDLoc dl(Op);
3378
3379   // FIXME: We are currently always generating CMPs because we don't support
3380   // generating CMN through the backend. This is not as good as the natural
3381   // CMP case because it causes a register dependency and cannot be folded
3382   // later.
3383
3384   switch (Op.getOpcode()) {
3385   default:
3386     llvm_unreachable("Unknown overflow instruction!");
3387   case ISD::SADDO:
3388     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3389     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3390     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3391     break;
3392   case ISD::UADDO:
3393     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3394     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3395     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3396     break;
3397   case ISD::SSUBO:
3398     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3399     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3400     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3401     break;
3402   case ISD::USUBO:
3403     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3404     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3405     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3406     break;
3407   } // switch (...)
3408
3409   return std::make_pair(Value, OverflowCmp);
3410 }
3411
3412
3413 SDValue
3414 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3415   // Let legalize expand this if it isn't a legal type yet.
3416   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3417     return SDValue();
3418
3419   SDValue Value, OverflowCmp;
3420   SDValue ARMcc;
3421   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3422   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3423   SDLoc dl(Op);
3424   // We use 0 and 1 as false and true values.
3425   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3426   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3427   EVT VT = Op.getValueType();
3428
3429   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3430                                  ARMcc, CCR, OverflowCmp);
3431
3432   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3433   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3434 }
3435
3436
3437 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3438   SDValue Cond = Op.getOperand(0);
3439   SDValue SelectTrue = Op.getOperand(1);
3440   SDValue SelectFalse = Op.getOperand(2);
3441   SDLoc dl(Op);
3442   unsigned Opc = Cond.getOpcode();
3443
3444   if (Cond.getResNo() == 1 &&
3445       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3446        Opc == ISD::USUBO)) {
3447     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3448       return SDValue();
3449
3450     SDValue Value, OverflowCmp;
3451     SDValue ARMcc;
3452     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3453     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3454     EVT VT = Op.getValueType();
3455
3456     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3457                    OverflowCmp, DAG);
3458   }
3459
3460   // Convert:
3461   //
3462   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3463   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3464   //
3465   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3466     const ConstantSDNode *CMOVTrue =
3467       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3468     const ConstantSDNode *CMOVFalse =
3469       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3470
3471     if (CMOVTrue && CMOVFalse) {
3472       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3473       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3474
3475       SDValue True;
3476       SDValue False;
3477       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3478         True = SelectTrue;
3479         False = SelectFalse;
3480       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3481         True = SelectFalse;
3482         False = SelectTrue;
3483       }
3484
3485       if (True.getNode() && False.getNode()) {
3486         EVT VT = Op.getValueType();
3487         SDValue ARMcc = Cond.getOperand(2);
3488         SDValue CCR = Cond.getOperand(3);
3489         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3490         assert(True.getValueType() == VT);
3491         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3492       }
3493     }
3494   }
3495
3496   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3497   // undefined bits before doing a full-word comparison with zero.
3498   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3499                      DAG.getConstant(1, dl, Cond.getValueType()));
3500
3501   return DAG.getSelectCC(dl, Cond,
3502                          DAG.getConstant(0, dl, Cond.getValueType()),
3503                          SelectTrue, SelectFalse, ISD::SETNE);
3504 }
3505
3506 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3507                                  bool &swpCmpOps, bool &swpVselOps) {
3508   // Start by selecting the GE condition code for opcodes that return true for
3509   // 'equality'
3510   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3511       CC == ISD::SETULE)
3512     CondCode = ARMCC::GE;
3513
3514   // and GT for opcodes that return false for 'equality'.
3515   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3516            CC == ISD::SETULT)
3517     CondCode = ARMCC::GT;
3518
3519   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3520   // to swap the compare operands.
3521   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3522       CC == ISD::SETULT)
3523     swpCmpOps = true;
3524
3525   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3526   // If we have an unordered opcode, we need to swap the operands to the VSEL
3527   // instruction (effectively negating the condition).
3528   //
3529   // This also has the effect of swapping which one of 'less' or 'greater'
3530   // returns true, so we also swap the compare operands. It also switches
3531   // whether we return true for 'equality', so we compensate by picking the
3532   // opposite condition code to our original choice.
3533   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3534       CC == ISD::SETUGT) {
3535     swpCmpOps = !swpCmpOps;
3536     swpVselOps = !swpVselOps;
3537     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3538   }
3539
3540   // 'ordered' is 'anything but unordered', so use the VS condition code and
3541   // swap the VSEL operands.
3542   if (CC == ISD::SETO) {
3543     CondCode = ARMCC::VS;
3544     swpVselOps = true;
3545   }
3546
3547   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3548   // code and swap the VSEL operands.
3549   if (CC == ISD::SETUNE) {
3550     CondCode = ARMCC::EQ;
3551     swpVselOps = true;
3552   }
3553 }
3554
3555 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3556                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3557                                    SDValue Cmp, SelectionDAG &DAG) const {
3558   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3559     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3560                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3561     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3562                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3563
3564     SDValue TrueLow = TrueVal.getValue(0);
3565     SDValue TrueHigh = TrueVal.getValue(1);
3566     SDValue FalseLow = FalseVal.getValue(0);
3567     SDValue FalseHigh = FalseVal.getValue(1);
3568
3569     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3570                               ARMcc, CCR, Cmp);
3571     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3572                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3573
3574     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3575   } else {
3576     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3577                        Cmp);
3578   }
3579 }
3580
3581 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3582   EVT VT = Op.getValueType();
3583   SDValue LHS = Op.getOperand(0);
3584   SDValue RHS = Op.getOperand(1);
3585   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3586   SDValue TrueVal = Op.getOperand(2);
3587   SDValue FalseVal = Op.getOperand(3);
3588   SDLoc dl(Op);
3589
3590   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3591     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3592                                                     dl);
3593
3594     // If softenSetCCOperands only returned one value, we should compare it to
3595     // zero.
3596     if (!RHS.getNode()) {
3597       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3598       CC = ISD::SETNE;
3599     }
3600   }
3601
3602   if (LHS.getValueType() == MVT::i32) {
3603     // Try to generate VSEL on ARMv8.
3604     // The VSEL instruction can't use all the usual ARM condition
3605     // codes: it only has two bits to select the condition code, so it's
3606     // constrained to use only GE, GT, VS and EQ.
3607     //
3608     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3609     // swap the operands of the previous compare instruction (effectively
3610     // inverting the compare condition, swapping 'less' and 'greater') and
3611     // sometimes need to swap the operands to the VSEL (which inverts the
3612     // condition in the sense of firing whenever the previous condition didn't)
3613     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3614                                     TrueVal.getValueType() == MVT::f64)) {
3615       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3616       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3617           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3618         CC = ISD::getSetCCInverse(CC, true);
3619         std::swap(TrueVal, FalseVal);
3620       }
3621     }
3622
3623     SDValue ARMcc;
3624     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3625     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3626     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3627   }
3628
3629   ARMCC::CondCodes CondCode, CondCode2;
3630   FPCCToARMCC(CC, CondCode, CondCode2);
3631
3632   // Try to generate VMAXNM/VMINNM on ARMv8.
3633   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3634                                   TrueVal.getValueType() == MVT::f64)) {
3635     bool swpCmpOps = false;
3636     bool swpVselOps = false;
3637     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3638
3639     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3640         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3641       if (swpCmpOps)
3642         std::swap(LHS, RHS);
3643       if (swpVselOps)
3644         std::swap(TrueVal, FalseVal);
3645     }
3646   }
3647
3648   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3649   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3650   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3651   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3652   if (CondCode2 != ARMCC::AL) {
3653     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3654     // FIXME: Needs another CMP because flag can have but one use.
3655     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3656     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3657   }
3658   return Result;
3659 }
3660
3661 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3662 /// to morph to an integer compare sequence.
3663 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3664                            const ARMSubtarget *Subtarget) {
3665   SDNode *N = Op.getNode();
3666   if (!N->hasOneUse())
3667     // Otherwise it requires moving the value from fp to integer registers.
3668     return false;
3669   if (!N->getNumValues())
3670     return false;
3671   EVT VT = Op.getValueType();
3672   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3673     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3674     // vmrs are very slow, e.g. cortex-a8.
3675     return false;
3676
3677   if (isFloatingPointZero(Op)) {
3678     SeenZero = true;
3679     return true;
3680   }
3681   return ISD::isNormalLoad(N);
3682 }
3683
3684 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3685   if (isFloatingPointZero(Op))
3686     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3687
3688   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3689     return DAG.getLoad(MVT::i32, SDLoc(Op),
3690                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3691                        Ld->isVolatile(), Ld->isNonTemporal(),
3692                        Ld->isInvariant(), Ld->getAlignment());
3693
3694   llvm_unreachable("Unknown VFP cmp argument!");
3695 }
3696
3697 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3698                            SDValue &RetVal1, SDValue &RetVal2) {
3699   SDLoc dl(Op);
3700
3701   if (isFloatingPointZero(Op)) {
3702     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3703     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3704     return;
3705   }
3706
3707   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3708     SDValue Ptr = Ld->getBasePtr();
3709     RetVal1 = DAG.getLoad(MVT::i32, dl,
3710                           Ld->getChain(), Ptr,
3711                           Ld->getPointerInfo(),
3712                           Ld->isVolatile(), Ld->isNonTemporal(),
3713                           Ld->isInvariant(), Ld->getAlignment());
3714
3715     EVT PtrType = Ptr.getValueType();
3716     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3717     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3718                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3719     RetVal2 = DAG.getLoad(MVT::i32, dl,
3720                           Ld->getChain(), NewPtr,
3721                           Ld->getPointerInfo().getWithOffset(4),
3722                           Ld->isVolatile(), Ld->isNonTemporal(),
3723                           Ld->isInvariant(), NewAlign);
3724     return;
3725   }
3726
3727   llvm_unreachable("Unknown VFP cmp argument!");
3728 }
3729
3730 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3731 /// f32 and even f64 comparisons to integer ones.
3732 SDValue
3733 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3734   SDValue Chain = Op.getOperand(0);
3735   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3736   SDValue LHS = Op.getOperand(2);
3737   SDValue RHS = Op.getOperand(3);
3738   SDValue Dest = Op.getOperand(4);
3739   SDLoc dl(Op);
3740
3741   bool LHSSeenZero = false;
3742   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3743   bool RHSSeenZero = false;
3744   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3745   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3746     // If unsafe fp math optimization is enabled and there are no other uses of
3747     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3748     // to an integer comparison.
3749     if (CC == ISD::SETOEQ)
3750       CC = ISD::SETEQ;
3751     else if (CC == ISD::SETUNE)
3752       CC = ISD::SETNE;
3753
3754     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3755     SDValue ARMcc;
3756     if (LHS.getValueType() == MVT::f32) {
3757       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3758                         bitcastf32Toi32(LHS, DAG), Mask);
3759       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3760                         bitcastf32Toi32(RHS, DAG), Mask);
3761       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3762       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3763       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3764                          Chain, Dest, ARMcc, CCR, Cmp);
3765     }
3766
3767     SDValue LHS1, LHS2;
3768     SDValue RHS1, RHS2;
3769     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3770     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3771     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3772     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3773     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3774     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3775     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3776     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3777     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3778   }
3779
3780   return SDValue();
3781 }
3782
3783 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3784   SDValue Chain = Op.getOperand(0);
3785   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3786   SDValue LHS = Op.getOperand(2);
3787   SDValue RHS = Op.getOperand(3);
3788   SDValue Dest = Op.getOperand(4);
3789   SDLoc dl(Op);
3790
3791   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3792     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3793                                                     dl);
3794
3795     // If softenSetCCOperands only returned one value, we should compare it to
3796     // zero.
3797     if (!RHS.getNode()) {
3798       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3799       CC = ISD::SETNE;
3800     }
3801   }
3802
3803   if (LHS.getValueType() == MVT::i32) {
3804     SDValue ARMcc;
3805     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3806     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3807     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3808                        Chain, Dest, ARMcc, CCR, Cmp);
3809   }
3810
3811   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3812
3813   if (getTargetMachine().Options.UnsafeFPMath &&
3814       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3815        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3816     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3817     if (Result.getNode())
3818       return Result;
3819   }
3820
3821   ARMCC::CondCodes CondCode, CondCode2;
3822   FPCCToARMCC(CC, CondCode, CondCode2);
3823
3824   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3825   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3826   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3827   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3828   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3829   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3830   if (CondCode2 != ARMCC::AL) {
3831     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3832     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3833     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3834   }
3835   return Res;
3836 }
3837
3838 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3839   SDValue Chain = Op.getOperand(0);
3840   SDValue Table = Op.getOperand(1);
3841   SDValue Index = Op.getOperand(2);
3842   SDLoc dl(Op);
3843
3844   EVT PTy = getPointerTy(DAG.getDataLayout());
3845   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3846   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3847   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3848   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3849   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3850   if (Subtarget->isThumb2()) {
3851     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3852     // which does another jump to the destination. This also makes it easier
3853     // to translate it to TBB / TBH later.
3854     // FIXME: This might not work if the function is extremely large.
3855     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3856                        Addr, Op.getOperand(2), JTI);
3857   }
3858   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3859     Addr =
3860         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3861                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3862                     false, false, false, 0);
3863     Chain = Addr.getValue(1);
3864     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3865     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3866   } else {
3867     Addr =
3868         DAG.getLoad(PTy, dl, Chain, Addr,
3869                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3870                     false, false, false, 0);
3871     Chain = Addr.getValue(1);
3872     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3873   }
3874 }
3875
3876 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3877   EVT VT = Op.getValueType();
3878   SDLoc dl(Op);
3879
3880   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3881     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3882       return Op;
3883     return DAG.UnrollVectorOp(Op.getNode());
3884   }
3885
3886   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3887          "Invalid type for custom lowering!");
3888   if (VT != MVT::v4i16)
3889     return DAG.UnrollVectorOp(Op.getNode());
3890
3891   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3892   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3893 }
3894
3895 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3896   EVT VT = Op.getValueType();
3897   if (VT.isVector())
3898     return LowerVectorFP_TO_INT(Op, DAG);
3899   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3900     RTLIB::Libcall LC;
3901     if (Op.getOpcode() == ISD::FP_TO_SINT)
3902       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3903                               Op.getValueType());
3904     else
3905       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3906                               Op.getValueType());
3907     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3908                        /*isSigned*/ false, SDLoc(Op)).first;
3909   }
3910
3911   return Op;
3912 }
3913
3914 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3915   EVT VT = Op.getValueType();
3916   SDLoc dl(Op);
3917
3918   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3919     if (VT.getVectorElementType() == MVT::f32)
3920       return Op;
3921     return DAG.UnrollVectorOp(Op.getNode());
3922   }
3923
3924   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3925          "Invalid type for custom lowering!");
3926   if (VT != MVT::v4f32)
3927     return DAG.UnrollVectorOp(Op.getNode());
3928
3929   unsigned CastOpc;
3930   unsigned Opc;
3931   switch (Op.getOpcode()) {
3932   default: llvm_unreachable("Invalid opcode!");
3933   case ISD::SINT_TO_FP:
3934     CastOpc = ISD::SIGN_EXTEND;
3935     Opc = ISD::SINT_TO_FP;
3936     break;
3937   case ISD::UINT_TO_FP:
3938     CastOpc = ISD::ZERO_EXTEND;
3939     Opc = ISD::UINT_TO_FP;
3940     break;
3941   }
3942
3943   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3944   return DAG.getNode(Opc, dl, VT, Op);
3945 }
3946
3947 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3948   EVT VT = Op.getValueType();
3949   if (VT.isVector())
3950     return LowerVectorINT_TO_FP(Op, DAG);
3951   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3952     RTLIB::Libcall LC;
3953     if (Op.getOpcode() == ISD::SINT_TO_FP)
3954       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3955                               Op.getValueType());
3956     else
3957       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3958                               Op.getValueType());
3959     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3960                        /*isSigned*/ false, SDLoc(Op)).first;
3961   }
3962
3963   return Op;
3964 }
3965
3966 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3967   // Implement fcopysign with a fabs and a conditional fneg.
3968   SDValue Tmp0 = Op.getOperand(0);
3969   SDValue Tmp1 = Op.getOperand(1);
3970   SDLoc dl(Op);
3971   EVT VT = Op.getValueType();
3972   EVT SrcVT = Tmp1.getValueType();
3973   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3974     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3975   bool UseNEON = !InGPR && Subtarget->hasNEON();
3976
3977   if (UseNEON) {
3978     // Use VBSL to copy the sign bit.
3979     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3980     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3981                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3982     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3983     if (VT == MVT::f64)
3984       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3985                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3986                          DAG.getConstant(32, dl, MVT::i32));
3987     else /*if (VT == MVT::f32)*/
3988       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3989     if (SrcVT == MVT::f32) {
3990       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3991       if (VT == MVT::f64)
3992         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3993                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3994                            DAG.getConstant(32, dl, MVT::i32));
3995     } else if (VT == MVT::f32)
3996       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3997                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3998                          DAG.getConstant(32, dl, MVT::i32));
3999     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4000     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4001
4002     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4003                                             dl, MVT::i32);
4004     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4005     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4006                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4007
4008     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4009                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4010                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4011     if (VT == MVT::f32) {
4012       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4013       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4014                         DAG.getConstant(0, dl, MVT::i32));
4015     } else {
4016       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4017     }
4018
4019     return Res;
4020   }
4021
4022   // Bitcast operand 1 to i32.
4023   if (SrcVT == MVT::f64)
4024     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4025                        Tmp1).getValue(1);
4026   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4027
4028   // Or in the signbit with integer operations.
4029   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4030   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4031   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4032   if (VT == MVT::f32) {
4033     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4034                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4035     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4036                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4037   }
4038
4039   // f64: Or the high part with signbit and then combine two parts.
4040   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4041                      Tmp0);
4042   SDValue Lo = Tmp0.getValue(0);
4043   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4044   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4045   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4046 }
4047
4048 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4049   MachineFunction &MF = DAG.getMachineFunction();
4050   MachineFrameInfo *MFI = MF.getFrameInfo();
4051   MFI->setReturnAddressIsTaken(true);
4052
4053   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4054     return SDValue();
4055
4056   EVT VT = Op.getValueType();
4057   SDLoc dl(Op);
4058   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4059   if (Depth) {
4060     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4061     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4062     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4063                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4064                        MachinePointerInfo(), false, false, false, 0);
4065   }
4066
4067   // Return LR, which contains the return address. Mark it an implicit live-in.
4068   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4069   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4070 }
4071
4072 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4073   const ARMBaseRegisterInfo &ARI =
4074     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4075   MachineFunction &MF = DAG.getMachineFunction();
4076   MachineFrameInfo *MFI = MF.getFrameInfo();
4077   MFI->setFrameAddressIsTaken(true);
4078
4079   EVT VT = Op.getValueType();
4080   SDLoc dl(Op);  // FIXME probably not meaningful
4081   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4082   unsigned FrameReg = ARI.getFrameRegister(MF);
4083   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4084   while (Depth--)
4085     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4086                             MachinePointerInfo(),
4087                             false, false, false, 0);
4088   return FrameAddr;
4089 }
4090
4091 // FIXME? Maybe this could be a TableGen attribute on some registers and
4092 // this table could be generated automatically from RegInfo.
4093 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4094                                               SelectionDAG &DAG) const {
4095   unsigned Reg = StringSwitch<unsigned>(RegName)
4096                        .Case("sp", ARM::SP)
4097                        .Default(0);
4098   if (Reg)
4099     return Reg;
4100   report_fatal_error(Twine("Invalid register name \""
4101                               + StringRef(RegName)  + "\"."));
4102 }
4103
4104 // Result is 64 bit value so split into two 32 bit values and return as a
4105 // pair of values.
4106 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4107                                 SelectionDAG &DAG) {
4108   SDLoc DL(N);
4109
4110   // This function is only supposed to be called for i64 type destination.
4111   assert(N->getValueType(0) == MVT::i64
4112           && "ExpandREAD_REGISTER called for non-i64 type result.");
4113
4114   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4115                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4116                              N->getOperand(0),
4117                              N->getOperand(1));
4118
4119   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4120                     Read.getValue(1)));
4121   Results.push_back(Read.getOperand(0));
4122 }
4123
4124 /// ExpandBITCAST - If the target supports VFP, this function is called to
4125 /// expand a bit convert where either the source or destination type is i64 to
4126 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4127 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4128 /// vectors), since the legalizer won't know what to do with that.
4129 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4130   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4131   SDLoc dl(N);
4132   SDValue Op = N->getOperand(0);
4133
4134   // This function is only supposed to be called for i64 types, either as the
4135   // source or destination of the bit convert.
4136   EVT SrcVT = Op.getValueType();
4137   EVT DstVT = N->getValueType(0);
4138   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4139          "ExpandBITCAST called for non-i64 type");
4140
4141   // Turn i64->f64 into VMOVDRR.
4142   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4143     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4144                              DAG.getConstant(0, dl, MVT::i32));
4145     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4146                              DAG.getConstant(1, dl, MVT::i32));
4147     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4148                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4149   }
4150
4151   // Turn f64->i64 into VMOVRRD.
4152   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4153     SDValue Cvt;
4154     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4155         SrcVT.getVectorNumElements() > 1)
4156       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4157                         DAG.getVTList(MVT::i32, MVT::i32),
4158                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4159     else
4160       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4161                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4162     // Merge the pieces into a single i64 value.
4163     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4164   }
4165
4166   return SDValue();
4167 }
4168
4169 /// getZeroVector - Returns a vector of specified type with all zero elements.
4170 /// Zero vectors are used to represent vector negation and in those cases
4171 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4172 /// not support i64 elements, so sometimes the zero vectors will need to be
4173 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4174 /// zero vector.
4175 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4176   assert(VT.isVector() && "Expected a vector type");
4177   // The canonical modified immediate encoding of a zero vector is....0!
4178   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4179   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4180   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4181   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4182 }
4183
4184 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4185 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4186 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4187                                                 SelectionDAG &DAG) const {
4188   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4189   EVT VT = Op.getValueType();
4190   unsigned VTBits = VT.getSizeInBits();
4191   SDLoc dl(Op);
4192   SDValue ShOpLo = Op.getOperand(0);
4193   SDValue ShOpHi = Op.getOperand(1);
4194   SDValue ShAmt  = Op.getOperand(2);
4195   SDValue ARMcc;
4196   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4197
4198   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4199
4200   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4201                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4202   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4203   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4204                                    DAG.getConstant(VTBits, dl, MVT::i32));
4205   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4206   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4207   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4208
4209   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4210   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4211                           ISD::SETGE, ARMcc, DAG, dl);
4212   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4213   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4214                            CCR, Cmp);
4215
4216   SDValue Ops[2] = { Lo, Hi };
4217   return DAG.getMergeValues(Ops, dl);
4218 }
4219
4220 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4221 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4222 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4223                                                SelectionDAG &DAG) const {
4224   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4225   EVT VT = Op.getValueType();
4226   unsigned VTBits = VT.getSizeInBits();
4227   SDLoc dl(Op);
4228   SDValue ShOpLo = Op.getOperand(0);
4229   SDValue ShOpHi = Op.getOperand(1);
4230   SDValue ShAmt  = Op.getOperand(2);
4231   SDValue ARMcc;
4232
4233   assert(Op.getOpcode() == ISD::SHL_PARTS);
4234   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4235                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4236   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4237   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4238                                    DAG.getConstant(VTBits, dl, MVT::i32));
4239   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4240   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4241
4242   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4243   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4244   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4245                           ISD::SETGE, ARMcc, DAG, dl);
4246   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4247   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4248                            CCR, Cmp);
4249
4250   SDValue Ops[2] = { Lo, Hi };
4251   return DAG.getMergeValues(Ops, dl);
4252 }
4253
4254 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4255                                             SelectionDAG &DAG) const {
4256   // The rounding mode is in bits 23:22 of the FPSCR.
4257   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4258   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4259   // so that the shift + and get folded into a bitfield extract.
4260   SDLoc dl(Op);
4261   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4262                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4263                                               MVT::i32));
4264   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4265                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4266   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4267                               DAG.getConstant(22, dl, MVT::i32));
4268   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4269                      DAG.getConstant(3, dl, MVT::i32));
4270 }
4271
4272 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4273                          const ARMSubtarget *ST) {
4274   SDLoc dl(N);
4275   EVT VT = N->getValueType(0);
4276   if (VT.isVector()) {
4277     assert(ST->hasNEON());
4278
4279     // Compute the least significant set bit: LSB = X & -X
4280     SDValue X = N->getOperand(0);
4281     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4282     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4283
4284     EVT ElemTy = VT.getVectorElementType();
4285
4286     if (ElemTy == MVT::i8) {
4287       // Compute with: cttz(x) = ctpop(lsb - 1)
4288       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4289                                 DAG.getTargetConstant(1, dl, ElemTy));
4290       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4291       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4292     }
4293
4294     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4295         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4296       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4297       unsigned NumBits = ElemTy.getSizeInBits();
4298       SDValue WidthMinus1 =
4299           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4300                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4301       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4302       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4303     }
4304
4305     // Compute with: cttz(x) = ctpop(lsb - 1)
4306
4307     // Since we can only compute the number of bits in a byte with vcnt.8, we
4308     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4309     // and i64.
4310
4311     // Compute LSB - 1.
4312     SDValue Bits;
4313     if (ElemTy == MVT::i64) {
4314       // Load constant 0xffff'ffff'ffff'ffff to register.
4315       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4316                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4317       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4318     } else {
4319       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4320                                 DAG.getTargetConstant(1, dl, ElemTy));
4321       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4322     }
4323
4324     // Count #bits with vcnt.8.
4325     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4326     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4327     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4328
4329     // Gather the #bits with vpaddl (pairwise add.)
4330     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4331     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4332         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4333         Cnt8);
4334     if (ElemTy == MVT::i16)
4335       return Cnt16;
4336
4337     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4338     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4339         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4340         Cnt16);
4341     if (ElemTy == MVT::i32)
4342       return Cnt32;
4343
4344     assert(ElemTy == MVT::i64);
4345     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4346         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4347         Cnt32);
4348     return Cnt64;
4349   }
4350
4351   if (!ST->hasV6T2Ops())
4352     return SDValue();
4353
4354   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4355   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4356 }
4357
4358 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4359 /// for each 16-bit element from operand, repeated.  The basic idea is to
4360 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4361 ///
4362 /// Trace for v4i16:
4363 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4364 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4365 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4366 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4367 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4368 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4369 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4370 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4371 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4372   EVT VT = N->getValueType(0);
4373   SDLoc DL(N);
4374
4375   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4376   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4377   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4378   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4379   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4380   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4381 }
4382
4383 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4384 /// bit-count for each 16-bit element from the operand.  We need slightly
4385 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4386 /// 64/128-bit registers.
4387 ///
4388 /// Trace for v4i16:
4389 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4390 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4391 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4392 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4393 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4394   EVT VT = N->getValueType(0);
4395   SDLoc DL(N);
4396
4397   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4398   if (VT.is64BitVector()) {
4399     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4400     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4401                        DAG.getIntPtrConstant(0, DL));
4402   } else {
4403     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4404                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4405     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4406   }
4407 }
4408
4409 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4410 /// bit-count for each 32-bit element from the operand.  The idea here is
4411 /// to split the vector into 16-bit elements, leverage the 16-bit count
4412 /// routine, and then combine the results.
4413 ///
4414 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4415 /// input    = [v0    v1    ] (vi: 32-bit elements)
4416 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4417 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4418 /// vrev: N0 = [k1 k0 k3 k2 ]
4419 ///            [k0 k1 k2 k3 ]
4420 ///       N1 =+[k1 k0 k3 k2 ]
4421 ///            [k0 k2 k1 k3 ]
4422 ///       N2 =+[k1 k3 k0 k2 ]
4423 ///            [k0    k2    k1    k3    ]
4424 /// Extended =+[k1    k3    k0    k2    ]
4425 ///            [k0    k2    ]
4426 /// Extracted=+[k1    k3    ]
4427 ///
4428 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4429   EVT VT = N->getValueType(0);
4430   SDLoc DL(N);
4431
4432   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4433
4434   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4435   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4436   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4437   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4438   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4439
4440   if (VT.is64BitVector()) {
4441     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4442     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4443                        DAG.getIntPtrConstant(0, DL));
4444   } else {
4445     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4446                                     DAG.getIntPtrConstant(0, DL));
4447     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4448   }
4449 }
4450
4451 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4452                           const ARMSubtarget *ST) {
4453   EVT VT = N->getValueType(0);
4454
4455   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4456   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4457           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4458          "Unexpected type for custom ctpop lowering");
4459
4460   if (VT.getVectorElementType() == MVT::i32)
4461     return lowerCTPOP32BitElements(N, DAG);
4462   else
4463     return lowerCTPOP16BitElements(N, DAG);
4464 }
4465
4466 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4467                           const ARMSubtarget *ST) {
4468   EVT VT = N->getValueType(0);
4469   SDLoc dl(N);
4470
4471   if (!VT.isVector())
4472     return SDValue();
4473
4474   // Lower vector shifts on NEON to use VSHL.
4475   assert(ST->hasNEON() && "unexpected vector shift");
4476
4477   // Left shifts translate directly to the vshiftu intrinsic.
4478   if (N->getOpcode() == ISD::SHL)
4479     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4480                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4481                                        MVT::i32),
4482                        N->getOperand(0), N->getOperand(1));
4483
4484   assert((N->getOpcode() == ISD::SRA ||
4485           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4486
4487   // NEON uses the same intrinsics for both left and right shifts.  For
4488   // right shifts, the shift amounts are negative, so negate the vector of
4489   // shift amounts.
4490   EVT ShiftVT = N->getOperand(1).getValueType();
4491   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4492                                      getZeroVector(ShiftVT, DAG, dl),
4493                                      N->getOperand(1));
4494   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4495                              Intrinsic::arm_neon_vshifts :
4496                              Intrinsic::arm_neon_vshiftu);
4497   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4498                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4499                      N->getOperand(0), NegatedCount);
4500 }
4501
4502 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4503                                 const ARMSubtarget *ST) {
4504   EVT VT = N->getValueType(0);
4505   SDLoc dl(N);
4506
4507   // We can get here for a node like i32 = ISD::SHL i32, i64
4508   if (VT != MVT::i64)
4509     return SDValue();
4510
4511   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4512          "Unknown shift to lower!");
4513
4514   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4515   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4516       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4517     return SDValue();
4518
4519   // If we are in thumb mode, we don't have RRX.
4520   if (ST->isThumb1Only()) return SDValue();
4521
4522   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4523   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4524                            DAG.getConstant(0, dl, MVT::i32));
4525   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4526                            DAG.getConstant(1, dl, MVT::i32));
4527
4528   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4529   // captures the result into a carry flag.
4530   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4531   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4532
4533   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4534   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4535
4536   // Merge the pieces into a single i64 value.
4537  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4538 }
4539
4540 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4541   SDValue TmpOp0, TmpOp1;
4542   bool Invert = false;
4543   bool Swap = false;
4544   unsigned Opc = 0;
4545
4546   SDValue Op0 = Op.getOperand(0);
4547   SDValue Op1 = Op.getOperand(1);
4548   SDValue CC = Op.getOperand(2);
4549   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4550   EVT VT = Op.getValueType();
4551   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4552   SDLoc dl(Op);
4553
4554   if (CmpVT.getVectorElementType() == MVT::i64)
4555     // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4556     // but it's possible that our operands are 64-bit but our result is 32-bit.
4557     // Bail in this case.
4558     return SDValue();
4559
4560   if (Op1.getValueType().isFloatingPoint()) {
4561     switch (SetCCOpcode) {
4562     default: llvm_unreachable("Illegal FP comparison");
4563     case ISD::SETUNE:
4564     case ISD::SETNE:  Invert = true; // Fallthrough
4565     case ISD::SETOEQ:
4566     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4567     case ISD::SETOLT:
4568     case ISD::SETLT: Swap = true; // Fallthrough
4569     case ISD::SETOGT:
4570     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4571     case ISD::SETOLE:
4572     case ISD::SETLE:  Swap = true; // Fallthrough
4573     case ISD::SETOGE:
4574     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4575     case ISD::SETUGE: Swap = true; // Fallthrough
4576     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4577     case ISD::SETUGT: Swap = true; // Fallthrough
4578     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4579     case ISD::SETUEQ: Invert = true; // Fallthrough
4580     case ISD::SETONE:
4581       // Expand this to (OLT | OGT).
4582       TmpOp0 = Op0;
4583       TmpOp1 = Op1;
4584       Opc = ISD::OR;
4585       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4586       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4587       break;
4588     case ISD::SETUO: Invert = true; // Fallthrough
4589     case ISD::SETO:
4590       // Expand this to (OLT | OGE).
4591       TmpOp0 = Op0;
4592       TmpOp1 = Op1;
4593       Opc = ISD::OR;
4594       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4595       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4596       break;
4597     }
4598   } else {
4599     // Integer comparisons.
4600     switch (SetCCOpcode) {
4601     default: llvm_unreachable("Illegal integer comparison");
4602     case ISD::SETNE:  Invert = true;
4603     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4604     case ISD::SETLT:  Swap = true;
4605     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4606     case ISD::SETLE:  Swap = true;
4607     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4608     case ISD::SETULT: Swap = true;
4609     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4610     case ISD::SETULE: Swap = true;
4611     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4612     }
4613
4614     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4615     if (Opc == ARMISD::VCEQ) {
4616
4617       SDValue AndOp;
4618       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4619         AndOp = Op0;
4620       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4621         AndOp = Op1;
4622
4623       // Ignore bitconvert.
4624       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4625         AndOp = AndOp.getOperand(0);
4626
4627       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4628         Opc = ARMISD::VTST;
4629         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4630         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4631         Invert = !Invert;
4632       }
4633     }
4634   }
4635
4636   if (Swap)
4637     std::swap(Op0, Op1);
4638
4639   // If one of the operands is a constant vector zero, attempt to fold the
4640   // comparison to a specialized compare-against-zero form.
4641   SDValue SingleOp;
4642   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4643     SingleOp = Op0;
4644   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4645     if (Opc == ARMISD::VCGE)
4646       Opc = ARMISD::VCLEZ;
4647     else if (Opc == ARMISD::VCGT)
4648       Opc = ARMISD::VCLTZ;
4649     SingleOp = Op1;
4650   }
4651
4652   SDValue Result;
4653   if (SingleOp.getNode()) {
4654     switch (Opc) {
4655     case ARMISD::VCEQ:
4656       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4657     case ARMISD::VCGE:
4658       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4659     case ARMISD::VCLEZ:
4660       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4661     case ARMISD::VCGT:
4662       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4663     case ARMISD::VCLTZ:
4664       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4665     default:
4666       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4667     }
4668   } else {
4669      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4670   }
4671
4672   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4673
4674   if (Invert)
4675     Result = DAG.getNOT(dl, Result, VT);
4676
4677   return Result;
4678 }
4679
4680 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4681 /// valid vector constant for a NEON instruction with a "modified immediate"
4682 /// operand (e.g., VMOV).  If so, return the encoded value.
4683 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4684                                  unsigned SplatBitSize, SelectionDAG &DAG,
4685                                  SDLoc dl, EVT &VT, bool is128Bits,
4686                                  NEONModImmType type) {
4687   unsigned OpCmode, Imm;
4688
4689   // SplatBitSize is set to the smallest size that splats the vector, so a
4690   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4691   // immediate instructions others than VMOV do not support the 8-bit encoding
4692   // of a zero vector, and the default encoding of zero is supposed to be the
4693   // 32-bit version.
4694   if (SplatBits == 0)
4695     SplatBitSize = 32;
4696
4697   switch (SplatBitSize) {
4698   case 8:
4699     if (type != VMOVModImm)
4700       return SDValue();
4701     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4702     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4703     OpCmode = 0xe;
4704     Imm = SplatBits;
4705     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4706     break;
4707
4708   case 16:
4709     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4710     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4711     if ((SplatBits & ~0xff) == 0) {
4712       // Value = 0x00nn: Op=x, Cmode=100x.
4713       OpCmode = 0x8;
4714       Imm = SplatBits;
4715       break;
4716     }
4717     if ((SplatBits & ~0xff00) == 0) {
4718       // Value = 0xnn00: Op=x, Cmode=101x.
4719       OpCmode = 0xa;
4720       Imm = SplatBits >> 8;
4721       break;
4722     }
4723     return SDValue();
4724
4725   case 32:
4726     // NEON's 32-bit VMOV supports splat values where:
4727     // * only one byte is nonzero, or
4728     // * the least significant byte is 0xff and the second byte is nonzero, or
4729     // * the least significant 2 bytes are 0xff and the third is nonzero.
4730     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4731     if ((SplatBits & ~0xff) == 0) {
4732       // Value = 0x000000nn: Op=x, Cmode=000x.
4733       OpCmode = 0;
4734       Imm = SplatBits;
4735       break;
4736     }
4737     if ((SplatBits & ~0xff00) == 0) {
4738       // Value = 0x0000nn00: Op=x, Cmode=001x.
4739       OpCmode = 0x2;
4740       Imm = SplatBits >> 8;
4741       break;
4742     }
4743     if ((SplatBits & ~0xff0000) == 0) {
4744       // Value = 0x00nn0000: Op=x, Cmode=010x.
4745       OpCmode = 0x4;
4746       Imm = SplatBits >> 16;
4747       break;
4748     }
4749     if ((SplatBits & ~0xff000000) == 0) {
4750       // Value = 0xnn000000: Op=x, Cmode=011x.
4751       OpCmode = 0x6;
4752       Imm = SplatBits >> 24;
4753       break;
4754     }
4755
4756     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4757     if (type == OtherModImm) return SDValue();
4758
4759     if ((SplatBits & ~0xffff) == 0 &&
4760         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4761       // Value = 0x0000nnff: Op=x, Cmode=1100.
4762       OpCmode = 0xc;
4763       Imm = SplatBits >> 8;
4764       break;
4765     }
4766
4767     if ((SplatBits & ~0xffffff) == 0 &&
4768         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4769       // Value = 0x00nnffff: Op=x, Cmode=1101.
4770       OpCmode = 0xd;
4771       Imm = SplatBits >> 16;
4772       break;
4773     }
4774
4775     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4776     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4777     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4778     // and fall through here to test for a valid 64-bit splat.  But, then the
4779     // caller would also need to check and handle the change in size.
4780     return SDValue();
4781
4782   case 64: {
4783     if (type != VMOVModImm)
4784       return SDValue();
4785     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4786     uint64_t BitMask = 0xff;
4787     uint64_t Val = 0;
4788     unsigned ImmMask = 1;
4789     Imm = 0;
4790     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4791       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4792         Val |= BitMask;
4793         Imm |= ImmMask;
4794       } else if ((SplatBits & BitMask) != 0) {
4795         return SDValue();
4796       }
4797       BitMask <<= 8;
4798       ImmMask <<= 1;
4799     }
4800
4801     if (DAG.getDataLayout().isBigEndian())
4802       // swap higher and lower 32 bit word
4803       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4804
4805     // Op=1, Cmode=1110.
4806     OpCmode = 0x1e;
4807     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4808     break;
4809   }
4810
4811   default:
4812     llvm_unreachable("unexpected size for isNEONModifiedImm");
4813   }
4814
4815   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4816   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4817 }
4818
4819 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4820                                            const ARMSubtarget *ST) const {
4821   if (!ST->hasVFP3())
4822     return SDValue();
4823
4824   bool IsDouble = Op.getValueType() == MVT::f64;
4825   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4826
4827   // Use the default (constant pool) lowering for double constants when we have
4828   // an SP-only FPU
4829   if (IsDouble && Subtarget->isFPOnlySP())
4830     return SDValue();
4831
4832   // Try splatting with a VMOV.f32...
4833   APFloat FPVal = CFP->getValueAPF();
4834   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4835
4836   if (ImmVal != -1) {
4837     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4838       // We have code in place to select a valid ConstantFP already, no need to
4839       // do any mangling.
4840       return Op;
4841     }
4842
4843     // It's a float and we are trying to use NEON operations where
4844     // possible. Lower it to a splat followed by an extract.
4845     SDLoc DL(Op);
4846     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4847     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4848                                       NewVal);
4849     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4850                        DAG.getConstant(0, DL, MVT::i32));
4851   }
4852
4853   // The rest of our options are NEON only, make sure that's allowed before
4854   // proceeding..
4855   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4856     return SDValue();
4857
4858   EVT VMovVT;
4859   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4860
4861   // It wouldn't really be worth bothering for doubles except for one very
4862   // important value, which does happen to match: 0.0. So make sure we don't do
4863   // anything stupid.
4864   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4865     return SDValue();
4866
4867   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4868   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4869                                      VMovVT, false, VMOVModImm);
4870   if (NewVal != SDValue()) {
4871     SDLoc DL(Op);
4872     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4873                                       NewVal);
4874     if (IsDouble)
4875       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4876
4877     // It's a float: cast and extract a vector element.
4878     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4879                                        VecConstant);
4880     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4881                        DAG.getConstant(0, DL, MVT::i32));
4882   }
4883
4884   // Finally, try a VMVN.i32
4885   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4886                              false, VMVNModImm);
4887   if (NewVal != SDValue()) {
4888     SDLoc DL(Op);
4889     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4890
4891     if (IsDouble)
4892       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4893
4894     // It's a float: cast and extract a vector element.
4895     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4896                                        VecConstant);
4897     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4898                        DAG.getConstant(0, DL, MVT::i32));
4899   }
4900
4901   return SDValue();
4902 }
4903
4904 // check if an VEXT instruction can handle the shuffle mask when the
4905 // vector sources of the shuffle are the same.
4906 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4907   unsigned NumElts = VT.getVectorNumElements();
4908
4909   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4910   if (M[0] < 0)
4911     return false;
4912
4913   Imm = M[0];
4914
4915   // If this is a VEXT shuffle, the immediate value is the index of the first
4916   // element.  The other shuffle indices must be the successive elements after
4917   // the first one.
4918   unsigned ExpectedElt = Imm;
4919   for (unsigned i = 1; i < NumElts; ++i) {
4920     // Increment the expected index.  If it wraps around, just follow it
4921     // back to index zero and keep going.
4922     ++ExpectedElt;
4923     if (ExpectedElt == NumElts)
4924       ExpectedElt = 0;
4925
4926     if (M[i] < 0) continue; // ignore UNDEF indices
4927     if (ExpectedElt != static_cast<unsigned>(M[i]))
4928       return false;
4929   }
4930
4931   return true;
4932 }
4933
4934
4935 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4936                        bool &ReverseVEXT, unsigned &Imm) {
4937   unsigned NumElts = VT.getVectorNumElements();
4938   ReverseVEXT = false;
4939
4940   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4941   if (M[0] < 0)
4942     return false;
4943
4944   Imm = M[0];
4945
4946   // If this is a VEXT shuffle, the immediate value is the index of the first
4947   // element.  The other shuffle indices must be the successive elements after
4948   // the first one.
4949   unsigned ExpectedElt = Imm;
4950   for (unsigned i = 1; i < NumElts; ++i) {
4951     // Increment the expected index.  If it wraps around, it may still be
4952     // a VEXT but the source vectors must be swapped.
4953     ExpectedElt += 1;
4954     if (ExpectedElt == NumElts * 2) {
4955       ExpectedElt = 0;
4956       ReverseVEXT = true;
4957     }
4958
4959     if (M[i] < 0) continue; // ignore UNDEF indices
4960     if (ExpectedElt != static_cast<unsigned>(M[i]))
4961       return false;
4962   }
4963
4964   // Adjust the index value if the source operands will be swapped.
4965   if (ReverseVEXT)
4966     Imm -= NumElts;
4967
4968   return true;
4969 }
4970
4971 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4972 /// instruction with the specified blocksize.  (The order of the elements
4973 /// within each block of the vector is reversed.)
4974 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4975   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4976          "Only possible block sizes for VREV are: 16, 32, 64");
4977
4978   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4979   if (EltSz == 64)
4980     return false;
4981
4982   unsigned NumElts = VT.getVectorNumElements();
4983   unsigned BlockElts = M[0] + 1;
4984   // If the first shuffle index is UNDEF, be optimistic.
4985   if (M[0] < 0)
4986     BlockElts = BlockSize / EltSz;
4987
4988   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4989     return false;
4990
4991   for (unsigned i = 0; i < NumElts; ++i) {
4992     if (M[i] < 0) continue; // ignore UNDEF indices
4993     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4994       return false;
4995   }
4996
4997   return true;
4998 }
4999
5000 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5001   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5002   // range, then 0 is placed into the resulting vector. So pretty much any mask
5003   // of 8 elements can work here.
5004   return VT == MVT::v8i8 && M.size() == 8;
5005 }
5006
5007 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5008 // checking that pairs of elements in the shuffle mask represent the same index
5009 // in each vector, incrementing the expected index by 2 at each step.
5010 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5011 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5012 //  v2={e,f,g,h}
5013 // WhichResult gives the offset for each element in the mask based on which
5014 // of the two results it belongs to.
5015 //
5016 // The transpose can be represented either as:
5017 // result1 = shufflevector v1, v2, result1_shuffle_mask
5018 // result2 = shufflevector v1, v2, result2_shuffle_mask
5019 // where v1/v2 and the shuffle masks have the same number of elements
5020 // (here WhichResult (see below) indicates which result is being checked)
5021 //
5022 // or as:
5023 // results = shufflevector v1, v2, shuffle_mask
5024 // where both results are returned in one vector and the shuffle mask has twice
5025 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5026 // want to check the low half and high half of the shuffle mask as if it were
5027 // the other case
5028 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5029   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5030   if (EltSz == 64)
5031     return false;
5032
5033   unsigned NumElts = VT.getVectorNumElements();
5034   if (M.size() != NumElts && M.size() != NumElts*2)
5035     return false;
5036
5037   // If the mask is twice as long as the input vector then we need to check the
5038   // upper and lower parts of the mask with a matching value for WhichResult
5039   // FIXME: A mask with only even values will be rejected in case the first
5040   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5041   // M[0] is used to determine WhichResult
5042   for (unsigned i = 0; i < M.size(); i += NumElts) {
5043     if (M.size() == NumElts * 2)
5044       WhichResult = i / NumElts;
5045     else
5046       WhichResult = M[i] == 0 ? 0 : 1;
5047     for (unsigned j = 0; j < NumElts; j += 2) {
5048       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5049           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5050         return false;
5051     }
5052   }
5053
5054   if (M.size() == NumElts*2)
5055     WhichResult = 0;
5056
5057   return true;
5058 }
5059
5060 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5061 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5062 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5063 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5064   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5065   if (EltSz == 64)
5066     return false;
5067
5068   unsigned NumElts = VT.getVectorNumElements();
5069   if (M.size() != NumElts && M.size() != NumElts*2)
5070     return false;
5071
5072   for (unsigned i = 0; i < M.size(); i += NumElts) {
5073     if (M.size() == NumElts * 2)
5074       WhichResult = i / NumElts;
5075     else
5076       WhichResult = M[i] == 0 ? 0 : 1;
5077     for (unsigned j = 0; j < NumElts; j += 2) {
5078       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5079           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5080         return false;
5081     }
5082   }
5083
5084   if (M.size() == NumElts*2)
5085     WhichResult = 0;
5086
5087   return true;
5088 }
5089
5090 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5091 // that the mask elements are either all even and in steps of size 2 or all odd
5092 // and in steps of size 2.
5093 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5094 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5095 //  v2={e,f,g,h}
5096 // Requires similar checks to that of isVTRNMask with
5097 // respect the how results are returned.
5098 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5099   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5100   if (EltSz == 64)
5101     return false;
5102
5103   unsigned NumElts = VT.getVectorNumElements();
5104   if (M.size() != NumElts && M.size() != NumElts*2)
5105     return false;
5106
5107   for (unsigned i = 0; i < M.size(); i += NumElts) {
5108     WhichResult = M[i] == 0 ? 0 : 1;
5109     for (unsigned j = 0; j < NumElts; ++j) {
5110       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5111         return false;
5112     }
5113   }
5114
5115   if (M.size() == NumElts*2)
5116     WhichResult = 0;
5117
5118   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5119   if (VT.is64BitVector() && EltSz == 32)
5120     return false;
5121
5122   return true;
5123 }
5124
5125 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5126 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5127 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5128 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5129   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5130   if (EltSz == 64)
5131     return false;
5132
5133   unsigned NumElts = VT.getVectorNumElements();
5134   if (M.size() != NumElts && M.size() != NumElts*2)
5135     return false;
5136
5137   unsigned Half = NumElts / 2;
5138   for (unsigned i = 0; i < M.size(); i += NumElts) {
5139     WhichResult = M[i] == 0 ? 0 : 1;
5140     for (unsigned j = 0; j < NumElts; j += Half) {
5141       unsigned Idx = WhichResult;
5142       for (unsigned k = 0; k < Half; ++k) {
5143         int MIdx = M[i + j + k];
5144         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5145           return false;
5146         Idx += 2;
5147       }
5148     }
5149   }
5150
5151   if (M.size() == NumElts*2)
5152     WhichResult = 0;
5153
5154   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5155   if (VT.is64BitVector() && EltSz == 32)
5156     return false;
5157
5158   return true;
5159 }
5160
5161 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5162 // that pairs of elements of the shufflemask represent the same index in each
5163 // vector incrementing sequentially through the vectors.
5164 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5165 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5166 //  v2={e,f,g,h}
5167 // Requires similar checks to that of isVTRNMask with respect the how results
5168 // are returned.
5169 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5170   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5171   if (EltSz == 64)
5172     return false;
5173
5174   unsigned NumElts = VT.getVectorNumElements();
5175   if (M.size() != NumElts && M.size() != NumElts*2)
5176     return false;
5177
5178   for (unsigned i = 0; i < M.size(); i += NumElts) {
5179     WhichResult = M[i] == 0 ? 0 : 1;
5180     unsigned Idx = WhichResult * NumElts / 2;
5181     for (unsigned j = 0; j < NumElts; j += 2) {
5182       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5183           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5184         return false;
5185       Idx += 1;
5186     }
5187   }
5188
5189   if (M.size() == NumElts*2)
5190     WhichResult = 0;
5191
5192   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5193   if (VT.is64BitVector() && EltSz == 32)
5194     return false;
5195
5196   return true;
5197 }
5198
5199 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5200 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5201 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5202 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5203   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5204   if (EltSz == 64)
5205     return false;
5206
5207   unsigned NumElts = VT.getVectorNumElements();
5208   if (M.size() != NumElts && M.size() != NumElts*2)
5209     return false;
5210
5211   for (unsigned i = 0; i < M.size(); i += NumElts) {
5212     WhichResult = M[i] == 0 ? 0 : 1;
5213     unsigned Idx = WhichResult * NumElts / 2;
5214     for (unsigned j = 0; j < NumElts; j += 2) {
5215       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5216           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5217         return false;
5218       Idx += 1;
5219     }
5220   }
5221
5222   if (M.size() == NumElts*2)
5223     WhichResult = 0;
5224
5225   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5226   if (VT.is64BitVector() && EltSz == 32)
5227     return false;
5228
5229   return true;
5230 }
5231
5232 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5233 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5234 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5235                                            unsigned &WhichResult,
5236                                            bool &isV_UNDEF) {
5237   isV_UNDEF = false;
5238   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5239     return ARMISD::VTRN;
5240   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5241     return ARMISD::VUZP;
5242   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5243     return ARMISD::VZIP;
5244
5245   isV_UNDEF = true;
5246   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5247     return ARMISD::VTRN;
5248   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5249     return ARMISD::VUZP;
5250   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5251     return ARMISD::VZIP;
5252
5253   return 0;
5254 }
5255
5256 /// \return true if this is a reverse operation on an vector.
5257 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5258   unsigned NumElts = VT.getVectorNumElements();
5259   // Make sure the mask has the right size.
5260   if (NumElts != M.size())
5261       return false;
5262
5263   // Look for <15, ..., 3, -1, 1, 0>.
5264   for (unsigned i = 0; i != NumElts; ++i)
5265     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5266       return false;
5267
5268   return true;
5269 }
5270
5271 // If N is an integer constant that can be moved into a register in one
5272 // instruction, return an SDValue of such a constant (will become a MOV
5273 // instruction).  Otherwise return null.
5274 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5275                                      const ARMSubtarget *ST, SDLoc dl) {
5276   uint64_t Val;
5277   if (!isa<ConstantSDNode>(N))
5278     return SDValue();
5279   Val = cast<ConstantSDNode>(N)->getZExtValue();
5280
5281   if (ST->isThumb1Only()) {
5282     if (Val <= 255 || ~Val <= 255)
5283       return DAG.getConstant(Val, dl, MVT::i32);
5284   } else {
5285     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5286       return DAG.getConstant(Val, dl, MVT::i32);
5287   }
5288   return SDValue();
5289 }
5290
5291 // If this is a case we can't handle, return null and let the default
5292 // expansion code take care of it.
5293 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5294                                              const ARMSubtarget *ST) const {
5295   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5296   SDLoc dl(Op);
5297   EVT VT = Op.getValueType();
5298
5299   APInt SplatBits, SplatUndef;
5300   unsigned SplatBitSize;
5301   bool HasAnyUndefs;
5302   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5303     if (SplatBitSize <= 64) {
5304       // Check if an immediate VMOV works.
5305       EVT VmovVT;
5306       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5307                                       SplatUndef.getZExtValue(), SplatBitSize,
5308                                       DAG, dl, VmovVT, VT.is128BitVector(),
5309                                       VMOVModImm);
5310       if (Val.getNode()) {
5311         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5312         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5313       }
5314
5315       // Try an immediate VMVN.
5316       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5317       Val = isNEONModifiedImm(NegatedImm,
5318                                       SplatUndef.getZExtValue(), SplatBitSize,
5319                                       DAG, dl, VmovVT, VT.is128BitVector(),
5320                                       VMVNModImm);
5321       if (Val.getNode()) {
5322         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5323         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5324       }
5325
5326       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5327       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5328         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5329         if (ImmVal != -1) {
5330           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5331           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5332         }
5333       }
5334     }
5335   }
5336
5337   // Scan through the operands to see if only one value is used.
5338   //
5339   // As an optimisation, even if more than one value is used it may be more
5340   // profitable to splat with one value then change some lanes.
5341   //
5342   // Heuristically we decide to do this if the vector has a "dominant" value,
5343   // defined as splatted to more than half of the lanes.
5344   unsigned NumElts = VT.getVectorNumElements();
5345   bool isOnlyLowElement = true;
5346   bool usesOnlyOneValue = true;
5347   bool hasDominantValue = false;
5348   bool isConstant = true;
5349
5350   // Map of the number of times a particular SDValue appears in the
5351   // element list.
5352   DenseMap<SDValue, unsigned> ValueCounts;
5353   SDValue Value;
5354   for (unsigned i = 0; i < NumElts; ++i) {
5355     SDValue V = Op.getOperand(i);
5356     if (V.getOpcode() == ISD::UNDEF)
5357       continue;
5358     if (i > 0)
5359       isOnlyLowElement = false;
5360     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5361       isConstant = false;
5362
5363     ValueCounts.insert(std::make_pair(V, 0));
5364     unsigned &Count = ValueCounts[V];
5365
5366     // Is this value dominant? (takes up more than half of the lanes)
5367     if (++Count > (NumElts / 2)) {
5368       hasDominantValue = true;
5369       Value = V;
5370     }
5371   }
5372   if (ValueCounts.size() != 1)
5373     usesOnlyOneValue = false;
5374   if (!Value.getNode() && ValueCounts.size() > 0)
5375     Value = ValueCounts.begin()->first;
5376
5377   if (ValueCounts.size() == 0)
5378     return DAG.getUNDEF(VT);
5379
5380   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5381   // Keep going if we are hitting this case.
5382   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5383     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5384
5385   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5386
5387   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5388   // i32 and try again.
5389   if (hasDominantValue && EltSize <= 32) {
5390     if (!isConstant) {
5391       SDValue N;
5392
5393       // If we are VDUPing a value that comes directly from a vector, that will
5394       // cause an unnecessary move to and from a GPR, where instead we could
5395       // just use VDUPLANE. We can only do this if the lane being extracted
5396       // is at a constant index, as the VDUP from lane instructions only have
5397       // constant-index forms.
5398       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5399           isa<ConstantSDNode>(Value->getOperand(1))) {
5400         // We need to create a new undef vector to use for the VDUPLANE if the
5401         // size of the vector from which we get the value is different than the
5402         // size of the vector that we need to create. We will insert the element
5403         // such that the register coalescer will remove unnecessary copies.
5404         if (VT != Value->getOperand(0).getValueType()) {
5405           ConstantSDNode *constIndex;
5406           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5407           assert(constIndex && "The index is not a constant!");
5408           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5409                              VT.getVectorNumElements();
5410           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5411                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5412                         Value, DAG.getConstant(index, dl, MVT::i32)),
5413                            DAG.getConstant(index, dl, MVT::i32));
5414         } else
5415           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5416                         Value->getOperand(0), Value->getOperand(1));
5417       } else
5418         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5419
5420       if (!usesOnlyOneValue) {
5421         // The dominant value was splatted as 'N', but we now have to insert
5422         // all differing elements.
5423         for (unsigned I = 0; I < NumElts; ++I) {
5424           if (Op.getOperand(I) == Value)
5425             continue;
5426           SmallVector<SDValue, 3> Ops;
5427           Ops.push_back(N);
5428           Ops.push_back(Op.getOperand(I));
5429           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5430           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5431         }
5432       }
5433       return N;
5434     }
5435     if (VT.getVectorElementType().isFloatingPoint()) {
5436       SmallVector<SDValue, 8> Ops;
5437       for (unsigned i = 0; i < NumElts; ++i)
5438         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5439                                   Op.getOperand(i)));
5440       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5441       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5442       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5443       if (Val.getNode())
5444         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5445     }
5446     if (usesOnlyOneValue) {
5447       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5448       if (isConstant && Val.getNode())
5449         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5450     }
5451   }
5452
5453   // If all elements are constants and the case above didn't get hit, fall back
5454   // to the default expansion, which will generate a load from the constant
5455   // pool.
5456   if (isConstant)
5457     return SDValue();
5458
5459   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5460   if (NumElts >= 4) {
5461     SDValue shuffle = ReconstructShuffle(Op, DAG);
5462     if (shuffle != SDValue())
5463       return shuffle;
5464   }
5465
5466   // Vectors with 32- or 64-bit elements can be built by directly assigning
5467   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5468   // will be legalized.
5469   if (EltSize >= 32) {
5470     // Do the expansion with floating-point types, since that is what the VFP
5471     // registers are defined to use, and since i64 is not legal.
5472     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5473     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5474     SmallVector<SDValue, 8> Ops;
5475     for (unsigned i = 0; i < NumElts; ++i)
5476       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5477     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5478     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5479   }
5480
5481   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5482   // know the default expansion would otherwise fall back on something even
5483   // worse. For a vector with one or two non-undef values, that's
5484   // scalar_to_vector for the elements followed by a shuffle (provided the
5485   // shuffle is valid for the target) and materialization element by element
5486   // on the stack followed by a load for everything else.
5487   if (!isConstant && !usesOnlyOneValue) {
5488     SDValue Vec = DAG.getUNDEF(VT);
5489     for (unsigned i = 0 ; i < NumElts; ++i) {
5490       SDValue V = Op.getOperand(i);
5491       if (V.getOpcode() == ISD::UNDEF)
5492         continue;
5493       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5494       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5495     }
5496     return Vec;
5497   }
5498
5499   return SDValue();
5500 }
5501
5502 // Gather data to see if the operation can be modelled as a
5503 // shuffle in combination with VEXTs.
5504 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5505                                               SelectionDAG &DAG) const {
5506   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5507   SDLoc dl(Op);
5508   EVT VT = Op.getValueType();
5509   unsigned NumElts = VT.getVectorNumElements();
5510
5511   struct ShuffleSourceInfo {
5512     SDValue Vec;
5513     unsigned MinElt;
5514     unsigned MaxElt;
5515
5516     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5517     // be compatible with the shuffle we intend to construct. As a result
5518     // ShuffleVec will be some sliding window into the original Vec.
5519     SDValue ShuffleVec;
5520
5521     // Code should guarantee that element i in Vec starts at element "WindowBase
5522     // + i * WindowScale in ShuffleVec".
5523     int WindowBase;
5524     int WindowScale;
5525
5526     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5527     ShuffleSourceInfo(SDValue Vec)
5528         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5529           WindowScale(1) {}
5530   };
5531
5532   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5533   // node.
5534   SmallVector<ShuffleSourceInfo, 2> Sources;
5535   for (unsigned i = 0; i < NumElts; ++i) {
5536     SDValue V = Op.getOperand(i);
5537     if (V.getOpcode() == ISD::UNDEF)
5538       continue;
5539     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5540       // A shuffle can only come from building a vector from various
5541       // elements of other vectors.
5542       return SDValue();
5543     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5544       // Furthermore, shuffles require a constant mask, whereas extractelts
5545       // accept variable indices.
5546       return SDValue();
5547     }
5548
5549     // Add this element source to the list if it's not already there.
5550     SDValue SourceVec = V.getOperand(0);
5551     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5552     if (Source == Sources.end())
5553       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5554
5555     // Update the minimum and maximum lane number seen.
5556     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5557     Source->MinElt = std::min(Source->MinElt, EltNo);
5558     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5559   }
5560
5561   // Currently only do something sane when at most two source vectors
5562   // are involved.
5563   if (Sources.size() > 2)
5564     return SDValue();
5565
5566   // Find out the smallest element size among result and two sources, and use
5567   // it as element size to build the shuffle_vector.
5568   EVT SmallestEltTy = VT.getVectorElementType();
5569   for (auto &Source : Sources) {
5570     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5571     if (SrcEltTy.bitsLT(SmallestEltTy))
5572       SmallestEltTy = SrcEltTy;
5573   }
5574   unsigned ResMultiplier =
5575       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5576   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5577   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5578
5579   // If the source vector is too wide or too narrow, we may nevertheless be able
5580   // to construct a compatible shuffle either by concatenating it with UNDEF or
5581   // extracting a suitable range of elements.
5582   for (auto &Src : Sources) {
5583     EVT SrcVT = Src.ShuffleVec.getValueType();
5584
5585     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5586       continue;
5587
5588     // This stage of the search produces a source with the same element type as
5589     // the original, but with a total width matching the BUILD_VECTOR output.
5590     EVT EltVT = SrcVT.getVectorElementType();
5591     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5592     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5593
5594     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5595       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5596         return SDValue();
5597       // We can pad out the smaller vector for free, so if it's part of a
5598       // shuffle...
5599       Src.ShuffleVec =
5600           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5601                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5602       continue;
5603     }
5604
5605     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5606       return SDValue();
5607
5608     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5609       // Span too large for a VEXT to cope
5610       return SDValue();
5611     }
5612
5613     if (Src.MinElt >= NumSrcElts) {
5614       // The extraction can just take the second half
5615       Src.ShuffleVec =
5616           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5617                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5618       Src.WindowBase = -NumSrcElts;
5619     } else if (Src.MaxElt < NumSrcElts) {
5620       // The extraction can just take the first half
5621       Src.ShuffleVec =
5622           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5623                       DAG.getConstant(0, dl, MVT::i32));
5624     } else {
5625       // An actual VEXT is needed
5626       SDValue VEXTSrc1 =
5627           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5628                       DAG.getConstant(0, dl, MVT::i32));
5629       SDValue VEXTSrc2 =
5630           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5631                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5632
5633       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5634                                    VEXTSrc2,
5635                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
5636       Src.WindowBase = -Src.MinElt;
5637     }
5638   }
5639
5640   // Another possible incompatibility occurs from the vector element types. We
5641   // can fix this by bitcasting the source vectors to the same type we intend
5642   // for the shuffle.
5643   for (auto &Src : Sources) {
5644     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5645     if (SrcEltTy == SmallestEltTy)
5646       continue;
5647     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5648     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5649     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5650     Src.WindowBase *= Src.WindowScale;
5651   }
5652
5653   // Final sanity check before we try to actually produce a shuffle.
5654   DEBUG(
5655     for (auto Src : Sources)
5656       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5657   );
5658
5659   // The stars all align, our next step is to produce the mask for the shuffle.
5660   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5661   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5662   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5663     SDValue Entry = Op.getOperand(i);
5664     if (Entry.getOpcode() == ISD::UNDEF)
5665       continue;
5666
5667     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5668     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5669
5670     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5671     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5672     // segment.
5673     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5674     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5675                                VT.getVectorElementType().getSizeInBits());
5676     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5677
5678     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5679     // starting at the appropriate offset.
5680     int *LaneMask = &Mask[i * ResMultiplier];
5681
5682     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5683     ExtractBase += NumElts * (Src - Sources.begin());
5684     for (int j = 0; j < LanesDefined; ++j)
5685       LaneMask[j] = ExtractBase + j;
5686   }
5687
5688   // Final check before we try to produce nonsense...
5689   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5690     return SDValue();
5691
5692   // We can't handle more than two sources. This should have already
5693   // been checked before this point.
5694   assert(Sources.size() <= 2 && "Too many sources!");
5695
5696   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5697   for (unsigned i = 0; i < Sources.size(); ++i)
5698     ShuffleOps[i] = Sources[i].ShuffleVec;
5699
5700   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5701                                          ShuffleOps[1], &Mask[0]);
5702   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5703 }
5704
5705 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5706 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5707 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5708 /// are assumed to be legal.
5709 bool
5710 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5711                                       EVT VT) const {
5712   if (VT.getVectorNumElements() == 4 &&
5713       (VT.is128BitVector() || VT.is64BitVector())) {
5714     unsigned PFIndexes[4];
5715     for (unsigned i = 0; i != 4; ++i) {
5716       if (M[i] < 0)
5717         PFIndexes[i] = 8;
5718       else
5719         PFIndexes[i] = M[i];
5720     }
5721
5722     // Compute the index in the perfect shuffle table.
5723     unsigned PFTableIndex =
5724       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5725     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5726     unsigned Cost = (PFEntry >> 30);
5727
5728     if (Cost <= 4)
5729       return true;
5730   }
5731
5732   bool ReverseVEXT, isV_UNDEF;
5733   unsigned Imm, WhichResult;
5734
5735   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5736   return (EltSize >= 32 ||
5737           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5738           isVREVMask(M, VT, 64) ||
5739           isVREVMask(M, VT, 32) ||
5740           isVREVMask(M, VT, 16) ||
5741           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5742           isVTBLMask(M, VT) ||
5743           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5744           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5745 }
5746
5747 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5748 /// the specified operations to build the shuffle.
5749 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5750                                       SDValue RHS, SelectionDAG &DAG,
5751                                       SDLoc dl) {
5752   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5753   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5754   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5755
5756   enum {
5757     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5758     OP_VREV,
5759     OP_VDUP0,
5760     OP_VDUP1,
5761     OP_VDUP2,
5762     OP_VDUP3,
5763     OP_VEXT1,
5764     OP_VEXT2,
5765     OP_VEXT3,
5766     OP_VUZPL, // VUZP, left result
5767     OP_VUZPR, // VUZP, right result
5768     OP_VZIPL, // VZIP, left result
5769     OP_VZIPR, // VZIP, right result
5770     OP_VTRNL, // VTRN, left result
5771     OP_VTRNR  // VTRN, right result
5772   };
5773
5774   if (OpNum == OP_COPY) {
5775     if (LHSID == (1*9+2)*9+3) return LHS;
5776     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5777     return RHS;
5778   }
5779
5780   SDValue OpLHS, OpRHS;
5781   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5782   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5783   EVT VT = OpLHS.getValueType();
5784
5785   switch (OpNum) {
5786   default: llvm_unreachable("Unknown shuffle opcode!");
5787   case OP_VREV:
5788     // VREV divides the vector in half and swaps within the half.
5789     if (VT.getVectorElementType() == MVT::i32 ||
5790         VT.getVectorElementType() == MVT::f32)
5791       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5792     // vrev <4 x i16> -> VREV32
5793     if (VT.getVectorElementType() == MVT::i16)
5794       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5795     // vrev <4 x i8> -> VREV16
5796     assert(VT.getVectorElementType() == MVT::i8);
5797     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5798   case OP_VDUP0:
5799   case OP_VDUP1:
5800   case OP_VDUP2:
5801   case OP_VDUP3:
5802     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5803                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5804   case OP_VEXT1:
5805   case OP_VEXT2:
5806   case OP_VEXT3:
5807     return DAG.getNode(ARMISD::VEXT, dl, VT,
5808                        OpLHS, OpRHS,
5809                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5810   case OP_VUZPL:
5811   case OP_VUZPR:
5812     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5813                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5814   case OP_VZIPL:
5815   case OP_VZIPR:
5816     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5817                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5818   case OP_VTRNL:
5819   case OP_VTRNR:
5820     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5821                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5822   }
5823 }
5824
5825 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5826                                        ArrayRef<int> ShuffleMask,
5827                                        SelectionDAG &DAG) {
5828   // Check to see if we can use the VTBL instruction.
5829   SDValue V1 = Op.getOperand(0);
5830   SDValue V2 = Op.getOperand(1);
5831   SDLoc DL(Op);
5832
5833   SmallVector<SDValue, 8> VTBLMask;
5834   for (ArrayRef<int>::iterator
5835          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5836     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5837
5838   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5839     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5840                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5841
5842   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5843                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5844 }
5845
5846 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5847                                                       SelectionDAG &DAG) {
5848   SDLoc DL(Op);
5849   SDValue OpLHS = Op.getOperand(0);
5850   EVT VT = OpLHS.getValueType();
5851
5852   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5853          "Expect an v8i16/v16i8 type");
5854   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5855   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5856   // extract the first 8 bytes into the top double word and the last 8 bytes
5857   // into the bottom double word. The v8i16 case is similar.
5858   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5859   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5860                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5861 }
5862
5863 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5864   SDValue V1 = Op.getOperand(0);
5865   SDValue V2 = Op.getOperand(1);
5866   SDLoc dl(Op);
5867   EVT VT = Op.getValueType();
5868   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5869
5870   // Convert shuffles that are directly supported on NEON to target-specific
5871   // DAG nodes, instead of keeping them as shuffles and matching them again
5872   // during code selection.  This is more efficient and avoids the possibility
5873   // of inconsistencies between legalization and selection.
5874   // FIXME: floating-point vectors should be canonicalized to integer vectors
5875   // of the same time so that they get CSEd properly.
5876   ArrayRef<int> ShuffleMask = SVN->getMask();
5877
5878   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5879   if (EltSize <= 32) {
5880     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5881       int Lane = SVN->getSplatIndex();
5882       // If this is undef splat, generate it via "just" vdup, if possible.
5883       if (Lane == -1) Lane = 0;
5884
5885       // Test if V1 is a SCALAR_TO_VECTOR.
5886       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5887         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5888       }
5889       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5890       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5891       // reaches it).
5892       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5893           !isa<ConstantSDNode>(V1.getOperand(0))) {
5894         bool IsScalarToVector = true;
5895         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5896           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5897             IsScalarToVector = false;
5898             break;
5899           }
5900         if (IsScalarToVector)
5901           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5902       }
5903       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5904                          DAG.getConstant(Lane, dl, MVT::i32));
5905     }
5906
5907     bool ReverseVEXT;
5908     unsigned Imm;
5909     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5910       if (ReverseVEXT)
5911         std::swap(V1, V2);
5912       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5913                          DAG.getConstant(Imm, dl, MVT::i32));
5914     }
5915
5916     if (isVREVMask(ShuffleMask, VT, 64))
5917       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5918     if (isVREVMask(ShuffleMask, VT, 32))
5919       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5920     if (isVREVMask(ShuffleMask, VT, 16))
5921       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5922
5923     if (V2->getOpcode() == ISD::UNDEF &&
5924         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5925       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5926                          DAG.getConstant(Imm, dl, MVT::i32));
5927     }
5928
5929     // Check for Neon shuffles that modify both input vectors in place.
5930     // If both results are used, i.e., if there are two shuffles with the same
5931     // source operands and with masks corresponding to both results of one of
5932     // these operations, DAG memoization will ensure that a single node is
5933     // used for both shuffles.
5934     unsigned WhichResult;
5935     bool isV_UNDEF;
5936     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5937             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5938       if (isV_UNDEF)
5939         V2 = V1;
5940       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5941           .getValue(WhichResult);
5942     }
5943
5944     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5945     // shuffles that produce a result larger than their operands with:
5946     //   shuffle(concat(v1, undef), concat(v2, undef))
5947     // ->
5948     //   shuffle(concat(v1, v2), undef)
5949     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5950     //
5951     // This is useful in the general case, but there are special cases where
5952     // native shuffles produce larger results: the two-result ops.
5953     //
5954     // Look through the concat when lowering them:
5955     //   shuffle(concat(v1, v2), undef)
5956     // ->
5957     //   concat(VZIP(v1, v2):0, :1)
5958     //
5959     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5960         V2->getOpcode() == ISD::UNDEF) {
5961       SDValue SubV1 = V1->getOperand(0);
5962       SDValue SubV2 = V1->getOperand(1);
5963       EVT SubVT = SubV1.getValueType();
5964
5965       // We expect these to have been canonicalized to -1.
5966       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5967         return i < (int)VT.getVectorNumElements();
5968       }) && "Unexpected shuffle index into UNDEF operand!");
5969
5970       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5971               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5972         if (isV_UNDEF)
5973           SubV2 = SubV1;
5974         assert((WhichResult == 0) &&
5975                "In-place shuffle of concat can only have one result!");
5976         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5977                                   SubV1, SubV2);
5978         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5979                            Res.getValue(1));
5980       }
5981     }
5982   }
5983
5984   // If the shuffle is not directly supported and it has 4 elements, use
5985   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5986   unsigned NumElts = VT.getVectorNumElements();
5987   if (NumElts == 4) {
5988     unsigned PFIndexes[4];
5989     for (unsigned i = 0; i != 4; ++i) {
5990       if (ShuffleMask[i] < 0)
5991         PFIndexes[i] = 8;
5992       else
5993         PFIndexes[i] = ShuffleMask[i];
5994     }
5995
5996     // Compute the index in the perfect shuffle table.
5997     unsigned PFTableIndex =
5998       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5999     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6000     unsigned Cost = (PFEntry >> 30);
6001
6002     if (Cost <= 4)
6003       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6004   }
6005
6006   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6007   if (EltSize >= 32) {
6008     // Do the expansion with floating-point types, since that is what the VFP
6009     // registers are defined to use, and since i64 is not legal.
6010     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6011     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6012     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6013     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6014     SmallVector<SDValue, 8> Ops;
6015     for (unsigned i = 0; i < NumElts; ++i) {
6016       if (ShuffleMask[i] < 0)
6017         Ops.push_back(DAG.getUNDEF(EltVT));
6018       else
6019         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6020                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6021                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6022                                                   dl, MVT::i32)));
6023     }
6024     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6025     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6026   }
6027
6028   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6029     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6030
6031   if (VT == MVT::v8i8) {
6032     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6033     if (NewOp.getNode())
6034       return NewOp;
6035   }
6036
6037   return SDValue();
6038 }
6039
6040 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6041   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6042   SDValue Lane = Op.getOperand(2);
6043   if (!isa<ConstantSDNode>(Lane))
6044     return SDValue();
6045
6046   return Op;
6047 }
6048
6049 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6050   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6051   SDValue Lane = Op.getOperand(1);
6052   if (!isa<ConstantSDNode>(Lane))
6053     return SDValue();
6054
6055   SDValue Vec = Op.getOperand(0);
6056   if (Op.getValueType() == MVT::i32 &&
6057       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6058     SDLoc dl(Op);
6059     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6060   }
6061
6062   return Op;
6063 }
6064
6065 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6066   // The only time a CONCAT_VECTORS operation can have legal types is when
6067   // two 64-bit vectors are concatenated to a 128-bit vector.
6068   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6069          "unexpected CONCAT_VECTORS");
6070   SDLoc dl(Op);
6071   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6072   SDValue Op0 = Op.getOperand(0);
6073   SDValue Op1 = Op.getOperand(1);
6074   if (Op0.getOpcode() != ISD::UNDEF)
6075     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6076                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6077                       DAG.getIntPtrConstant(0, dl));
6078   if (Op1.getOpcode() != ISD::UNDEF)
6079     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6080                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6081                       DAG.getIntPtrConstant(1, dl));
6082   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6083 }
6084
6085 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6086 /// element has been zero/sign-extended, depending on the isSigned parameter,
6087 /// from an integer type half its size.
6088 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6089                                    bool isSigned) {
6090   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6091   EVT VT = N->getValueType(0);
6092   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6093     SDNode *BVN = N->getOperand(0).getNode();
6094     if (BVN->getValueType(0) != MVT::v4i32 ||
6095         BVN->getOpcode() != ISD::BUILD_VECTOR)
6096       return false;
6097     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6098     unsigned HiElt = 1 - LoElt;
6099     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6100     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6101     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6102     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6103     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6104       return false;
6105     if (isSigned) {
6106       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6107           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6108         return true;
6109     } else {
6110       if (Hi0->isNullValue() && Hi1->isNullValue())
6111         return true;
6112     }
6113     return false;
6114   }
6115
6116   if (N->getOpcode() != ISD::BUILD_VECTOR)
6117     return false;
6118
6119   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6120     SDNode *Elt = N->getOperand(i).getNode();
6121     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6122       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6123       unsigned HalfSize = EltSize / 2;
6124       if (isSigned) {
6125         if (!isIntN(HalfSize, C->getSExtValue()))
6126           return false;
6127       } else {
6128         if (!isUIntN(HalfSize, C->getZExtValue()))
6129           return false;
6130       }
6131       continue;
6132     }
6133     return false;
6134   }
6135
6136   return true;
6137 }
6138
6139 /// isSignExtended - Check if a node is a vector value that is sign-extended
6140 /// or a constant BUILD_VECTOR with sign-extended elements.
6141 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6142   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6143     return true;
6144   if (isExtendedBUILD_VECTOR(N, DAG, true))
6145     return true;
6146   return false;
6147 }
6148
6149 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6150 /// or a constant BUILD_VECTOR with zero-extended elements.
6151 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6152   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6153     return true;
6154   if (isExtendedBUILD_VECTOR(N, DAG, false))
6155     return true;
6156   return false;
6157 }
6158
6159 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6160   if (OrigVT.getSizeInBits() >= 64)
6161     return OrigVT;
6162
6163   assert(OrigVT.isSimple() && "Expecting a simple value type");
6164
6165   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6166   switch (OrigSimpleTy) {
6167   default: llvm_unreachable("Unexpected Vector Type");
6168   case MVT::v2i8:
6169   case MVT::v2i16:
6170      return MVT::v2i32;
6171   case MVT::v4i8:
6172     return  MVT::v4i16;
6173   }
6174 }
6175
6176 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6177 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6178 /// We insert the required extension here to get the vector to fill a D register.
6179 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6180                                             const EVT &OrigTy,
6181                                             const EVT &ExtTy,
6182                                             unsigned ExtOpcode) {
6183   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6184   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6185   // 64-bits we need to insert a new extension so that it will be 64-bits.
6186   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6187   if (OrigTy.getSizeInBits() >= 64)
6188     return N;
6189
6190   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6191   EVT NewVT = getExtensionTo64Bits(OrigTy);
6192
6193   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6194 }
6195
6196 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6197 /// does not do any sign/zero extension. If the original vector is less
6198 /// than 64 bits, an appropriate extension will be added after the load to
6199 /// reach a total size of 64 bits. We have to add the extension separately
6200 /// because ARM does not have a sign/zero extending load for vectors.
6201 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6202   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6203
6204   // The load already has the right type.
6205   if (ExtendedTy == LD->getMemoryVT())
6206     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6207                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6208                 LD->isNonTemporal(), LD->isInvariant(),
6209                 LD->getAlignment());
6210
6211   // We need to create a zextload/sextload. We cannot just create a load
6212   // followed by a zext/zext node because LowerMUL is also run during normal
6213   // operation legalization where we can't create illegal types.
6214   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6215                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6216                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6217                         LD->isNonTemporal(), LD->getAlignment());
6218 }
6219
6220 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6221 /// extending load, or BUILD_VECTOR with extended elements, return the
6222 /// unextended value. The unextended vector should be 64 bits so that it can
6223 /// be used as an operand to a VMULL instruction. If the original vector size
6224 /// before extension is less than 64 bits we add a an extension to resize
6225 /// the vector to 64 bits.
6226 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6227   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6228     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6229                                         N->getOperand(0)->getValueType(0),
6230                                         N->getValueType(0),
6231                                         N->getOpcode());
6232
6233   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6234     return SkipLoadExtensionForVMULL(LD, DAG);
6235
6236   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6237   // have been legalized as a BITCAST from v4i32.
6238   if (N->getOpcode() == ISD::BITCAST) {
6239     SDNode *BVN = N->getOperand(0).getNode();
6240     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6241            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6242     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6243     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6244                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6245   }
6246   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6247   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6248   EVT VT = N->getValueType(0);
6249   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6250   unsigned NumElts = VT.getVectorNumElements();
6251   MVT TruncVT = MVT::getIntegerVT(EltSize);
6252   SmallVector<SDValue, 8> Ops;
6253   SDLoc dl(N);
6254   for (unsigned i = 0; i != NumElts; ++i) {
6255     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6256     const APInt &CInt = C->getAPIntValue();
6257     // Element types smaller than 32 bits are not legal, so use i32 elements.
6258     // The values are implicitly truncated so sext vs. zext doesn't matter.
6259     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6260   }
6261   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6262                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6263 }
6264
6265 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6266   unsigned Opcode = N->getOpcode();
6267   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6268     SDNode *N0 = N->getOperand(0).getNode();
6269     SDNode *N1 = N->getOperand(1).getNode();
6270     return N0->hasOneUse() && N1->hasOneUse() &&
6271       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6272   }
6273   return false;
6274 }
6275
6276 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6277   unsigned Opcode = N->getOpcode();
6278   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6279     SDNode *N0 = N->getOperand(0).getNode();
6280     SDNode *N1 = N->getOperand(1).getNode();
6281     return N0->hasOneUse() && N1->hasOneUse() &&
6282       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6283   }
6284   return false;
6285 }
6286
6287 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6288   // Multiplications are only custom-lowered for 128-bit vectors so that
6289   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6290   EVT VT = Op.getValueType();
6291   assert(VT.is128BitVector() && VT.isInteger() &&
6292          "unexpected type for custom-lowering ISD::MUL");
6293   SDNode *N0 = Op.getOperand(0).getNode();
6294   SDNode *N1 = Op.getOperand(1).getNode();
6295   unsigned NewOpc = 0;
6296   bool isMLA = false;
6297   bool isN0SExt = isSignExtended(N0, DAG);
6298   bool isN1SExt = isSignExtended(N1, DAG);
6299   if (isN0SExt && isN1SExt)
6300     NewOpc = ARMISD::VMULLs;
6301   else {
6302     bool isN0ZExt = isZeroExtended(N0, DAG);
6303     bool isN1ZExt = isZeroExtended(N1, DAG);
6304     if (isN0ZExt && isN1ZExt)
6305       NewOpc = ARMISD::VMULLu;
6306     else if (isN1SExt || isN1ZExt) {
6307       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6308       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6309       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6310         NewOpc = ARMISD::VMULLs;
6311         isMLA = true;
6312       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6313         NewOpc = ARMISD::VMULLu;
6314         isMLA = true;
6315       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6316         std::swap(N0, N1);
6317         NewOpc = ARMISD::VMULLu;
6318         isMLA = true;
6319       }
6320     }
6321
6322     if (!NewOpc) {
6323       if (VT == MVT::v2i64)
6324         // Fall through to expand this.  It is not legal.
6325         return SDValue();
6326       else
6327         // Other vector multiplications are legal.
6328         return Op;
6329     }
6330   }
6331
6332   // Legalize to a VMULL instruction.
6333   SDLoc DL(Op);
6334   SDValue Op0;
6335   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6336   if (!isMLA) {
6337     Op0 = SkipExtensionForVMULL(N0, DAG);
6338     assert(Op0.getValueType().is64BitVector() &&
6339            Op1.getValueType().is64BitVector() &&
6340            "unexpected types for extended operands to VMULL");
6341     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6342   }
6343
6344   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6345   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6346   //   vmull q0, d4, d6
6347   //   vmlal q0, d5, d6
6348   // is faster than
6349   //   vaddl q0, d4, d5
6350   //   vmovl q1, d6
6351   //   vmul  q0, q0, q1
6352   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6353   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6354   EVT Op1VT = Op1.getValueType();
6355   return DAG.getNode(N0->getOpcode(), DL, VT,
6356                      DAG.getNode(NewOpc, DL, VT,
6357                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6358                      DAG.getNode(NewOpc, DL, VT,
6359                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6360 }
6361
6362 static SDValue
6363 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6364   // TODO: Should this propagate fast-math-flags?
6365
6366   // Convert to float
6367   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6368   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6369   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6370   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6371   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6372   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6373   // Get reciprocal estimate.
6374   // float4 recip = vrecpeq_f32(yf);
6375   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6376                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6377                    Y);
6378   // Because char has a smaller range than uchar, we can actually get away
6379   // without any newton steps.  This requires that we use a weird bias
6380   // of 0xb000, however (again, this has been exhaustively tested).
6381   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6382   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6383   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6384   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6385   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6386   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6387   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6388   // Convert back to short.
6389   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6390   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6391   return X;
6392 }
6393
6394 static SDValue
6395 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6396   // TODO: Should this propagate fast-math-flags?
6397
6398   SDValue N2;
6399   // Convert to float.
6400   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6401   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6402   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6403   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6404   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6405   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6406
6407   // Use reciprocal estimate and one refinement step.
6408   // float4 recip = vrecpeq_f32(yf);
6409   // recip *= vrecpsq_f32(yf, recip);
6410   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6411                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6412                    N1);
6413   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6414                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6415                    N1, N2);
6416   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6417   // Because short has a smaller range than ushort, we can actually get away
6418   // with only a single newton step.  This requires that we use a weird bias
6419   // of 89, however (again, this has been exhaustively tested).
6420   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6421   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6422   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6423   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6424   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6425   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6426   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6427   // Convert back to integer and return.
6428   // return vmovn_s32(vcvt_s32_f32(result));
6429   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6430   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6431   return N0;
6432 }
6433
6434 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6435   EVT VT = Op.getValueType();
6436   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6437          "unexpected type for custom-lowering ISD::SDIV");
6438
6439   SDLoc dl(Op);
6440   SDValue N0 = Op.getOperand(0);
6441   SDValue N1 = Op.getOperand(1);
6442   SDValue N2, N3;
6443
6444   if (VT == MVT::v8i8) {
6445     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6446     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6447
6448     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6449                      DAG.getIntPtrConstant(4, dl));
6450     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6451                      DAG.getIntPtrConstant(4, dl));
6452     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6453                      DAG.getIntPtrConstant(0, dl));
6454     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6455                      DAG.getIntPtrConstant(0, dl));
6456
6457     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6458     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6459
6460     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6461     N0 = LowerCONCAT_VECTORS(N0, DAG);
6462
6463     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6464     return N0;
6465   }
6466   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6467 }
6468
6469 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6470   // TODO: Should this propagate fast-math-flags?
6471   EVT VT = Op.getValueType();
6472   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6473          "unexpected type for custom-lowering ISD::UDIV");
6474
6475   SDLoc dl(Op);
6476   SDValue N0 = Op.getOperand(0);
6477   SDValue N1 = Op.getOperand(1);
6478   SDValue N2, N3;
6479
6480   if (VT == MVT::v8i8) {
6481     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6482     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6483
6484     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6485                      DAG.getIntPtrConstant(4, dl));
6486     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6487                      DAG.getIntPtrConstant(4, dl));
6488     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6489                      DAG.getIntPtrConstant(0, dl));
6490     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6491                      DAG.getIntPtrConstant(0, dl));
6492
6493     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6494     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6495
6496     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6497     N0 = LowerCONCAT_VECTORS(N0, DAG);
6498
6499     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6500                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6501                                      MVT::i32),
6502                      N0);
6503     return N0;
6504   }
6505
6506   // v4i16 sdiv ... Convert to float.
6507   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6508   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6509   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6510   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6511   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6512   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6513
6514   // Use reciprocal estimate and two refinement steps.
6515   // float4 recip = vrecpeq_f32(yf);
6516   // recip *= vrecpsq_f32(yf, recip);
6517   // recip *= vrecpsq_f32(yf, recip);
6518   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6519                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6520                    BN1);
6521   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6522                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6523                    BN1, N2);
6524   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6525   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6526                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6527                    BN1, N2);
6528   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6529   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6530   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6531   // and that it will never cause us to return an answer too large).
6532   // float4 result = as_float4(as_int4(xf*recip) + 2);
6533   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6534   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6535   N1 = DAG.getConstant(2, dl, MVT::i32);
6536   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6537   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6538   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6539   // Convert back to integer and return.
6540   // return vmovn_u32(vcvt_s32_f32(result));
6541   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6542   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6543   return N0;
6544 }
6545
6546 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6547   EVT VT = Op.getNode()->getValueType(0);
6548   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6549
6550   unsigned Opc;
6551   bool ExtraOp = false;
6552   switch (Op.getOpcode()) {
6553   default: llvm_unreachable("Invalid code");
6554   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6555   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6556   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6557   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6558   }
6559
6560   if (!ExtraOp)
6561     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6562                        Op.getOperand(1));
6563   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6564                      Op.getOperand(1), Op.getOperand(2));
6565 }
6566
6567 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6568   assert(Subtarget->isTargetDarwin());
6569
6570   // For iOS, we want to call an alternative entry point: __sincos_stret,
6571   // return values are passed via sret.
6572   SDLoc dl(Op);
6573   SDValue Arg = Op.getOperand(0);
6574   EVT ArgVT = Arg.getValueType();
6575   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6576   auto PtrVT = getPointerTy(DAG.getDataLayout());
6577
6578   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6579
6580   // Pair of floats / doubles used to pass the result.
6581   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6582
6583   // Create stack object for sret.
6584   auto &DL = DAG.getDataLayout();
6585   const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6586   const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6587   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6588   SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6589
6590   ArgListTy Args;
6591   ArgListEntry Entry;
6592
6593   Entry.Node = SRet;
6594   Entry.Ty = RetTy->getPointerTo();
6595   Entry.isSExt = false;
6596   Entry.isZExt = false;
6597   Entry.isSRet = true;
6598   Args.push_back(Entry);
6599
6600   Entry.Node = Arg;
6601   Entry.Ty = ArgTy;
6602   Entry.isSExt = false;
6603   Entry.isZExt = false;
6604   Args.push_back(Entry);
6605
6606   const char *LibcallName =
6607       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6608   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6609
6610   TargetLowering::CallLoweringInfo CLI(DAG);
6611   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6612     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6613                std::move(Args), 0)
6614     .setDiscardResult();
6615
6616   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6617
6618   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6619                                 MachinePointerInfo(), false, false, false, 0);
6620
6621   // Address of cos field.
6622   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6623                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6624   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6625                                 MachinePointerInfo(), false, false, false, 0);
6626
6627   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6628   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6629                      LoadSin.getValue(0), LoadCos.getValue(0));
6630 }
6631
6632 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6633                                                   bool Signed,
6634                                                   SDValue &Chain) const {
6635   EVT VT = Op.getValueType();
6636   assert((VT == MVT::i32 || VT == MVT::i64) &&
6637          "unexpected type for custom lowering DIV");
6638   SDLoc dl(Op);
6639
6640   const auto &DL = DAG.getDataLayout();
6641   const auto &TLI = DAG.getTargetLoweringInfo();
6642
6643   const char *Name = nullptr;
6644   if (Signed)
6645     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6646   else
6647     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6648
6649   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6650
6651   ARMTargetLowering::ArgListTy Args;
6652
6653   for (auto AI : {1, 0}) {
6654     ArgListEntry Arg;
6655     Arg.Node = Op.getOperand(AI);
6656     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6657     Args.push_back(Arg);
6658   }
6659
6660   CallLoweringInfo CLI(DAG);
6661   CLI.setDebugLoc(dl)
6662     .setChain(Chain)
6663     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6664                ES, std::move(Args), 0);
6665
6666   return LowerCallTo(CLI).first;
6667 }
6668
6669 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
6670                                             bool Signed) const {
6671   assert(Op.getValueType() == MVT::i32 &&
6672          "unexpected type for custom lowering DIV");
6673   SDLoc dl(Op);
6674
6675   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6676                                DAG.getEntryNode(), Op.getOperand(1));
6677
6678   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6679 }
6680
6681 void ARMTargetLowering::ExpandDIV_Windows(
6682     SDValue Op, SelectionDAG &DAG, bool Signed,
6683     SmallVectorImpl<SDValue> &Results) const {
6684   const auto &DL = DAG.getDataLayout();
6685   const auto &TLI = DAG.getTargetLoweringInfo();
6686
6687   assert(Op.getValueType() == MVT::i64 &&
6688          "unexpected type for custom lowering DIV");
6689   SDLoc dl(Op);
6690
6691   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6692                            DAG.getConstant(0, dl, MVT::i32));
6693   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6694                            DAG.getConstant(1, dl, MVT::i32));
6695   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6696
6697   SDValue DBZCHK =
6698       DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6699
6700   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6701
6702   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6703   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6704                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6705   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6706
6707   Results.push_back(Lower);
6708   Results.push_back(Upper);
6709 }
6710
6711 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6712   // Monotonic load/store is legal for all targets
6713   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6714     return Op;
6715
6716   // Acquire/Release load/store is not legal for targets without a
6717   // dmb or equivalent available.
6718   return SDValue();
6719 }
6720
6721 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6722                                     SmallVectorImpl<SDValue> &Results,
6723                                     SelectionDAG &DAG,
6724                                     const ARMSubtarget *Subtarget) {
6725   SDLoc DL(N);
6726   // Under Power Management extensions, the cycle-count is:
6727   //    mrc p15, #0, <Rt>, c9, c13, #0
6728   SDValue Ops[] = { N->getOperand(0), // Chain
6729                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6730                     DAG.getConstant(15, DL, MVT::i32),
6731                     DAG.getConstant(0, DL, MVT::i32),
6732                     DAG.getConstant(9, DL, MVT::i32),
6733                     DAG.getConstant(13, DL, MVT::i32),
6734                     DAG.getConstant(0, DL, MVT::i32)
6735   };
6736
6737   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6738                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
6739   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6740                                 DAG.getConstant(0, DL, MVT::i32)));
6741   Results.push_back(Cycles32.getValue(1));
6742 }
6743
6744 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6745   switch (Op.getOpcode()) {
6746   default: llvm_unreachable("Don't know how to custom lower this!");
6747   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6748   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6749   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6750   case ISD::GlobalAddress:
6751     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6752     default: llvm_unreachable("unknown object format");
6753     case Triple::COFF:
6754       return LowerGlobalAddressWindows(Op, DAG);
6755     case Triple::ELF:
6756       return LowerGlobalAddressELF(Op, DAG);
6757     case Triple::MachO:
6758       return LowerGlobalAddressDarwin(Op, DAG);
6759     }
6760   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6761   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6762   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6763   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6764   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6765   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6766   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6767   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6768   case ISD::SINT_TO_FP:
6769   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6770   case ISD::FP_TO_SINT:
6771   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6772   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6773   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6774   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6775   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6776   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6777   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6778   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6779                                                                Subtarget);
6780   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6781   case ISD::SHL:
6782   case ISD::SRL:
6783   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6784   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
6785   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
6786   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6787   case ISD::SRL_PARTS:
6788   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6789   case ISD::CTTZ:
6790   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6791   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6792   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6793   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6794   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6795   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6796   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6797   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6798   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6799   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6800   case ISD::MUL:           return LowerMUL(Op, DAG);
6801   case ISD::SDIV:
6802     if (Subtarget->isTargetWindows())
6803       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
6804     return LowerSDIV(Op, DAG);
6805   case ISD::UDIV:
6806     if (Subtarget->isTargetWindows())
6807       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
6808     return LowerUDIV(Op, DAG);
6809   case ISD::ADDC:
6810   case ISD::ADDE:
6811   case ISD::SUBC:
6812   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6813   case ISD::SADDO:
6814   case ISD::UADDO:
6815   case ISD::SSUBO:
6816   case ISD::USUBO:
6817     return LowerXALUO(Op, DAG);
6818   case ISD::ATOMIC_LOAD:
6819   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6820   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6821   case ISD::SDIVREM:
6822   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6823   case ISD::DYNAMIC_STACKALLOC:
6824     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6825       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6826     llvm_unreachable("Don't know how to custom lower this!");
6827   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6828   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6829   case ARMISD::WIN__DBZCHK: return SDValue();
6830   }
6831 }
6832
6833 /// ReplaceNodeResults - Replace the results of node with an illegal result
6834 /// type with new values built out of custom code.
6835 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6836                                            SmallVectorImpl<SDValue> &Results,
6837                                            SelectionDAG &DAG) const {
6838   SDValue Res;
6839   switch (N->getOpcode()) {
6840   default:
6841     llvm_unreachable("Don't know how to custom expand this!");
6842   case ISD::READ_REGISTER:
6843     ExpandREAD_REGISTER(N, Results, DAG);
6844     break;
6845   case ISD::BITCAST:
6846     Res = ExpandBITCAST(N, DAG);
6847     break;
6848   case ISD::SRL:
6849   case ISD::SRA:
6850     Res = Expand64BitShift(N, DAG, Subtarget);
6851     break;
6852   case ISD::SREM:
6853   case ISD::UREM:
6854     Res = LowerREM(N, DAG);
6855     break;
6856   case ISD::READCYCLECOUNTER:
6857     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6858     return;
6859   case ISD::UDIV:
6860   case ISD::SDIV:
6861     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
6862     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
6863                              Results);
6864   }
6865   if (Res.getNode())
6866     Results.push_back(Res);
6867 }
6868
6869 //===----------------------------------------------------------------------===//
6870 //                           ARM Scheduler Hooks
6871 //===----------------------------------------------------------------------===//
6872
6873 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6874 /// registers the function context.
6875 void ARMTargetLowering::
6876 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6877                        MachineBasicBlock *DispatchBB, int FI) const {
6878   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6879   DebugLoc dl = MI->getDebugLoc();
6880   MachineFunction *MF = MBB->getParent();
6881   MachineRegisterInfo *MRI = &MF->getRegInfo();
6882   MachineConstantPool *MCP = MF->getConstantPool();
6883   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6884   const Function *F = MF->getFunction();
6885
6886   bool isThumb = Subtarget->isThumb();
6887   bool isThumb2 = Subtarget->isThumb2();
6888
6889   unsigned PCLabelId = AFI->createPICLabelUId();
6890   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6891   ARMConstantPoolValue *CPV =
6892     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6893   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6894
6895   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6896                                            : &ARM::GPRRegClass;
6897
6898   // Grab constant pool and fixed stack memory operands.
6899   MachineMemOperand *CPMMO =
6900       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6901                                MachineMemOperand::MOLoad, 4, 4);
6902
6903   MachineMemOperand *FIMMOSt =
6904       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6905                                MachineMemOperand::MOStore, 4, 4);
6906
6907   // Load the address of the dispatch MBB into the jump buffer.
6908   if (isThumb2) {
6909     // Incoming value: jbuf
6910     //   ldr.n  r5, LCPI1_1
6911     //   orr    r5, r5, #1
6912     //   add    r5, pc
6913     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6914     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6915     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6916                    .addConstantPoolIndex(CPI)
6917                    .addMemOperand(CPMMO));
6918     // Set the low bit because of thumb mode.
6919     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6920     AddDefaultCC(
6921       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6922                      .addReg(NewVReg1, RegState::Kill)
6923                      .addImm(0x01)));
6924     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6925     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6926       .addReg(NewVReg2, RegState::Kill)
6927       .addImm(PCLabelId);
6928     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6929                    .addReg(NewVReg3, RegState::Kill)
6930                    .addFrameIndex(FI)
6931                    .addImm(36)  // &jbuf[1] :: pc
6932                    .addMemOperand(FIMMOSt));
6933   } else if (isThumb) {
6934     // Incoming value: jbuf
6935     //   ldr.n  r1, LCPI1_4
6936     //   add    r1, pc
6937     //   mov    r2, #1
6938     //   orrs   r1, r2
6939     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6940     //   str    r1, [r2]
6941     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6942     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6943                    .addConstantPoolIndex(CPI)
6944                    .addMemOperand(CPMMO));
6945     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6946     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6947       .addReg(NewVReg1, RegState::Kill)
6948       .addImm(PCLabelId);
6949     // Set the low bit because of thumb mode.
6950     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6951     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6952                    .addReg(ARM::CPSR, RegState::Define)
6953                    .addImm(1));
6954     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6955     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6956                    .addReg(ARM::CPSR, RegState::Define)
6957                    .addReg(NewVReg2, RegState::Kill)
6958                    .addReg(NewVReg3, RegState::Kill));
6959     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6960     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6961             .addFrameIndex(FI)
6962             .addImm(36); // &jbuf[1] :: pc
6963     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6964                    .addReg(NewVReg4, RegState::Kill)
6965                    .addReg(NewVReg5, RegState::Kill)
6966                    .addImm(0)
6967                    .addMemOperand(FIMMOSt));
6968   } else {
6969     // Incoming value: jbuf
6970     //   ldr  r1, LCPI1_1
6971     //   add  r1, pc, r1
6972     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6973     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6974     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6975                    .addConstantPoolIndex(CPI)
6976                    .addImm(0)
6977                    .addMemOperand(CPMMO));
6978     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6979     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6980                    .addReg(NewVReg1, RegState::Kill)
6981                    .addImm(PCLabelId));
6982     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6983                    .addReg(NewVReg2, RegState::Kill)
6984                    .addFrameIndex(FI)
6985                    .addImm(36)  // &jbuf[1] :: pc
6986                    .addMemOperand(FIMMOSt));
6987   }
6988 }
6989
6990 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6991                                               MachineBasicBlock *MBB) const {
6992   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6993   DebugLoc dl = MI->getDebugLoc();
6994   MachineFunction *MF = MBB->getParent();
6995   MachineRegisterInfo *MRI = &MF->getRegInfo();
6996   MachineFrameInfo *MFI = MF->getFrameInfo();
6997   int FI = MFI->getFunctionContextIndex();
6998
6999   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7000                                                         : &ARM::GPRnopcRegClass;
7001
7002   // Get a mapping of the call site numbers to all of the landing pads they're
7003   // associated with.
7004   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7005   unsigned MaxCSNum = 0;
7006   MachineModuleInfo &MMI = MF->getMMI();
7007   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7008        ++BB) {
7009     if (!BB->isEHPad()) continue;
7010
7011     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7012     // pad.
7013     for (MachineBasicBlock::iterator
7014            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7015       if (!II->isEHLabel()) continue;
7016
7017       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7018       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7019
7020       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7021       for (SmallVectorImpl<unsigned>::iterator
7022              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7023            CSI != CSE; ++CSI) {
7024         CallSiteNumToLPad[*CSI].push_back(&*BB);
7025         MaxCSNum = std::max(MaxCSNum, *CSI);
7026       }
7027       break;
7028     }
7029   }
7030
7031   // Get an ordered list of the machine basic blocks for the jump table.
7032   std::vector<MachineBasicBlock*> LPadList;
7033   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7034   LPadList.reserve(CallSiteNumToLPad.size());
7035   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7036     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7037     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7038            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7039       LPadList.push_back(*II);
7040       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7041     }
7042   }
7043
7044   assert(!LPadList.empty() &&
7045          "No landing pad destinations for the dispatch jump table!");
7046
7047   // Create the jump table and associated information.
7048   MachineJumpTableInfo *JTI =
7049     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7050   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7051   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7052
7053   // Create the MBBs for the dispatch code.
7054
7055   // Shove the dispatch's address into the return slot in the function context.
7056   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7057   DispatchBB->setIsEHPad();
7058
7059   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7060   unsigned trap_opcode;
7061   if (Subtarget->isThumb())
7062     trap_opcode = ARM::tTRAP;
7063   else
7064     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7065
7066   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7067   DispatchBB->addSuccessor(TrapBB);
7068
7069   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7070   DispatchBB->addSuccessor(DispContBB);
7071
7072   // Insert and MBBs.
7073   MF->insert(MF->end(), DispatchBB);
7074   MF->insert(MF->end(), DispContBB);
7075   MF->insert(MF->end(), TrapBB);
7076
7077   // Insert code into the entry block that creates and registers the function
7078   // context.
7079   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7080
7081   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7082       MachinePointerInfo::getFixedStack(*MF, FI),
7083       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7084
7085   MachineInstrBuilder MIB;
7086   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7087
7088   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7089   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7090
7091   // Add a register mask with no preserved registers.  This results in all
7092   // registers being marked as clobbered.
7093   MIB.addRegMask(RI.getNoPreservedMask());
7094
7095   unsigned NumLPads = LPadList.size();
7096   if (Subtarget->isThumb2()) {
7097     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7098     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7099                    .addFrameIndex(FI)
7100                    .addImm(4)
7101                    .addMemOperand(FIMMOLd));
7102
7103     if (NumLPads < 256) {
7104       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7105                      .addReg(NewVReg1)
7106                      .addImm(LPadList.size()));
7107     } else {
7108       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7109       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7110                      .addImm(NumLPads & 0xFFFF));
7111
7112       unsigned VReg2 = VReg1;
7113       if ((NumLPads & 0xFFFF0000) != 0) {
7114         VReg2 = MRI->createVirtualRegister(TRC);
7115         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7116                        .addReg(VReg1)
7117                        .addImm(NumLPads >> 16));
7118       }
7119
7120       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7121                      .addReg(NewVReg1)
7122                      .addReg(VReg2));
7123     }
7124
7125     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7126       .addMBB(TrapBB)
7127       .addImm(ARMCC::HI)
7128       .addReg(ARM::CPSR);
7129
7130     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7131     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7132                    .addJumpTableIndex(MJTI));
7133
7134     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7135     AddDefaultCC(
7136       AddDefaultPred(
7137         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7138         .addReg(NewVReg3, RegState::Kill)
7139         .addReg(NewVReg1)
7140         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7141
7142     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7143       .addReg(NewVReg4, RegState::Kill)
7144       .addReg(NewVReg1)
7145       .addJumpTableIndex(MJTI);
7146   } else if (Subtarget->isThumb()) {
7147     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7148     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7149                    .addFrameIndex(FI)
7150                    .addImm(1)
7151                    .addMemOperand(FIMMOLd));
7152
7153     if (NumLPads < 256) {
7154       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7155                      .addReg(NewVReg1)
7156                      .addImm(NumLPads));
7157     } else {
7158       MachineConstantPool *ConstantPool = MF->getConstantPool();
7159       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7160       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7161
7162       // MachineConstantPool wants an explicit alignment.
7163       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7164       if (Align == 0)
7165         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7166       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7167
7168       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7169       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7170                      .addReg(VReg1, RegState::Define)
7171                      .addConstantPoolIndex(Idx));
7172       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7173                      .addReg(NewVReg1)
7174                      .addReg(VReg1));
7175     }
7176
7177     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7178       .addMBB(TrapBB)
7179       .addImm(ARMCC::HI)
7180       .addReg(ARM::CPSR);
7181
7182     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7183     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7184                    .addReg(ARM::CPSR, RegState::Define)
7185                    .addReg(NewVReg1)
7186                    .addImm(2));
7187
7188     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7189     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7190                    .addJumpTableIndex(MJTI));
7191
7192     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7193     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7194                    .addReg(ARM::CPSR, RegState::Define)
7195                    .addReg(NewVReg2, RegState::Kill)
7196                    .addReg(NewVReg3));
7197
7198     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7199         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7200
7201     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7202     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7203                    .addReg(NewVReg4, RegState::Kill)
7204                    .addImm(0)
7205                    .addMemOperand(JTMMOLd));
7206
7207     unsigned NewVReg6 = NewVReg5;
7208     if (RelocM == Reloc::PIC_) {
7209       NewVReg6 = MRI->createVirtualRegister(TRC);
7210       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7211                      .addReg(ARM::CPSR, RegState::Define)
7212                      .addReg(NewVReg5, RegState::Kill)
7213                      .addReg(NewVReg3));
7214     }
7215
7216     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7217       .addReg(NewVReg6, RegState::Kill)
7218       .addJumpTableIndex(MJTI);
7219   } else {
7220     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7221     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7222                    .addFrameIndex(FI)
7223                    .addImm(4)
7224                    .addMemOperand(FIMMOLd));
7225
7226     if (NumLPads < 256) {
7227       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7228                      .addReg(NewVReg1)
7229                      .addImm(NumLPads));
7230     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7231       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7232       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7233                      .addImm(NumLPads & 0xFFFF));
7234
7235       unsigned VReg2 = VReg1;
7236       if ((NumLPads & 0xFFFF0000) != 0) {
7237         VReg2 = MRI->createVirtualRegister(TRC);
7238         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7239                        .addReg(VReg1)
7240                        .addImm(NumLPads >> 16));
7241       }
7242
7243       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7244                      .addReg(NewVReg1)
7245                      .addReg(VReg2));
7246     } else {
7247       MachineConstantPool *ConstantPool = MF->getConstantPool();
7248       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7249       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7250
7251       // MachineConstantPool wants an explicit alignment.
7252       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7253       if (Align == 0)
7254         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7255       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7256
7257       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7258       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7259                      .addReg(VReg1, RegState::Define)
7260                      .addConstantPoolIndex(Idx)
7261                      .addImm(0));
7262       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7263                      .addReg(NewVReg1)
7264                      .addReg(VReg1, RegState::Kill));
7265     }
7266
7267     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7268       .addMBB(TrapBB)
7269       .addImm(ARMCC::HI)
7270       .addReg(ARM::CPSR);
7271
7272     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7273     AddDefaultCC(
7274       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7275                      .addReg(NewVReg1)
7276                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7277     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7278     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7279                    .addJumpTableIndex(MJTI));
7280
7281     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7282         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7283     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7284     AddDefaultPred(
7285       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7286       .addReg(NewVReg3, RegState::Kill)
7287       .addReg(NewVReg4)
7288       .addImm(0)
7289       .addMemOperand(JTMMOLd));
7290
7291     if (RelocM == Reloc::PIC_) {
7292       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7293         .addReg(NewVReg5, RegState::Kill)
7294         .addReg(NewVReg4)
7295         .addJumpTableIndex(MJTI);
7296     } else {
7297       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7298         .addReg(NewVReg5, RegState::Kill)
7299         .addJumpTableIndex(MJTI);
7300     }
7301   }
7302
7303   // Add the jump table entries as successors to the MBB.
7304   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7305   for (std::vector<MachineBasicBlock*>::iterator
7306          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7307     MachineBasicBlock *CurMBB = *I;
7308     if (SeenMBBs.insert(CurMBB).second)
7309       DispContBB->addSuccessor(CurMBB);
7310   }
7311
7312   // N.B. the order the invoke BBs are processed in doesn't matter here.
7313   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7314   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7315   for (MachineBasicBlock *BB : InvokeBBs) {
7316
7317     // Remove the landing pad successor from the invoke block and replace it
7318     // with the new dispatch block.
7319     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7320                                                   BB->succ_end());
7321     while (!Successors.empty()) {
7322       MachineBasicBlock *SMBB = Successors.pop_back_val();
7323       if (SMBB->isEHPad()) {
7324         BB->removeSuccessor(SMBB);
7325         MBBLPads.push_back(SMBB);
7326       }
7327     }
7328
7329     BB->addSuccessor(DispatchBB);
7330
7331     // Find the invoke call and mark all of the callee-saved registers as
7332     // 'implicit defined' so that they're spilled. This prevents code from
7333     // moving instructions to before the EH block, where they will never be
7334     // executed.
7335     for (MachineBasicBlock::reverse_iterator
7336            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7337       if (!II->isCall()) continue;
7338
7339       DenseMap<unsigned, bool> DefRegs;
7340       for (MachineInstr::mop_iterator
7341              OI = II->operands_begin(), OE = II->operands_end();
7342            OI != OE; ++OI) {
7343         if (!OI->isReg()) continue;
7344         DefRegs[OI->getReg()] = true;
7345       }
7346
7347       MachineInstrBuilder MIB(*MF, &*II);
7348
7349       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7350         unsigned Reg = SavedRegs[i];
7351         if (Subtarget->isThumb2() &&
7352             !ARM::tGPRRegClass.contains(Reg) &&
7353             !ARM::hGPRRegClass.contains(Reg))
7354           continue;
7355         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7356           continue;
7357         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7358           continue;
7359         if (!DefRegs[Reg])
7360           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7361       }
7362
7363       break;
7364     }
7365   }
7366
7367   // Mark all former landing pads as non-landing pads. The dispatch is the only
7368   // landing pad now.
7369   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7370          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7371     (*I)->setIsEHPad(false);
7372
7373   // The instruction is gone now.
7374   MI->eraseFromParent();
7375 }
7376
7377 static
7378 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7379   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7380        E = MBB->succ_end(); I != E; ++I)
7381     if (*I != Succ)
7382       return *I;
7383   llvm_unreachable("Expecting a BB with two successors!");
7384 }
7385
7386 /// Return the load opcode for a given load size. If load size >= 8,
7387 /// neon opcode will be returned.
7388 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7389   if (LdSize >= 8)
7390     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7391                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7392   if (IsThumb1)
7393     return LdSize == 4 ? ARM::tLDRi
7394                        : LdSize == 2 ? ARM::tLDRHi
7395                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7396   if (IsThumb2)
7397     return LdSize == 4 ? ARM::t2LDR_POST
7398                        : LdSize == 2 ? ARM::t2LDRH_POST
7399                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7400   return LdSize == 4 ? ARM::LDR_POST_IMM
7401                      : LdSize == 2 ? ARM::LDRH_POST
7402                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7403 }
7404
7405 /// Return the store opcode for a given store size. If store size >= 8,
7406 /// neon opcode will be returned.
7407 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7408   if (StSize >= 8)
7409     return StSize == 16 ? ARM::VST1q32wb_fixed
7410                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7411   if (IsThumb1)
7412     return StSize == 4 ? ARM::tSTRi
7413                        : StSize == 2 ? ARM::tSTRHi
7414                                      : StSize == 1 ? ARM::tSTRBi : 0;
7415   if (IsThumb2)
7416     return StSize == 4 ? ARM::t2STR_POST
7417                        : StSize == 2 ? ARM::t2STRH_POST
7418                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7419   return StSize == 4 ? ARM::STR_POST_IMM
7420                      : StSize == 2 ? ARM::STRH_POST
7421                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7422 }
7423
7424 /// Emit a post-increment load operation with given size. The instructions
7425 /// will be added to BB at Pos.
7426 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7427                        const TargetInstrInfo *TII, DebugLoc dl,
7428                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7429                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7430   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7431   assert(LdOpc != 0 && "Should have a load opcode");
7432   if (LdSize >= 8) {
7433     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7434                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7435                        .addImm(0));
7436   } else if (IsThumb1) {
7437     // load + update AddrIn
7438     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7439                        .addReg(AddrIn).addImm(0));
7440     MachineInstrBuilder MIB =
7441         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7442     MIB = AddDefaultT1CC(MIB);
7443     MIB.addReg(AddrIn).addImm(LdSize);
7444     AddDefaultPred(MIB);
7445   } else if (IsThumb2) {
7446     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7447                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7448                        .addImm(LdSize));
7449   } else { // arm
7450     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7451                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7452                        .addReg(0).addImm(LdSize));
7453   }
7454 }
7455
7456 /// Emit a post-increment store operation with given size. The instructions
7457 /// will be added to BB at Pos.
7458 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7459                        const TargetInstrInfo *TII, DebugLoc dl,
7460                        unsigned StSize, unsigned Data, unsigned AddrIn,
7461                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7462   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7463   assert(StOpc != 0 && "Should have a store opcode");
7464   if (StSize >= 8) {
7465     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7466                        .addReg(AddrIn).addImm(0).addReg(Data));
7467   } else if (IsThumb1) {
7468     // store + update AddrIn
7469     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7470                        .addReg(AddrIn).addImm(0));
7471     MachineInstrBuilder MIB =
7472         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7473     MIB = AddDefaultT1CC(MIB);
7474     MIB.addReg(AddrIn).addImm(StSize);
7475     AddDefaultPred(MIB);
7476   } else if (IsThumb2) {
7477     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7478                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7479   } else { // arm
7480     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7481                        .addReg(Data).addReg(AddrIn).addReg(0)
7482                        .addImm(StSize));
7483   }
7484 }
7485
7486 MachineBasicBlock *
7487 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7488                                    MachineBasicBlock *BB) const {
7489   // This pseudo instruction has 3 operands: dst, src, size
7490   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7491   // Otherwise, we will generate unrolled scalar copies.
7492   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7493   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7494   MachineFunction::iterator It = ++BB->getIterator();
7495
7496   unsigned dest = MI->getOperand(0).getReg();
7497   unsigned src = MI->getOperand(1).getReg();
7498   unsigned SizeVal = MI->getOperand(2).getImm();
7499   unsigned Align = MI->getOperand(3).getImm();
7500   DebugLoc dl = MI->getDebugLoc();
7501
7502   MachineFunction *MF = BB->getParent();
7503   MachineRegisterInfo &MRI = MF->getRegInfo();
7504   unsigned UnitSize = 0;
7505   const TargetRegisterClass *TRC = nullptr;
7506   const TargetRegisterClass *VecTRC = nullptr;
7507
7508   bool IsThumb1 = Subtarget->isThumb1Only();
7509   bool IsThumb2 = Subtarget->isThumb2();
7510
7511   if (Align & 1) {
7512     UnitSize = 1;
7513   } else if (Align & 2) {
7514     UnitSize = 2;
7515   } else {
7516     // Check whether we can use NEON instructions.
7517     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7518         Subtarget->hasNEON()) {
7519       if ((Align % 16 == 0) && SizeVal >= 16)
7520         UnitSize = 16;
7521       else if ((Align % 8 == 0) && SizeVal >= 8)
7522         UnitSize = 8;
7523     }
7524     // Can't use NEON instructions.
7525     if (UnitSize == 0)
7526       UnitSize = 4;
7527   }
7528
7529   // Select the correct opcode and register class for unit size load/store
7530   bool IsNeon = UnitSize >= 8;
7531   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7532   if (IsNeon)
7533     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7534                             : UnitSize == 8 ? &ARM::DPRRegClass
7535                                             : nullptr;
7536
7537   unsigned BytesLeft = SizeVal % UnitSize;
7538   unsigned LoopSize = SizeVal - BytesLeft;
7539
7540   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7541     // Use LDR and STR to copy.
7542     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7543     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7544     unsigned srcIn = src;
7545     unsigned destIn = dest;
7546     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7547       unsigned srcOut = MRI.createVirtualRegister(TRC);
7548       unsigned destOut = MRI.createVirtualRegister(TRC);
7549       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7550       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7551                  IsThumb1, IsThumb2);
7552       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7553                  IsThumb1, IsThumb2);
7554       srcIn = srcOut;
7555       destIn = destOut;
7556     }
7557
7558     // Handle the leftover bytes with LDRB and STRB.
7559     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7560     // [destOut] = STRB_POST(scratch, destIn, 1)
7561     for (unsigned i = 0; i < BytesLeft; i++) {
7562       unsigned srcOut = MRI.createVirtualRegister(TRC);
7563       unsigned destOut = MRI.createVirtualRegister(TRC);
7564       unsigned scratch = MRI.createVirtualRegister(TRC);
7565       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7566                  IsThumb1, IsThumb2);
7567       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7568                  IsThumb1, IsThumb2);
7569       srcIn = srcOut;
7570       destIn = destOut;
7571     }
7572     MI->eraseFromParent();   // The instruction is gone now.
7573     return BB;
7574   }
7575
7576   // Expand the pseudo op to a loop.
7577   // thisMBB:
7578   //   ...
7579   //   movw varEnd, # --> with thumb2
7580   //   movt varEnd, #
7581   //   ldrcp varEnd, idx --> without thumb2
7582   //   fallthrough --> loopMBB
7583   // loopMBB:
7584   //   PHI varPhi, varEnd, varLoop
7585   //   PHI srcPhi, src, srcLoop
7586   //   PHI destPhi, dst, destLoop
7587   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7588   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7589   //   subs varLoop, varPhi, #UnitSize
7590   //   bne loopMBB
7591   //   fallthrough --> exitMBB
7592   // exitMBB:
7593   //   epilogue to handle left-over bytes
7594   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7595   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7596   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7597   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7598   MF->insert(It, loopMBB);
7599   MF->insert(It, exitMBB);
7600
7601   // Transfer the remainder of BB and its successor edges to exitMBB.
7602   exitMBB->splice(exitMBB->begin(), BB,
7603                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7604   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7605
7606   // Load an immediate to varEnd.
7607   unsigned varEnd = MRI.createVirtualRegister(TRC);
7608   if (Subtarget->useMovt(*MF)) {
7609     unsigned Vtmp = varEnd;
7610     if ((LoopSize & 0xFFFF0000) != 0)
7611       Vtmp = MRI.createVirtualRegister(TRC);
7612     AddDefaultPred(BuildMI(BB, dl,
7613                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7614                            Vtmp).addImm(LoopSize & 0xFFFF));
7615
7616     if ((LoopSize & 0xFFFF0000) != 0)
7617       AddDefaultPred(BuildMI(BB, dl,
7618                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7619                              varEnd)
7620                          .addReg(Vtmp)
7621                          .addImm(LoopSize >> 16));
7622   } else {
7623     MachineConstantPool *ConstantPool = MF->getConstantPool();
7624     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7625     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7626
7627     // MachineConstantPool wants an explicit alignment.
7628     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7629     if (Align == 0)
7630       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7631     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7632
7633     if (IsThumb1)
7634       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7635           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7636     else
7637       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7638           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7639   }
7640   BB->addSuccessor(loopMBB);
7641
7642   // Generate the loop body:
7643   //   varPhi = PHI(varLoop, varEnd)
7644   //   srcPhi = PHI(srcLoop, src)
7645   //   destPhi = PHI(destLoop, dst)
7646   MachineBasicBlock *entryBB = BB;
7647   BB = loopMBB;
7648   unsigned varLoop = MRI.createVirtualRegister(TRC);
7649   unsigned varPhi = MRI.createVirtualRegister(TRC);
7650   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7651   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7652   unsigned destLoop = MRI.createVirtualRegister(TRC);
7653   unsigned destPhi = MRI.createVirtualRegister(TRC);
7654
7655   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7656     .addReg(varLoop).addMBB(loopMBB)
7657     .addReg(varEnd).addMBB(entryBB);
7658   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7659     .addReg(srcLoop).addMBB(loopMBB)
7660     .addReg(src).addMBB(entryBB);
7661   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7662     .addReg(destLoop).addMBB(loopMBB)
7663     .addReg(dest).addMBB(entryBB);
7664
7665   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7666   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7667   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7668   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7669              IsThumb1, IsThumb2);
7670   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7671              IsThumb1, IsThumb2);
7672
7673   // Decrement loop variable by UnitSize.
7674   if (IsThumb1) {
7675     MachineInstrBuilder MIB =
7676         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7677     MIB = AddDefaultT1CC(MIB);
7678     MIB.addReg(varPhi).addImm(UnitSize);
7679     AddDefaultPred(MIB);
7680   } else {
7681     MachineInstrBuilder MIB =
7682         BuildMI(*BB, BB->end(), dl,
7683                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7684     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7685     MIB->getOperand(5).setReg(ARM::CPSR);
7686     MIB->getOperand(5).setIsDef(true);
7687   }
7688   BuildMI(*BB, BB->end(), dl,
7689           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7690       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7691
7692   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7693   BB->addSuccessor(loopMBB);
7694   BB->addSuccessor(exitMBB);
7695
7696   // Add epilogue to handle BytesLeft.
7697   BB = exitMBB;
7698   MachineInstr *StartOfExit = exitMBB->begin();
7699
7700   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7701   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7702   unsigned srcIn = srcLoop;
7703   unsigned destIn = destLoop;
7704   for (unsigned i = 0; i < BytesLeft; i++) {
7705     unsigned srcOut = MRI.createVirtualRegister(TRC);
7706     unsigned destOut = MRI.createVirtualRegister(TRC);
7707     unsigned scratch = MRI.createVirtualRegister(TRC);
7708     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7709                IsThumb1, IsThumb2);
7710     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7711                IsThumb1, IsThumb2);
7712     srcIn = srcOut;
7713     destIn = destOut;
7714   }
7715
7716   MI->eraseFromParent();   // The instruction is gone now.
7717   return BB;
7718 }
7719
7720 MachineBasicBlock *
7721 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7722                                        MachineBasicBlock *MBB) const {
7723   const TargetMachine &TM = getTargetMachine();
7724   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7725   DebugLoc DL = MI->getDebugLoc();
7726
7727   assert(Subtarget->isTargetWindows() &&
7728          "__chkstk is only supported on Windows");
7729   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7730
7731   // __chkstk takes the number of words to allocate on the stack in R4, and
7732   // returns the stack adjustment in number of bytes in R4.  This will not
7733   // clober any other registers (other than the obvious lr).
7734   //
7735   // Although, technically, IP should be considered a register which may be
7736   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7737   // thumb-2 environment, so there is no interworking required.  As a result, we
7738   // do not expect a veneer to be emitted by the linker, clobbering IP.
7739   //
7740   // Each module receives its own copy of __chkstk, so no import thunk is
7741   // required, again, ensuring that IP is not clobbered.
7742   //
7743   // Finally, although some linkers may theoretically provide a trampoline for
7744   // out of range calls (which is quite common due to a 32M range limitation of
7745   // branches for Thumb), we can generate the long-call version via
7746   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7747   // IP.
7748
7749   switch (TM.getCodeModel()) {
7750   case CodeModel::Small:
7751   case CodeModel::Medium:
7752   case CodeModel::Default:
7753   case CodeModel::Kernel:
7754     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7755       .addImm((unsigned)ARMCC::AL).addReg(0)
7756       .addExternalSymbol("__chkstk")
7757       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7758       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7759       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7760     break;
7761   case CodeModel::Large:
7762   case CodeModel::JITDefault: {
7763     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7764     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7765
7766     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7767       .addExternalSymbol("__chkstk");
7768     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7769       .addImm((unsigned)ARMCC::AL).addReg(0)
7770       .addReg(Reg, RegState::Kill)
7771       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7772       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7773       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7774     break;
7775   }
7776   }
7777
7778   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7779                                       ARM::SP)
7780                               .addReg(ARM::SP).addReg(ARM::R4)));
7781
7782   MI->eraseFromParent();
7783   return MBB;
7784 }
7785
7786 MachineBasicBlock *
7787 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
7788                                        MachineBasicBlock *MBB) const {
7789   DebugLoc DL = MI->getDebugLoc();
7790   MachineFunction *MF = MBB->getParent();
7791   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7792
7793   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
7794   MF->push_back(ContBB);
7795   ContBB->splice(ContBB->begin(), MBB,
7796                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7797   MBB->addSuccessor(ContBB);
7798
7799   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7800   MF->push_back(TrapBB);
7801   BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
7802   MBB->addSuccessor(TrapBB);
7803
7804   BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
7805       .addReg(MI->getOperand(0).getReg())
7806       .addMBB(TrapBB);
7807
7808   MI->eraseFromParent();
7809   return ContBB;
7810 }
7811
7812 MachineBasicBlock *
7813 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7814                                                MachineBasicBlock *BB) const {
7815   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7816   DebugLoc dl = MI->getDebugLoc();
7817   bool isThumb2 = Subtarget->isThumb2();
7818   switch (MI->getOpcode()) {
7819   default: {
7820     MI->dump();
7821     llvm_unreachable("Unexpected instr type to insert");
7822   }
7823   // The Thumb2 pre-indexed stores have the same MI operands, they just
7824   // define them differently in the .td files from the isel patterns, so
7825   // they need pseudos.
7826   case ARM::t2STR_preidx:
7827     MI->setDesc(TII->get(ARM::t2STR_PRE));
7828     return BB;
7829   case ARM::t2STRB_preidx:
7830     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7831     return BB;
7832   case ARM::t2STRH_preidx:
7833     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7834     return BB;
7835
7836   case ARM::STRi_preidx:
7837   case ARM::STRBi_preidx: {
7838     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7839       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7840     // Decode the offset.
7841     unsigned Offset = MI->getOperand(4).getImm();
7842     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7843     Offset = ARM_AM::getAM2Offset(Offset);
7844     if (isSub)
7845       Offset = -Offset;
7846
7847     MachineMemOperand *MMO = *MI->memoperands_begin();
7848     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7849       .addOperand(MI->getOperand(0))  // Rn_wb
7850       .addOperand(MI->getOperand(1))  // Rt
7851       .addOperand(MI->getOperand(2))  // Rn
7852       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7853       .addOperand(MI->getOperand(5))  // pred
7854       .addOperand(MI->getOperand(6))
7855       .addMemOperand(MMO);
7856     MI->eraseFromParent();
7857     return BB;
7858   }
7859   case ARM::STRr_preidx:
7860   case ARM::STRBr_preidx:
7861   case ARM::STRH_preidx: {
7862     unsigned NewOpc;
7863     switch (MI->getOpcode()) {
7864     default: llvm_unreachable("unexpected opcode!");
7865     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7866     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7867     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7868     }
7869     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7870     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7871       MIB.addOperand(MI->getOperand(i));
7872     MI->eraseFromParent();
7873     return BB;
7874   }
7875
7876   case ARM::tMOVCCr_pseudo: {
7877     // To "insert" a SELECT_CC instruction, we actually have to insert the
7878     // diamond control-flow pattern.  The incoming instruction knows the
7879     // destination vreg to set, the condition code register to branch on, the
7880     // true/false values to select between, and a branch opcode to use.
7881     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7882     MachineFunction::iterator It = ++BB->getIterator();
7883
7884     //  thisMBB:
7885     //  ...
7886     //   TrueVal = ...
7887     //   cmpTY ccX, r1, r2
7888     //   bCC copy1MBB
7889     //   fallthrough --> copy0MBB
7890     MachineBasicBlock *thisMBB  = BB;
7891     MachineFunction *F = BB->getParent();
7892     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7893     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7894     F->insert(It, copy0MBB);
7895     F->insert(It, sinkMBB);
7896
7897     // Transfer the remainder of BB and its successor edges to sinkMBB.
7898     sinkMBB->splice(sinkMBB->begin(), BB,
7899                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7900     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7901
7902     BB->addSuccessor(copy0MBB);
7903     BB->addSuccessor(sinkMBB);
7904
7905     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7906       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7907
7908     //  copy0MBB:
7909     //   %FalseValue = ...
7910     //   # fallthrough to sinkMBB
7911     BB = copy0MBB;
7912
7913     // Update machine-CFG edges
7914     BB->addSuccessor(sinkMBB);
7915
7916     //  sinkMBB:
7917     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7918     //  ...
7919     BB = sinkMBB;
7920     BuildMI(*BB, BB->begin(), dl,
7921             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7922       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7923       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7924
7925     MI->eraseFromParent();   // The pseudo instruction is gone now.
7926     return BB;
7927   }
7928
7929   case ARM::BCCi64:
7930   case ARM::BCCZi64: {
7931     // If there is an unconditional branch to the other successor, remove it.
7932     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7933
7934     // Compare both parts that make up the double comparison separately for
7935     // equality.
7936     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7937
7938     unsigned LHS1 = MI->getOperand(1).getReg();
7939     unsigned LHS2 = MI->getOperand(2).getReg();
7940     if (RHSisZero) {
7941       AddDefaultPred(BuildMI(BB, dl,
7942                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7943                      .addReg(LHS1).addImm(0));
7944       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7945         .addReg(LHS2).addImm(0)
7946         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7947     } else {
7948       unsigned RHS1 = MI->getOperand(3).getReg();
7949       unsigned RHS2 = MI->getOperand(4).getReg();
7950       AddDefaultPred(BuildMI(BB, dl,
7951                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7952                      .addReg(LHS1).addReg(RHS1));
7953       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7954         .addReg(LHS2).addReg(RHS2)
7955         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7956     }
7957
7958     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7959     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7960     if (MI->getOperand(0).getImm() == ARMCC::NE)
7961       std::swap(destMBB, exitMBB);
7962
7963     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7964       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7965     if (isThumb2)
7966       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7967     else
7968       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7969
7970     MI->eraseFromParent();   // The pseudo instruction is gone now.
7971     return BB;
7972   }
7973
7974   case ARM::Int_eh_sjlj_setjmp:
7975   case ARM::Int_eh_sjlj_setjmp_nofp:
7976   case ARM::tInt_eh_sjlj_setjmp:
7977   case ARM::t2Int_eh_sjlj_setjmp:
7978   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7979     return BB;
7980
7981   case ARM::Int_eh_sjlj_setup_dispatch:
7982     EmitSjLjDispatchBlock(MI, BB);
7983     return BB;
7984
7985   case ARM::ABS:
7986   case ARM::t2ABS: {
7987     // To insert an ABS instruction, we have to insert the
7988     // diamond control-flow pattern.  The incoming instruction knows the
7989     // source vreg to test against 0, the destination vreg to set,
7990     // the condition code register to branch on, the
7991     // true/false values to select between, and a branch opcode to use.
7992     // It transforms
7993     //     V1 = ABS V0
7994     // into
7995     //     V2 = MOVS V0
7996     //     BCC                      (branch to SinkBB if V0 >= 0)
7997     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7998     //     SinkBB: V1 = PHI(V2, V3)
7999     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8000     MachineFunction::iterator BBI = ++BB->getIterator();
8001     MachineFunction *Fn = BB->getParent();
8002     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8003     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
8004     Fn->insert(BBI, RSBBB);
8005     Fn->insert(BBI, SinkBB);
8006
8007     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8008     unsigned int ABSDstReg = MI->getOperand(0).getReg();
8009     bool ABSSrcKIll = MI->getOperand(1).isKill();
8010     bool isThumb2 = Subtarget->isThumb2();
8011     MachineRegisterInfo &MRI = Fn->getRegInfo();
8012     // In Thumb mode S must not be specified if source register is the SP or
8013     // PC and if destination register is the SP, so restrict register class
8014     unsigned NewRsbDstReg =
8015       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8016
8017     // Transfer the remainder of BB and its successor edges to sinkMBB.
8018     SinkBB->splice(SinkBB->begin(), BB,
8019                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
8020     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8021
8022     BB->addSuccessor(RSBBB);
8023     BB->addSuccessor(SinkBB);
8024
8025     // fall through to SinkMBB
8026     RSBBB->addSuccessor(SinkBB);
8027
8028     // insert a cmp at the end of BB
8029     AddDefaultPred(BuildMI(BB, dl,
8030                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8031                    .addReg(ABSSrcReg).addImm(0));
8032
8033     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8034     BuildMI(BB, dl,
8035       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8036       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8037
8038     // insert rsbri in RSBBB
8039     // Note: BCC and rsbri will be converted into predicated rsbmi
8040     // by if-conversion pass
8041     BuildMI(*RSBBB, RSBBB->begin(), dl,
8042       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8043       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8044       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8045
8046     // insert PHI in SinkBB,
8047     // reuse ABSDstReg to not change uses of ABS instruction
8048     BuildMI(*SinkBB, SinkBB->begin(), dl,
8049       TII->get(ARM::PHI), ABSDstReg)
8050       .addReg(NewRsbDstReg).addMBB(RSBBB)
8051       .addReg(ABSSrcReg).addMBB(BB);
8052
8053     // remove ABS instruction
8054     MI->eraseFromParent();
8055
8056     // return last added BB
8057     return SinkBB;
8058   }
8059   case ARM::COPY_STRUCT_BYVAL_I32:
8060     ++NumLoopByVals;
8061     return EmitStructByval(MI, BB);
8062   case ARM::WIN__CHKSTK:
8063     return EmitLowered__chkstk(MI, BB);
8064   case ARM::WIN__DBZCHK:
8065     return EmitLowered__dbzchk(MI, BB);
8066   }
8067 }
8068
8069 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8070 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8071 /// instead of as a custom inserter because we need the use list from the SDNode.
8072 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8073                                    MachineInstr *MI, const SDNode *Node) {
8074   bool isThumb1 = Subtarget->isThumb1Only();
8075
8076   DebugLoc DL = MI->getDebugLoc();
8077   MachineFunction *MF = MI->getParent()->getParent();
8078   MachineRegisterInfo &MRI = MF->getRegInfo();
8079   MachineInstrBuilder MIB(*MF, MI);
8080
8081   // If the new dst/src is unused mark it as dead.
8082   if (!Node->hasAnyUseOfValue(0)) {
8083     MI->getOperand(0).setIsDead(true);
8084   }
8085   if (!Node->hasAnyUseOfValue(1)) {
8086     MI->getOperand(1).setIsDead(true);
8087   }
8088
8089   // The MEMCPY both defines and kills the scratch registers.
8090   for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) {
8091     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8092                                                          : &ARM::GPRRegClass);
8093     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8094   }
8095 }
8096
8097 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8098                                                       SDNode *Node) const {
8099   if (MI->getOpcode() == ARM::MEMCPY) {
8100     attachMEMCPYScratchRegs(Subtarget, MI, Node);
8101     return;
8102   }
8103
8104   const MCInstrDesc *MCID = &MI->getDesc();
8105   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8106   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8107   // operand is still set to noreg. If needed, set the optional operand's
8108   // register to CPSR, and remove the redundant implicit def.
8109   //
8110   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8111
8112   // Rename pseudo opcodes.
8113   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8114   if (NewOpc) {
8115     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8116     MCID = &TII->get(NewOpc);
8117
8118     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8119            "converted opcode should be the same except for cc_out");
8120
8121     MI->setDesc(*MCID);
8122
8123     // Add the optional cc_out operand
8124     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8125   }
8126   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8127
8128   // Any ARM instruction that sets the 's' bit should specify an optional
8129   // "cc_out" operand in the last operand position.
8130   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8131     assert(!NewOpc && "Optional cc_out operand required");
8132     return;
8133   }
8134   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8135   // since we already have an optional CPSR def.
8136   bool definesCPSR = false;
8137   bool deadCPSR = false;
8138   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8139        i != e; ++i) {
8140     const MachineOperand &MO = MI->getOperand(i);
8141     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8142       definesCPSR = true;
8143       if (MO.isDead())
8144         deadCPSR = true;
8145       MI->RemoveOperand(i);
8146       break;
8147     }
8148   }
8149   if (!definesCPSR) {
8150     assert(!NewOpc && "Optional cc_out operand required");
8151     return;
8152   }
8153   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8154   if (deadCPSR) {
8155     assert(!MI->getOperand(ccOutIdx).getReg() &&
8156            "expect uninitialized optional cc_out operand");
8157     return;
8158   }
8159
8160   // If this instruction was defined with an optional CPSR def and its dag node
8161   // had a live implicit CPSR def, then activate the optional CPSR def.
8162   MachineOperand &MO = MI->getOperand(ccOutIdx);
8163   MO.setReg(ARM::CPSR);
8164   MO.setIsDef(true);
8165 }
8166
8167 //===----------------------------------------------------------------------===//
8168 //                           ARM Optimization Hooks
8169 //===----------------------------------------------------------------------===//
8170
8171 // Helper function that checks if N is a null or all ones constant.
8172 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8173   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8174   if (!C)
8175     return false;
8176   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8177 }
8178
8179 // Return true if N is conditionally 0 or all ones.
8180 // Detects these expressions where cc is an i1 value:
8181 //
8182 //   (select cc 0, y)   [AllOnes=0]
8183 //   (select cc y, 0)   [AllOnes=0]
8184 //   (zext cc)          [AllOnes=0]
8185 //   (sext cc)          [AllOnes=0/1]
8186 //   (select cc -1, y)  [AllOnes=1]
8187 //   (select cc y, -1)  [AllOnes=1]
8188 //
8189 // Invert is set when N is the null/all ones constant when CC is false.
8190 // OtherOp is set to the alternative value of N.
8191 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8192                                        SDValue &CC, bool &Invert,
8193                                        SDValue &OtherOp,
8194                                        SelectionDAG &DAG) {
8195   switch (N->getOpcode()) {
8196   default: return false;
8197   case ISD::SELECT: {
8198     CC = N->getOperand(0);
8199     SDValue N1 = N->getOperand(1);
8200     SDValue N2 = N->getOperand(2);
8201     if (isZeroOrAllOnes(N1, AllOnes)) {
8202       Invert = false;
8203       OtherOp = N2;
8204       return true;
8205     }
8206     if (isZeroOrAllOnes(N2, AllOnes)) {
8207       Invert = true;
8208       OtherOp = N1;
8209       return true;
8210     }
8211     return false;
8212   }
8213   case ISD::ZERO_EXTEND:
8214     // (zext cc) can never be the all ones value.
8215     if (AllOnes)
8216       return false;
8217     // Fall through.
8218   case ISD::SIGN_EXTEND: {
8219     SDLoc dl(N);
8220     EVT VT = N->getValueType(0);
8221     CC = N->getOperand(0);
8222     if (CC.getValueType() != MVT::i1)
8223       return false;
8224     Invert = !AllOnes;
8225     if (AllOnes)
8226       // When looking for an AllOnes constant, N is an sext, and the 'other'
8227       // value is 0.
8228       OtherOp = DAG.getConstant(0, dl, VT);
8229     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8230       // When looking for a 0 constant, N can be zext or sext.
8231       OtherOp = DAG.getConstant(1, dl, VT);
8232     else
8233       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8234                                 VT);
8235     return true;
8236   }
8237   }
8238 }
8239
8240 // Combine a constant select operand into its use:
8241 //
8242 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8243 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8244 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8245 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8246 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8247 //
8248 // The transform is rejected if the select doesn't have a constant operand that
8249 // is null, or all ones when AllOnes is set.
8250 //
8251 // Also recognize sext/zext from i1:
8252 //
8253 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8254 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8255 //
8256 // These transformations eventually create predicated instructions.
8257 //
8258 // @param N       The node to transform.
8259 // @param Slct    The N operand that is a select.
8260 // @param OtherOp The other N operand (x above).
8261 // @param DCI     Context.
8262 // @param AllOnes Require the select constant to be all ones instead of null.
8263 // @returns The new node, or SDValue() on failure.
8264 static
8265 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8266                             TargetLowering::DAGCombinerInfo &DCI,
8267                             bool AllOnes = false) {
8268   SelectionDAG &DAG = DCI.DAG;
8269   EVT VT = N->getValueType(0);
8270   SDValue NonConstantVal;
8271   SDValue CCOp;
8272   bool SwapSelectOps;
8273   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8274                                   NonConstantVal, DAG))
8275     return SDValue();
8276
8277   // Slct is now know to be the desired identity constant when CC is true.
8278   SDValue TrueVal = OtherOp;
8279   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8280                                  OtherOp, NonConstantVal);
8281   // Unless SwapSelectOps says CC should be false.
8282   if (SwapSelectOps)
8283     std::swap(TrueVal, FalseVal);
8284
8285   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8286                      CCOp, TrueVal, FalseVal);
8287 }
8288
8289 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8290 static
8291 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8292                                        TargetLowering::DAGCombinerInfo &DCI) {
8293   SDValue N0 = N->getOperand(0);
8294   SDValue N1 = N->getOperand(1);
8295   if (N0.getNode()->hasOneUse()) {
8296     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8297     if (Result.getNode())
8298       return Result;
8299   }
8300   if (N1.getNode()->hasOneUse()) {
8301     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8302     if (Result.getNode())
8303       return Result;
8304   }
8305   return SDValue();
8306 }
8307
8308 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8309 // (only after legalization).
8310 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8311                                  TargetLowering::DAGCombinerInfo &DCI,
8312                                  const ARMSubtarget *Subtarget) {
8313
8314   // Only perform optimization if after legalize, and if NEON is available. We
8315   // also expected both operands to be BUILD_VECTORs.
8316   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8317       || N0.getOpcode() != ISD::BUILD_VECTOR
8318       || N1.getOpcode() != ISD::BUILD_VECTOR)
8319     return SDValue();
8320
8321   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8322   EVT VT = N->getValueType(0);
8323   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8324     return SDValue();
8325
8326   // Check that the vector operands are of the right form.
8327   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8328   // operands, where N is the size of the formed vector.
8329   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8330   // index such that we have a pair wise add pattern.
8331
8332   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8333   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8334     return SDValue();
8335   SDValue Vec = N0->getOperand(0)->getOperand(0);
8336   SDNode *V = Vec.getNode();
8337   unsigned nextIndex = 0;
8338
8339   // For each operands to the ADD which are BUILD_VECTORs,
8340   // check to see if each of their operands are an EXTRACT_VECTOR with
8341   // the same vector and appropriate index.
8342   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8343     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8344         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8345
8346       SDValue ExtVec0 = N0->getOperand(i);
8347       SDValue ExtVec1 = N1->getOperand(i);
8348
8349       // First operand is the vector, verify its the same.
8350       if (V != ExtVec0->getOperand(0).getNode() ||
8351           V != ExtVec1->getOperand(0).getNode())
8352         return SDValue();
8353
8354       // Second is the constant, verify its correct.
8355       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8356       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8357
8358       // For the constant, we want to see all the even or all the odd.
8359       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8360           || C1->getZExtValue() != nextIndex+1)
8361         return SDValue();
8362
8363       // Increment index.
8364       nextIndex+=2;
8365     } else
8366       return SDValue();
8367   }
8368
8369   // Create VPADDL node.
8370   SelectionDAG &DAG = DCI.DAG;
8371   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8372
8373   SDLoc dl(N);
8374
8375   // Build operand list.
8376   SmallVector<SDValue, 8> Ops;
8377   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8378                                 TLI.getPointerTy(DAG.getDataLayout())));
8379
8380   // Input is the vector.
8381   Ops.push_back(Vec);
8382
8383   // Get widened type and narrowed type.
8384   MVT widenType;
8385   unsigned numElem = VT.getVectorNumElements();
8386   
8387   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8388   switch (inputLaneType.getSimpleVT().SimpleTy) {
8389     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8390     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8391     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8392     default:
8393       llvm_unreachable("Invalid vector element type for padd optimization.");
8394   }
8395
8396   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8397   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8398   return DAG.getNode(ExtOp, dl, VT, tmp);
8399 }
8400
8401 static SDValue findMUL_LOHI(SDValue V) {
8402   if (V->getOpcode() == ISD::UMUL_LOHI ||
8403       V->getOpcode() == ISD::SMUL_LOHI)
8404     return V;
8405   return SDValue();
8406 }
8407
8408 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8409                                      TargetLowering::DAGCombinerInfo &DCI,
8410                                      const ARMSubtarget *Subtarget) {
8411
8412   if (Subtarget->isThumb1Only()) return SDValue();
8413
8414   // Only perform the checks after legalize when the pattern is available.
8415   if (DCI.isBeforeLegalize()) return SDValue();
8416
8417   // Look for multiply add opportunities.
8418   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8419   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8420   // a glue link from the first add to the second add.
8421   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8422   // a S/UMLAL instruction.
8423   //                  UMUL_LOHI
8424   //                 / :lo    \ :hi
8425   //                /          \          [no multiline comment]
8426   //    loAdd ->  ADDE         |
8427   //                 \ :glue  /
8428   //                  \      /
8429   //                    ADDC   <- hiAdd
8430   //
8431   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8432   SDValue AddcOp0 = AddcNode->getOperand(0);
8433   SDValue AddcOp1 = AddcNode->getOperand(1);
8434
8435   // Check if the two operands are from the same mul_lohi node.
8436   if (AddcOp0.getNode() == AddcOp1.getNode())
8437     return SDValue();
8438
8439   assert(AddcNode->getNumValues() == 2 &&
8440          AddcNode->getValueType(0) == MVT::i32 &&
8441          "Expect ADDC with two result values. First: i32");
8442
8443   // Check that we have a glued ADDC node.
8444   if (AddcNode->getValueType(1) != MVT::Glue)
8445     return SDValue();
8446
8447   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8448   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8449       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8450       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8451       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8452     return SDValue();
8453
8454   // Look for the glued ADDE.
8455   SDNode* AddeNode = AddcNode->getGluedUser();
8456   if (!AddeNode)
8457     return SDValue();
8458
8459   // Make sure it is really an ADDE.
8460   if (AddeNode->getOpcode() != ISD::ADDE)
8461     return SDValue();
8462
8463   assert(AddeNode->getNumOperands() == 3 &&
8464          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8465          "ADDE node has the wrong inputs");
8466
8467   // Check for the triangle shape.
8468   SDValue AddeOp0 = AddeNode->getOperand(0);
8469   SDValue AddeOp1 = AddeNode->getOperand(1);
8470
8471   // Make sure that the ADDE operands are not coming from the same node.
8472   if (AddeOp0.getNode() == AddeOp1.getNode())
8473     return SDValue();
8474
8475   // Find the MUL_LOHI node walking up ADDE's operands.
8476   bool IsLeftOperandMUL = false;
8477   SDValue MULOp = findMUL_LOHI(AddeOp0);
8478   if (MULOp == SDValue())
8479    MULOp = findMUL_LOHI(AddeOp1);
8480   else
8481     IsLeftOperandMUL = true;
8482   if (MULOp == SDValue())
8483     return SDValue();
8484
8485   // Figure out the right opcode.
8486   unsigned Opc = MULOp->getOpcode();
8487   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8488
8489   // Figure out the high and low input values to the MLAL node.
8490   SDValue* HiAdd = nullptr;
8491   SDValue* LoMul = nullptr;
8492   SDValue* LowAdd = nullptr;
8493
8494   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8495   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8496     return SDValue();
8497
8498   if (IsLeftOperandMUL)
8499     HiAdd = &AddeOp1;
8500   else
8501     HiAdd = &AddeOp0;
8502
8503
8504   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8505   // whose low result is fed to the ADDC we are checking.
8506
8507   if (AddcOp0 == MULOp.getValue(0)) {
8508     LoMul = &AddcOp0;
8509     LowAdd = &AddcOp1;
8510   }
8511   if (AddcOp1 == MULOp.getValue(0)) {
8512     LoMul = &AddcOp1;
8513     LowAdd = &AddcOp0;
8514   }
8515
8516   if (!LoMul)
8517     return SDValue();
8518
8519   // Create the merged node.
8520   SelectionDAG &DAG = DCI.DAG;
8521
8522   // Build operand list.
8523   SmallVector<SDValue, 8> Ops;
8524   Ops.push_back(LoMul->getOperand(0));
8525   Ops.push_back(LoMul->getOperand(1));
8526   Ops.push_back(*LowAdd);
8527   Ops.push_back(*HiAdd);
8528
8529   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8530                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8531
8532   // Replace the ADDs' nodes uses by the MLA node's values.
8533   SDValue HiMLALResult(MLALNode.getNode(), 1);
8534   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8535
8536   SDValue LoMLALResult(MLALNode.getNode(), 0);
8537   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8538
8539   // Return original node to notify the driver to stop replacing.
8540   SDValue resNode(AddcNode, 0);
8541   return resNode;
8542 }
8543
8544 /// PerformADDCCombine - Target-specific dag combine transform from
8545 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8546 static SDValue PerformADDCCombine(SDNode *N,
8547                                  TargetLowering::DAGCombinerInfo &DCI,
8548                                  const ARMSubtarget *Subtarget) {
8549
8550   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8551
8552 }
8553
8554 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8555 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8556 /// called with the default operands, and if that fails, with commuted
8557 /// operands.
8558 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8559                                           TargetLowering::DAGCombinerInfo &DCI,
8560                                           const ARMSubtarget *Subtarget){
8561
8562   // Attempt to create vpaddl for this add.
8563   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8564   if (Result.getNode())
8565     return Result;
8566
8567   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8568   if (N0.getNode()->hasOneUse()) {
8569     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8570     if (Result.getNode()) return Result;
8571   }
8572   return SDValue();
8573 }
8574
8575 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8576 ///
8577 static SDValue PerformADDCombine(SDNode *N,
8578                                  TargetLowering::DAGCombinerInfo &DCI,
8579                                  const ARMSubtarget *Subtarget) {
8580   SDValue N0 = N->getOperand(0);
8581   SDValue N1 = N->getOperand(1);
8582
8583   // First try with the default operand order.
8584   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8585   if (Result.getNode())
8586     return Result;
8587
8588   // If that didn't work, try again with the operands commuted.
8589   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8590 }
8591
8592 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8593 ///
8594 static SDValue PerformSUBCombine(SDNode *N,
8595                                  TargetLowering::DAGCombinerInfo &DCI) {
8596   SDValue N0 = N->getOperand(0);
8597   SDValue N1 = N->getOperand(1);
8598
8599   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8600   if (N1.getNode()->hasOneUse()) {
8601     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8602     if (Result.getNode()) return Result;
8603   }
8604
8605   return SDValue();
8606 }
8607
8608 /// PerformVMULCombine
8609 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8610 /// special multiplier accumulator forwarding.
8611 ///   vmul d3, d0, d2
8612 ///   vmla d3, d1, d2
8613 /// is faster than
8614 ///   vadd d3, d0, d1
8615 ///   vmul d3, d3, d2
8616 //  However, for (A + B) * (A + B),
8617 //    vadd d2, d0, d1
8618 //    vmul d3, d0, d2
8619 //    vmla d3, d1, d2
8620 //  is slower than
8621 //    vadd d2, d0, d1
8622 //    vmul d3, d2, d2
8623 static SDValue PerformVMULCombine(SDNode *N,
8624                                   TargetLowering::DAGCombinerInfo &DCI,
8625                                   const ARMSubtarget *Subtarget) {
8626   if (!Subtarget->hasVMLxForwarding())
8627     return SDValue();
8628
8629   SelectionDAG &DAG = DCI.DAG;
8630   SDValue N0 = N->getOperand(0);
8631   SDValue N1 = N->getOperand(1);
8632   unsigned Opcode = N0.getOpcode();
8633   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8634       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8635     Opcode = N1.getOpcode();
8636     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8637         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8638       return SDValue();
8639     std::swap(N0, N1);
8640   }
8641
8642   if (N0 == N1)
8643     return SDValue();
8644
8645   EVT VT = N->getValueType(0);
8646   SDLoc DL(N);
8647   SDValue N00 = N0->getOperand(0);
8648   SDValue N01 = N0->getOperand(1);
8649   return DAG.getNode(Opcode, DL, VT,
8650                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8651                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8652 }
8653
8654 static SDValue PerformMULCombine(SDNode *N,
8655                                  TargetLowering::DAGCombinerInfo &DCI,
8656                                  const ARMSubtarget *Subtarget) {
8657   SelectionDAG &DAG = DCI.DAG;
8658
8659   if (Subtarget->isThumb1Only())
8660     return SDValue();
8661
8662   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8663     return SDValue();
8664
8665   EVT VT = N->getValueType(0);
8666   if (VT.is64BitVector() || VT.is128BitVector())
8667     return PerformVMULCombine(N, DCI, Subtarget);
8668   if (VT != MVT::i32)
8669     return SDValue();
8670
8671   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8672   if (!C)
8673     return SDValue();
8674
8675   int64_t MulAmt = C->getSExtValue();
8676   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8677
8678   ShiftAmt = ShiftAmt & (32 - 1);
8679   SDValue V = N->getOperand(0);
8680   SDLoc DL(N);
8681
8682   SDValue Res;
8683   MulAmt >>= ShiftAmt;
8684
8685   if (MulAmt >= 0) {
8686     if (isPowerOf2_32(MulAmt - 1)) {
8687       // (mul x, 2^N + 1) => (add (shl x, N), x)
8688       Res = DAG.getNode(ISD::ADD, DL, VT,
8689                         V,
8690                         DAG.getNode(ISD::SHL, DL, VT,
8691                                     V,
8692                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8693                                                     MVT::i32)));
8694     } else if (isPowerOf2_32(MulAmt + 1)) {
8695       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8696       Res = DAG.getNode(ISD::SUB, DL, VT,
8697                         DAG.getNode(ISD::SHL, DL, VT,
8698                                     V,
8699                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8700                                                     MVT::i32)),
8701                         V);
8702     } else
8703       return SDValue();
8704   } else {
8705     uint64_t MulAmtAbs = -MulAmt;
8706     if (isPowerOf2_32(MulAmtAbs + 1)) {
8707       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8708       Res = DAG.getNode(ISD::SUB, DL, VT,
8709                         V,
8710                         DAG.getNode(ISD::SHL, DL, VT,
8711                                     V,
8712                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8713                                                     MVT::i32)));
8714     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8715       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8716       Res = DAG.getNode(ISD::ADD, DL, VT,
8717                         V,
8718                         DAG.getNode(ISD::SHL, DL, VT,
8719                                     V,
8720                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8721                                                     MVT::i32)));
8722       Res = DAG.getNode(ISD::SUB, DL, VT,
8723                         DAG.getConstant(0, DL, MVT::i32), Res);
8724
8725     } else
8726       return SDValue();
8727   }
8728
8729   if (ShiftAmt != 0)
8730     Res = DAG.getNode(ISD::SHL, DL, VT,
8731                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8732
8733   // Do not add new nodes to DAG combiner worklist.
8734   DCI.CombineTo(N, Res, false);
8735   return SDValue();
8736 }
8737
8738 static SDValue PerformANDCombine(SDNode *N,
8739                                  TargetLowering::DAGCombinerInfo &DCI,
8740                                  const ARMSubtarget *Subtarget) {
8741
8742   // Attempt to use immediate-form VBIC
8743   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8744   SDLoc dl(N);
8745   EVT VT = N->getValueType(0);
8746   SelectionDAG &DAG = DCI.DAG;
8747
8748   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8749     return SDValue();
8750
8751   APInt SplatBits, SplatUndef;
8752   unsigned SplatBitSize;
8753   bool HasAnyUndefs;
8754   if (BVN &&
8755       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8756     if (SplatBitSize <= 64) {
8757       EVT VbicVT;
8758       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8759                                       SplatUndef.getZExtValue(), SplatBitSize,
8760                                       DAG, dl, VbicVT, VT.is128BitVector(),
8761                                       OtherModImm);
8762       if (Val.getNode()) {
8763         SDValue Input =
8764           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8765         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8766         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8767       }
8768     }
8769   }
8770
8771   if (!Subtarget->isThumb1Only()) {
8772     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8773     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8774     if (Result.getNode())
8775       return Result;
8776   }
8777
8778   return SDValue();
8779 }
8780
8781 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8782 static SDValue PerformORCombine(SDNode *N,
8783                                 TargetLowering::DAGCombinerInfo &DCI,
8784                                 const ARMSubtarget *Subtarget) {
8785   // Attempt to use immediate-form VORR
8786   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8787   SDLoc dl(N);
8788   EVT VT = N->getValueType(0);
8789   SelectionDAG &DAG = DCI.DAG;
8790
8791   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8792     return SDValue();
8793
8794   APInt SplatBits, SplatUndef;
8795   unsigned SplatBitSize;
8796   bool HasAnyUndefs;
8797   if (BVN && Subtarget->hasNEON() &&
8798       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8799     if (SplatBitSize <= 64) {
8800       EVT VorrVT;
8801       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8802                                       SplatUndef.getZExtValue(), SplatBitSize,
8803                                       DAG, dl, VorrVT, VT.is128BitVector(),
8804                                       OtherModImm);
8805       if (Val.getNode()) {
8806         SDValue Input =
8807           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8808         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8809         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8810       }
8811     }
8812   }
8813
8814   if (!Subtarget->isThumb1Only()) {
8815     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8816     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8817     if (Result.getNode())
8818       return Result;
8819   }
8820
8821   // The code below optimizes (or (and X, Y), Z).
8822   // The AND operand needs to have a single user to make these optimizations
8823   // profitable.
8824   SDValue N0 = N->getOperand(0);
8825   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8826     return SDValue();
8827   SDValue N1 = N->getOperand(1);
8828
8829   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8830   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8831       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8832     APInt SplatUndef;
8833     unsigned SplatBitSize;
8834     bool HasAnyUndefs;
8835
8836     APInt SplatBits0, SplatBits1;
8837     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8838     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8839     // Ensure that the second operand of both ands are constants
8840     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8841                                       HasAnyUndefs) && !HasAnyUndefs) {
8842         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8843                                           HasAnyUndefs) && !HasAnyUndefs) {
8844             // Ensure that the bit width of the constants are the same and that
8845             // the splat arguments are logical inverses as per the pattern we
8846             // are trying to simplify.
8847             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8848                 SplatBits0 == ~SplatBits1) {
8849                 // Canonicalize the vector type to make instruction selection
8850                 // simpler.
8851                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8852                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8853                                              N0->getOperand(1),
8854                                              N0->getOperand(0),
8855                                              N1->getOperand(0));
8856                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8857             }
8858         }
8859     }
8860   }
8861
8862   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8863   // reasonable.
8864
8865   // BFI is only available on V6T2+
8866   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8867     return SDValue();
8868
8869   SDLoc DL(N);
8870   // 1) or (and A, mask), val => ARMbfi A, val, mask
8871   //      iff (val & mask) == val
8872   //
8873   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8874   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8875   //          && mask == ~mask2
8876   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8877   //          && ~mask == mask2
8878   //  (i.e., copy a bitfield value into another bitfield of the same width)
8879
8880   if (VT != MVT::i32)
8881     return SDValue();
8882
8883   SDValue N00 = N0.getOperand(0);
8884
8885   // The value and the mask need to be constants so we can verify this is
8886   // actually a bitfield set. If the mask is 0xffff, we can do better
8887   // via a movt instruction, so don't use BFI in that case.
8888   SDValue MaskOp = N0.getOperand(1);
8889   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8890   if (!MaskC)
8891     return SDValue();
8892   unsigned Mask = MaskC->getZExtValue();
8893   if (Mask == 0xffff)
8894     return SDValue();
8895   SDValue Res;
8896   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8897   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8898   if (N1C) {
8899     unsigned Val = N1C->getZExtValue();
8900     if ((Val & ~Mask) != Val)
8901       return SDValue();
8902
8903     if (ARM::isBitFieldInvertedMask(Mask)) {
8904       Val >>= countTrailingZeros(~Mask);
8905
8906       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8907                         DAG.getConstant(Val, DL, MVT::i32),
8908                         DAG.getConstant(Mask, DL, MVT::i32));
8909
8910       // Do not add new nodes to DAG combiner worklist.
8911       DCI.CombineTo(N, Res, false);
8912       return SDValue();
8913     }
8914   } else if (N1.getOpcode() == ISD::AND) {
8915     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8916     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8917     if (!N11C)
8918       return SDValue();
8919     unsigned Mask2 = N11C->getZExtValue();
8920
8921     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8922     // as is to match.
8923     if (ARM::isBitFieldInvertedMask(Mask) &&
8924         (Mask == ~Mask2)) {
8925       // The pack halfword instruction works better for masks that fit it,
8926       // so use that when it's available.
8927       if (Subtarget->hasT2ExtractPack() &&
8928           (Mask == 0xffff || Mask == 0xffff0000))
8929         return SDValue();
8930       // 2a
8931       unsigned amt = countTrailingZeros(Mask2);
8932       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8933                         DAG.getConstant(amt, DL, MVT::i32));
8934       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8935                         DAG.getConstant(Mask, DL, MVT::i32));
8936       // Do not add new nodes to DAG combiner worklist.
8937       DCI.CombineTo(N, Res, false);
8938       return SDValue();
8939     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8940                (~Mask == Mask2)) {
8941       // The pack halfword instruction works better for masks that fit it,
8942       // so use that when it's available.
8943       if (Subtarget->hasT2ExtractPack() &&
8944           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8945         return SDValue();
8946       // 2b
8947       unsigned lsb = countTrailingZeros(Mask);
8948       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8949                         DAG.getConstant(lsb, DL, MVT::i32));
8950       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8951                         DAG.getConstant(Mask2, DL, MVT::i32));
8952       // Do not add new nodes to DAG combiner worklist.
8953       DCI.CombineTo(N, Res, false);
8954       return SDValue();
8955     }
8956   }
8957
8958   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8959       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8960       ARM::isBitFieldInvertedMask(~Mask)) {
8961     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8962     // where lsb(mask) == #shamt and masked bits of B are known zero.
8963     SDValue ShAmt = N00.getOperand(1);
8964     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8965     unsigned LSB = countTrailingZeros(Mask);
8966     if (ShAmtC != LSB)
8967       return SDValue();
8968
8969     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8970                       DAG.getConstant(~Mask, DL, MVT::i32));
8971
8972     // Do not add new nodes to DAG combiner worklist.
8973     DCI.CombineTo(N, Res, false);
8974   }
8975
8976   return SDValue();
8977 }
8978
8979 static SDValue PerformXORCombine(SDNode *N,
8980                                  TargetLowering::DAGCombinerInfo &DCI,
8981                                  const ARMSubtarget *Subtarget) {
8982   EVT VT = N->getValueType(0);
8983   SelectionDAG &DAG = DCI.DAG;
8984
8985   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8986     return SDValue();
8987
8988   if (!Subtarget->isThumb1Only()) {
8989     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8990     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8991     if (Result.getNode())
8992       return Result;
8993   }
8994
8995   return SDValue();
8996 }
8997
8998 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8999 /// the bits being cleared by the AND are not demanded by the BFI.
9000 static SDValue PerformBFICombine(SDNode *N,
9001                                  TargetLowering::DAGCombinerInfo &DCI) {
9002   SDValue N1 = N->getOperand(1);
9003   if (N1.getOpcode() == ISD::AND) {
9004     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9005     if (!N11C)
9006       return SDValue();
9007     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9008     unsigned LSB = countTrailingZeros(~InvMask);
9009     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9010     assert(Width <
9011                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9012            "undefined behavior");
9013     unsigned Mask = (1u << Width) - 1;
9014     unsigned Mask2 = N11C->getZExtValue();
9015     if ((Mask & (~Mask2)) == 0)
9016       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9017                              N->getOperand(0), N1.getOperand(0),
9018                              N->getOperand(2));
9019   }
9020   return SDValue();
9021 }
9022
9023 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9024 /// ARMISD::VMOVRRD.
9025 static SDValue PerformVMOVRRDCombine(SDNode *N,
9026                                      TargetLowering::DAGCombinerInfo &DCI,
9027                                      const ARMSubtarget *Subtarget) {
9028   // vmovrrd(vmovdrr x, y) -> x,y
9029   SDValue InDouble = N->getOperand(0);
9030   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9031     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9032
9033   // vmovrrd(load f64) -> (load i32), (load i32)
9034   SDNode *InNode = InDouble.getNode();
9035   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9036       InNode->getValueType(0) == MVT::f64 &&
9037       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9038       !cast<LoadSDNode>(InNode)->isVolatile()) {
9039     // TODO: Should this be done for non-FrameIndex operands?
9040     LoadSDNode *LD = cast<LoadSDNode>(InNode);
9041
9042     SelectionDAG &DAG = DCI.DAG;
9043     SDLoc DL(LD);
9044     SDValue BasePtr = LD->getBasePtr();
9045     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9046                                  LD->getPointerInfo(), LD->isVolatile(),
9047                                  LD->isNonTemporal(), LD->isInvariant(),
9048                                  LD->getAlignment());
9049
9050     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9051                                     DAG.getConstant(4, DL, MVT::i32));
9052     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9053                                  LD->getPointerInfo(), LD->isVolatile(),
9054                                  LD->isNonTemporal(), LD->isInvariant(),
9055                                  std::min(4U, LD->getAlignment() / 2));
9056
9057     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9058     if (DCI.DAG.getDataLayout().isBigEndian())
9059       std::swap (NewLD1, NewLD2);
9060     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9061     return Result;
9062   }
9063
9064   return SDValue();
9065 }
9066
9067 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9068 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
9069 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9070   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9071   SDValue Op0 = N->getOperand(0);
9072   SDValue Op1 = N->getOperand(1);
9073   if (Op0.getOpcode() == ISD::BITCAST)
9074     Op0 = Op0.getOperand(0);
9075   if (Op1.getOpcode() == ISD::BITCAST)
9076     Op1 = Op1.getOperand(0);
9077   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9078       Op0.getNode() == Op1.getNode() &&
9079       Op0.getResNo() == 0 && Op1.getResNo() == 1)
9080     return DAG.getNode(ISD::BITCAST, SDLoc(N),
9081                        N->getValueType(0), Op0.getOperand(0));
9082   return SDValue();
9083 }
9084
9085 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9086 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9087 /// i64 vector to have f64 elements, since the value can then be loaded
9088 /// directly into a VFP register.
9089 static bool hasNormalLoadOperand(SDNode *N) {
9090   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9091   for (unsigned i = 0; i < NumElts; ++i) {
9092     SDNode *Elt = N->getOperand(i).getNode();
9093     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9094       return true;
9095   }
9096   return false;
9097 }
9098
9099 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9100 /// ISD::BUILD_VECTOR.
9101 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9102                                           TargetLowering::DAGCombinerInfo &DCI,
9103                                           const ARMSubtarget *Subtarget) {
9104   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9105   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9106   // into a pair of GPRs, which is fine when the value is used as a scalar,
9107   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9108   SelectionDAG &DAG = DCI.DAG;
9109   if (N->getNumOperands() == 2) {
9110     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9111     if (RV.getNode())
9112       return RV;
9113   }
9114
9115   // Load i64 elements as f64 values so that type legalization does not split
9116   // them up into i32 values.
9117   EVT VT = N->getValueType(0);
9118   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9119     return SDValue();
9120   SDLoc dl(N);
9121   SmallVector<SDValue, 8> Ops;
9122   unsigned NumElts = VT.getVectorNumElements();
9123   for (unsigned i = 0; i < NumElts; ++i) {
9124     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9125     Ops.push_back(V);
9126     // Make the DAGCombiner fold the bitcast.
9127     DCI.AddToWorklist(V.getNode());
9128   }
9129   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9130   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9131   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9132 }
9133
9134 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9135 static SDValue
9136 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9137   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9138   // At that time, we may have inserted bitcasts from integer to float.
9139   // If these bitcasts have survived DAGCombine, change the lowering of this
9140   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9141   // force to use floating point types.
9142
9143   // Make sure we can change the type of the vector.
9144   // This is possible iff:
9145   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9146   //    1.1. Vector is used only once.
9147   //    1.2. Use is a bit convert to an integer type.
9148   // 2. The size of its operands are 32-bits (64-bits are not legal).
9149   EVT VT = N->getValueType(0);
9150   EVT EltVT = VT.getVectorElementType();
9151
9152   // Check 1.1. and 2.
9153   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9154     return SDValue();
9155
9156   // By construction, the input type must be float.
9157   assert(EltVT == MVT::f32 && "Unexpected type!");
9158
9159   // Check 1.2.
9160   SDNode *Use = *N->use_begin();
9161   if (Use->getOpcode() != ISD::BITCAST ||
9162       Use->getValueType(0).isFloatingPoint())
9163     return SDValue();
9164
9165   // Check profitability.
9166   // Model is, if more than half of the relevant operands are bitcast from
9167   // i32, turn the build_vector into a sequence of insert_vector_elt.
9168   // Relevant operands are everything that is not statically
9169   // (i.e., at compile time) bitcasted.
9170   unsigned NumOfBitCastedElts = 0;
9171   unsigned NumElts = VT.getVectorNumElements();
9172   unsigned NumOfRelevantElts = NumElts;
9173   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9174     SDValue Elt = N->getOperand(Idx);
9175     if (Elt->getOpcode() == ISD::BITCAST) {
9176       // Assume only bit cast to i32 will go away.
9177       if (Elt->getOperand(0).getValueType() == MVT::i32)
9178         ++NumOfBitCastedElts;
9179     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9180       // Constants are statically casted, thus do not count them as
9181       // relevant operands.
9182       --NumOfRelevantElts;
9183   }
9184
9185   // Check if more than half of the elements require a non-free bitcast.
9186   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9187     return SDValue();
9188
9189   SelectionDAG &DAG = DCI.DAG;
9190   // Create the new vector type.
9191   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9192   // Check if the type is legal.
9193   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9194   if (!TLI.isTypeLegal(VecVT))
9195     return SDValue();
9196
9197   // Combine:
9198   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9199   // => BITCAST INSERT_VECTOR_ELT
9200   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9201   //                      (BITCAST EN), N.
9202   SDValue Vec = DAG.getUNDEF(VecVT);
9203   SDLoc dl(N);
9204   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9205     SDValue V = N->getOperand(Idx);
9206     if (V.getOpcode() == ISD::UNDEF)
9207       continue;
9208     if (V.getOpcode() == ISD::BITCAST &&
9209         V->getOperand(0).getValueType() == MVT::i32)
9210       // Fold obvious case.
9211       V = V.getOperand(0);
9212     else {
9213       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9214       // Make the DAGCombiner fold the bitcasts.
9215       DCI.AddToWorklist(V.getNode());
9216     }
9217     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9218     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9219   }
9220   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9221   // Make the DAGCombiner fold the bitcasts.
9222   DCI.AddToWorklist(Vec.getNode());
9223   return Vec;
9224 }
9225
9226 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9227 /// ISD::INSERT_VECTOR_ELT.
9228 static SDValue PerformInsertEltCombine(SDNode *N,
9229                                        TargetLowering::DAGCombinerInfo &DCI) {
9230   // Bitcast an i64 load inserted into a vector to f64.
9231   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9232   EVT VT = N->getValueType(0);
9233   SDNode *Elt = N->getOperand(1).getNode();
9234   if (VT.getVectorElementType() != MVT::i64 ||
9235       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9236     return SDValue();
9237
9238   SelectionDAG &DAG = DCI.DAG;
9239   SDLoc dl(N);
9240   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9241                                  VT.getVectorNumElements());
9242   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9243   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9244   // Make the DAGCombiner fold the bitcasts.
9245   DCI.AddToWorklist(Vec.getNode());
9246   DCI.AddToWorklist(V.getNode());
9247   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9248                                Vec, V, N->getOperand(2));
9249   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9250 }
9251
9252 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9253 /// ISD::VECTOR_SHUFFLE.
9254 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9255   // The LLVM shufflevector instruction does not require the shuffle mask
9256   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9257   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9258   // operands do not match the mask length, they are extended by concatenating
9259   // them with undef vectors.  That is probably the right thing for other
9260   // targets, but for NEON it is better to concatenate two double-register
9261   // size vector operands into a single quad-register size vector.  Do that
9262   // transformation here:
9263   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9264   //   shuffle(concat(v1, v2), undef)
9265   SDValue Op0 = N->getOperand(0);
9266   SDValue Op1 = N->getOperand(1);
9267   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9268       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9269       Op0.getNumOperands() != 2 ||
9270       Op1.getNumOperands() != 2)
9271     return SDValue();
9272   SDValue Concat0Op1 = Op0.getOperand(1);
9273   SDValue Concat1Op1 = Op1.getOperand(1);
9274   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9275       Concat1Op1.getOpcode() != ISD::UNDEF)
9276     return SDValue();
9277   // Skip the transformation if any of the types are illegal.
9278   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9279   EVT VT = N->getValueType(0);
9280   if (!TLI.isTypeLegal(VT) ||
9281       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9282       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9283     return SDValue();
9284
9285   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9286                                   Op0.getOperand(0), Op1.getOperand(0));
9287   // Translate the shuffle mask.
9288   SmallVector<int, 16> NewMask;
9289   unsigned NumElts = VT.getVectorNumElements();
9290   unsigned HalfElts = NumElts/2;
9291   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9292   for (unsigned n = 0; n < NumElts; ++n) {
9293     int MaskElt = SVN->getMaskElt(n);
9294     int NewElt = -1;
9295     if (MaskElt < (int)HalfElts)
9296       NewElt = MaskElt;
9297     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9298       NewElt = HalfElts + MaskElt - NumElts;
9299     NewMask.push_back(NewElt);
9300   }
9301   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9302                               DAG.getUNDEF(VT), NewMask.data());
9303 }
9304
9305 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9306 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9307 /// base address updates.
9308 /// For generic load/stores, the memory type is assumed to be a vector.
9309 /// The caller is assumed to have checked legality.
9310 static SDValue CombineBaseUpdate(SDNode *N,
9311                                  TargetLowering::DAGCombinerInfo &DCI) {
9312   SelectionDAG &DAG = DCI.DAG;
9313   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9314                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9315   const bool isStore = N->getOpcode() == ISD::STORE;
9316   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9317   SDValue Addr = N->getOperand(AddrOpIdx);
9318   MemSDNode *MemN = cast<MemSDNode>(N);
9319   SDLoc dl(N);
9320
9321   // Search for a use of the address operand that is an increment.
9322   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9323          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9324     SDNode *User = *UI;
9325     if (User->getOpcode() != ISD::ADD ||
9326         UI.getUse().getResNo() != Addr.getResNo())
9327       continue;
9328
9329     // Check that the add is independent of the load/store.  Otherwise, folding
9330     // it would create a cycle.
9331     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9332       continue;
9333
9334     // Find the new opcode for the updating load/store.
9335     bool isLoadOp = true;
9336     bool isLaneOp = false;
9337     unsigned NewOpc = 0;
9338     unsigned NumVecs = 0;
9339     if (isIntrinsic) {
9340       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9341       switch (IntNo) {
9342       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9343       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9344         NumVecs = 1; break;
9345       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9346         NumVecs = 2; break;
9347       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9348         NumVecs = 3; break;
9349       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9350         NumVecs = 4; break;
9351       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9352         NumVecs = 2; isLaneOp = true; break;
9353       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9354         NumVecs = 3; isLaneOp = true; break;
9355       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9356         NumVecs = 4; isLaneOp = true; break;
9357       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9358         NumVecs = 1; isLoadOp = false; break;
9359       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9360         NumVecs = 2; isLoadOp = false; break;
9361       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9362         NumVecs = 3; isLoadOp = false; break;
9363       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9364         NumVecs = 4; isLoadOp = false; break;
9365       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9366         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9367       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9368         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9369       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9370         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9371       }
9372     } else {
9373       isLaneOp = true;
9374       switch (N->getOpcode()) {
9375       default: llvm_unreachable("unexpected opcode for Neon base update");
9376       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9377       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9378       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9379       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9380         NumVecs = 1; isLaneOp = false; break;
9381       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9382         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9383       }
9384     }
9385
9386     // Find the size of memory referenced by the load/store.
9387     EVT VecTy;
9388     if (isLoadOp) {
9389       VecTy = N->getValueType(0);
9390     } else if (isIntrinsic) {
9391       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9392     } else {
9393       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9394       VecTy = N->getOperand(1).getValueType();
9395     }
9396
9397     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9398     if (isLaneOp)
9399       NumBytes /= VecTy.getVectorNumElements();
9400
9401     // If the increment is a constant, it must match the memory ref size.
9402     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9403     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9404       uint64_t IncVal = CInc->getZExtValue();
9405       if (IncVal != NumBytes)
9406         continue;
9407     } else if (NumBytes >= 3 * 16) {
9408       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9409       // separate instructions that make it harder to use a non-constant update.
9410       continue;
9411     }
9412
9413     // OK, we found an ADD we can fold into the base update.
9414     // Now, create a _UPD node, taking care of not breaking alignment.
9415
9416     EVT AlignedVecTy = VecTy;
9417     unsigned Alignment = MemN->getAlignment();
9418
9419     // If this is a less-than-standard-aligned load/store, change the type to
9420     // match the standard alignment.
9421     // The alignment is overlooked when selecting _UPD variants; and it's
9422     // easier to introduce bitcasts here than fix that.
9423     // There are 3 ways to get to this base-update combine:
9424     // - intrinsics: they are assumed to be properly aligned (to the standard
9425     //   alignment of the memory type), so we don't need to do anything.
9426     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9427     //   intrinsics, so, likewise, there's nothing to do.
9428     // - generic load/store instructions: the alignment is specified as an
9429     //   explicit operand, rather than implicitly as the standard alignment
9430     //   of the memory type (like the intrisics).  We need to change the
9431     //   memory type to match the explicit alignment.  That way, we don't
9432     //   generate non-standard-aligned ARMISD::VLDx nodes.
9433     if (isa<LSBaseSDNode>(N)) {
9434       if (Alignment == 0)
9435         Alignment = 1;
9436       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9437         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9438         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9439         assert(!isLaneOp && "Unexpected generic load/store lane.");
9440         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9441         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9442       }
9443       // Don't set an explicit alignment on regular load/stores that we want
9444       // to transform to VLD/VST 1_UPD nodes.
9445       // This matches the behavior of regular load/stores, which only get an
9446       // explicit alignment if the MMO alignment is larger than the standard
9447       // alignment of the memory type.
9448       // Intrinsics, however, always get an explicit alignment, set to the
9449       // alignment of the MMO.
9450       Alignment = 1;
9451     }
9452
9453     // Create the new updating load/store node.
9454     // First, create an SDVTList for the new updating node's results.
9455     EVT Tys[6];
9456     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9457     unsigned n;
9458     for (n = 0; n < NumResultVecs; ++n)
9459       Tys[n] = AlignedVecTy;
9460     Tys[n++] = MVT::i32;
9461     Tys[n] = MVT::Other;
9462     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9463
9464     // Then, gather the new node's operands.
9465     SmallVector<SDValue, 8> Ops;
9466     Ops.push_back(N->getOperand(0)); // incoming chain
9467     Ops.push_back(N->getOperand(AddrOpIdx));
9468     Ops.push_back(Inc);
9469
9470     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9471       // Try to match the intrinsic's signature
9472       Ops.push_back(StN->getValue());
9473     } else {
9474       // Loads (and of course intrinsics) match the intrinsics' signature,
9475       // so just add all but the alignment operand.
9476       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9477         Ops.push_back(N->getOperand(i));
9478     }
9479
9480     // For all node types, the alignment operand is always the last one.
9481     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9482
9483     // If this is a non-standard-aligned STORE, the penultimate operand is the
9484     // stored value.  Bitcast it to the aligned type.
9485     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9486       SDValue &StVal = Ops[Ops.size()-2];
9487       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9488     }
9489
9490     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9491                                            Ops, AlignedVecTy,
9492                                            MemN->getMemOperand());
9493
9494     // Update the uses.
9495     SmallVector<SDValue, 5> NewResults;
9496     for (unsigned i = 0; i < NumResultVecs; ++i)
9497       NewResults.push_back(SDValue(UpdN.getNode(), i));
9498
9499     // If this is an non-standard-aligned LOAD, the first result is the loaded
9500     // value.  Bitcast it to the expected result type.
9501     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9502       SDValue &LdVal = NewResults[0];
9503       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9504     }
9505
9506     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9507     DCI.CombineTo(N, NewResults);
9508     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9509
9510     break;
9511   }
9512   return SDValue();
9513 }
9514
9515 static SDValue PerformVLDCombine(SDNode *N,
9516                                  TargetLowering::DAGCombinerInfo &DCI) {
9517   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9518     return SDValue();
9519
9520   return CombineBaseUpdate(N, DCI);
9521 }
9522
9523 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9524 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9525 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9526 /// return true.
9527 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9528   SelectionDAG &DAG = DCI.DAG;
9529   EVT VT = N->getValueType(0);
9530   // vldN-dup instructions only support 64-bit vectors for N > 1.
9531   if (!VT.is64BitVector())
9532     return false;
9533
9534   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9535   SDNode *VLD = N->getOperand(0).getNode();
9536   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9537     return false;
9538   unsigned NumVecs = 0;
9539   unsigned NewOpc = 0;
9540   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9541   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9542     NumVecs = 2;
9543     NewOpc = ARMISD::VLD2DUP;
9544   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9545     NumVecs = 3;
9546     NewOpc = ARMISD::VLD3DUP;
9547   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9548     NumVecs = 4;
9549     NewOpc = ARMISD::VLD4DUP;
9550   } else {
9551     return false;
9552   }
9553
9554   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9555   // numbers match the load.
9556   unsigned VLDLaneNo =
9557     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9558   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9559        UI != UE; ++UI) {
9560     // Ignore uses of the chain result.
9561     if (UI.getUse().getResNo() == NumVecs)
9562       continue;
9563     SDNode *User = *UI;
9564     if (User->getOpcode() != ARMISD::VDUPLANE ||
9565         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9566       return false;
9567   }
9568
9569   // Create the vldN-dup node.
9570   EVT Tys[5];
9571   unsigned n;
9572   for (n = 0; n < NumVecs; ++n)
9573     Tys[n] = VT;
9574   Tys[n] = MVT::Other;
9575   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9576   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9577   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9578   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9579                                            Ops, VLDMemInt->getMemoryVT(),
9580                                            VLDMemInt->getMemOperand());
9581
9582   // Update the uses.
9583   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9584        UI != UE; ++UI) {
9585     unsigned ResNo = UI.getUse().getResNo();
9586     // Ignore uses of the chain result.
9587     if (ResNo == NumVecs)
9588       continue;
9589     SDNode *User = *UI;
9590     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9591   }
9592
9593   // Now the vldN-lane intrinsic is dead except for its chain result.
9594   // Update uses of the chain.
9595   std::vector<SDValue> VLDDupResults;
9596   for (unsigned n = 0; n < NumVecs; ++n)
9597     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9598   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9599   DCI.CombineTo(VLD, VLDDupResults);
9600
9601   return true;
9602 }
9603
9604 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9605 /// ARMISD::VDUPLANE.
9606 static SDValue PerformVDUPLANECombine(SDNode *N,
9607                                       TargetLowering::DAGCombinerInfo &DCI) {
9608   SDValue Op = N->getOperand(0);
9609
9610   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9611   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9612   if (CombineVLDDUP(N, DCI))
9613     return SDValue(N, 0);
9614
9615   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9616   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9617   while (Op.getOpcode() == ISD::BITCAST)
9618     Op = Op.getOperand(0);
9619   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9620     return SDValue();
9621
9622   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9623   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9624   // The canonical VMOV for a zero vector uses a 32-bit element size.
9625   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9626   unsigned EltBits;
9627   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9628     EltSize = 8;
9629   EVT VT = N->getValueType(0);
9630   if (EltSize > VT.getVectorElementType().getSizeInBits())
9631     return SDValue();
9632
9633   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9634 }
9635
9636 static SDValue PerformLOADCombine(SDNode *N,
9637                                   TargetLowering::DAGCombinerInfo &DCI) {
9638   EVT VT = N->getValueType(0);
9639
9640   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9641   if (ISD::isNormalLoad(N) && VT.isVector() &&
9642       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9643     return CombineBaseUpdate(N, DCI);
9644
9645   return SDValue();
9646 }
9647
9648 /// PerformSTORECombine - Target-specific dag combine xforms for
9649 /// ISD::STORE.
9650 static SDValue PerformSTORECombine(SDNode *N,
9651                                    TargetLowering::DAGCombinerInfo &DCI) {
9652   StoreSDNode *St = cast<StoreSDNode>(N);
9653   if (St->isVolatile())
9654     return SDValue();
9655
9656   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9657   // pack all of the elements in one place.  Next, store to memory in fewer
9658   // chunks.
9659   SDValue StVal = St->getValue();
9660   EVT VT = StVal.getValueType();
9661   if (St->isTruncatingStore() && VT.isVector()) {
9662     SelectionDAG &DAG = DCI.DAG;
9663     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9664     EVT StVT = St->getMemoryVT();
9665     unsigned NumElems = VT.getVectorNumElements();
9666     assert(StVT != VT && "Cannot truncate to the same type");
9667     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9668     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9669
9670     // From, To sizes and ElemCount must be pow of two
9671     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9672
9673     // We are going to use the original vector elt for storing.
9674     // Accumulated smaller vector elements must be a multiple of the store size.
9675     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9676
9677     unsigned SizeRatio  = FromEltSz / ToEltSz;
9678     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9679
9680     // Create a type on which we perform the shuffle.
9681     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9682                                      NumElems*SizeRatio);
9683     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9684
9685     SDLoc DL(St);
9686     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9687     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9688     for (unsigned i = 0; i < NumElems; ++i)
9689       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9690                           ? (i + 1) * SizeRatio - 1
9691                           : i * SizeRatio;
9692
9693     // Can't shuffle using an illegal type.
9694     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9695
9696     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9697                                 DAG.getUNDEF(WideVec.getValueType()),
9698                                 ShuffleVec.data());
9699     // At this point all of the data is stored at the bottom of the
9700     // register. We now need to save it to mem.
9701
9702     // Find the largest store unit
9703     MVT StoreType = MVT::i8;
9704     for (MVT Tp : MVT::integer_valuetypes()) {
9705       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9706         StoreType = Tp;
9707     }
9708     // Didn't find a legal store type.
9709     if (!TLI.isTypeLegal(StoreType))
9710       return SDValue();
9711
9712     // Bitcast the original vector into a vector of store-size units
9713     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9714             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9715     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9716     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9717     SmallVector<SDValue, 8> Chains;
9718     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9719                                         TLI.getPointerTy(DAG.getDataLayout()));
9720     SDValue BasePtr = St->getBasePtr();
9721
9722     // Perform one or more big stores into memory.
9723     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9724     for (unsigned I = 0; I < E; I++) {
9725       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9726                                    StoreType, ShuffWide,
9727                                    DAG.getIntPtrConstant(I, DL));
9728       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9729                                 St->getPointerInfo(), St->isVolatile(),
9730                                 St->isNonTemporal(), St->getAlignment());
9731       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9732                             Increment);
9733       Chains.push_back(Ch);
9734     }
9735     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9736   }
9737
9738   if (!ISD::isNormalStore(St))
9739     return SDValue();
9740
9741   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9742   // ARM stores of arguments in the same cache line.
9743   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9744       StVal.getNode()->hasOneUse()) {
9745     SelectionDAG  &DAG = DCI.DAG;
9746     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9747     SDLoc DL(St);
9748     SDValue BasePtr = St->getBasePtr();
9749     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9750                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9751                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9752                                   St->isNonTemporal(), St->getAlignment());
9753
9754     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9755                                     DAG.getConstant(4, DL, MVT::i32));
9756     return DAG.getStore(NewST1.getValue(0), DL,
9757                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9758                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9759                         St->isNonTemporal(),
9760                         std::min(4U, St->getAlignment() / 2));
9761   }
9762
9763   if (StVal.getValueType() == MVT::i64 &&
9764       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9765
9766     // Bitcast an i64 store extracted from a vector to f64.
9767     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9768     SelectionDAG &DAG = DCI.DAG;
9769     SDLoc dl(StVal);
9770     SDValue IntVec = StVal.getOperand(0);
9771     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9772                                    IntVec.getValueType().getVectorNumElements());
9773     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9774     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9775                                  Vec, StVal.getOperand(1));
9776     dl = SDLoc(N);
9777     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9778     // Make the DAGCombiner fold the bitcasts.
9779     DCI.AddToWorklist(Vec.getNode());
9780     DCI.AddToWorklist(ExtElt.getNode());
9781     DCI.AddToWorklist(V.getNode());
9782     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9783                         St->getPointerInfo(), St->isVolatile(),
9784                         St->isNonTemporal(), St->getAlignment(),
9785                         St->getAAInfo());
9786   }
9787
9788   // If this is a legal vector store, try to combine it into a VST1_UPD.
9789   if (ISD::isNormalStore(N) && VT.isVector() &&
9790       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9791     return CombineBaseUpdate(N, DCI);
9792
9793   return SDValue();
9794 }
9795
9796 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9797 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9798 /// when the VMUL has a constant operand that is a power of 2.
9799 ///
9800 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9801 ///  vmul.f32        d16, d17, d16
9802 ///  vcvt.s32.f32    d16, d16
9803 /// becomes:
9804 ///  vcvt.s32.f32    d16, d16, #3
9805 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
9806                                   const ARMSubtarget *Subtarget) {
9807   if (!Subtarget->hasNEON())
9808     return SDValue();
9809
9810   SDValue Op = N->getOperand(0);
9811   if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
9812     return SDValue();
9813
9814   SDValue ConstVec = Op->getOperand(1);
9815   if (!isa<BuildVectorSDNode>(ConstVec))
9816     return SDValue();
9817
9818   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9819   uint32_t FloatBits = FloatTy.getSizeInBits();
9820   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9821   uint32_t IntBits = IntTy.getSizeInBits();
9822   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9823   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
9824     // These instructions only exist converting from f32 to i32. We can handle
9825     // smaller integers by generating an extra truncate, but larger ones would
9826     // be lossy. We also can't handle more then 4 lanes, since these intructions
9827     // only support v2i32/v4i32 types.
9828     return SDValue();
9829   }
9830
9831   BitVector UndefElements;
9832   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9833   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
9834   if (C == -1 || C == 0 || C > 32)
9835     return SDValue();
9836
9837   SDLoc dl(N);
9838   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9839   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9840     Intrinsic::arm_neon_vcvtfp2fxu;
9841   SDValue FixConv = DAG.getNode(
9842       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9843       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
9844       DAG.getConstant(C, dl, MVT::i32));
9845
9846   if (IntBits < FloatBits)
9847     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9848
9849   return FixConv;
9850 }
9851
9852 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9853 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9854 /// when the VDIV has a constant operand that is a power of 2.
9855 ///
9856 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9857 ///  vcvt.f32.s32    d16, d16
9858 ///  vdiv.f32        d16, d17, d16
9859 /// becomes:
9860 ///  vcvt.f32.s32    d16, d16, #3
9861 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
9862                                   const ARMSubtarget *Subtarget) {
9863   if (!Subtarget->hasNEON())
9864     return SDValue();
9865
9866   SDValue Op = N->getOperand(0);
9867   unsigned OpOpcode = Op.getNode()->getOpcode();
9868   if (!N->getValueType(0).isVector() ||
9869       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9870     return SDValue();
9871
9872   SDValue ConstVec = N->getOperand(1);
9873   if (!isa<BuildVectorSDNode>(ConstVec))
9874     return SDValue();
9875
9876   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9877   uint32_t FloatBits = FloatTy.getSizeInBits();
9878   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9879   uint32_t IntBits = IntTy.getSizeInBits();
9880   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9881   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
9882     // These instructions only exist converting from i32 to f32. We can handle
9883     // smaller integers by generating an extra extend, but larger ones would
9884     // be lossy. We also can't handle more then 4 lanes, since these intructions
9885     // only support v2i32/v4i32 types.
9886     return SDValue();
9887   }
9888
9889   BitVector UndefElements;
9890   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9891   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
9892   if (C == -1 || C == 0 || C > 32)
9893     return SDValue();
9894
9895   SDLoc dl(N);
9896   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9897   SDValue ConvInput = Op.getOperand(0);
9898   if (IntBits < FloatBits)
9899     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9900                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9901                             ConvInput);
9902
9903   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9904     Intrinsic::arm_neon_vcvtfxu2fp;
9905   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9906                      Op.getValueType(),
9907                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9908                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
9909 }
9910
9911 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9912 /// operand of a vector shift operation, where all the elements of the
9913 /// build_vector must have the same constant integer value.
9914 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9915   // Ignore bit_converts.
9916   while (Op.getOpcode() == ISD::BITCAST)
9917     Op = Op.getOperand(0);
9918   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9919   APInt SplatBits, SplatUndef;
9920   unsigned SplatBitSize;
9921   bool HasAnyUndefs;
9922   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9923                                       HasAnyUndefs, ElementBits) ||
9924       SplatBitSize > ElementBits)
9925     return false;
9926   Cnt = SplatBits.getSExtValue();
9927   return true;
9928 }
9929
9930 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9931 /// operand of a vector shift left operation.  That value must be in the range:
9932 ///   0 <= Value < ElementBits for a left shift; or
9933 ///   0 <= Value <= ElementBits for a long left shift.
9934 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9935   assert(VT.isVector() && "vector shift count is not a vector type");
9936   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9937   if (! getVShiftImm(Op, ElementBits, Cnt))
9938     return false;
9939   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9940 }
9941
9942 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9943 /// operand of a vector shift right operation.  For a shift opcode, the value
9944 /// is positive, but for an intrinsic the value count must be negative. The
9945 /// absolute value must be in the range:
9946 ///   1 <= |Value| <= ElementBits for a right shift; or
9947 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9948 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9949                          int64_t &Cnt) {
9950   assert(VT.isVector() && "vector shift count is not a vector type");
9951   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9952   if (! getVShiftImm(Op, ElementBits, Cnt))
9953     return false;
9954   if (!isIntrinsic)
9955     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9956   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9957     Cnt = -Cnt;
9958     return true;
9959   }
9960   return false;
9961 }
9962
9963 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9964 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9965   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9966   switch (IntNo) {
9967   default:
9968     // Don't do anything for most intrinsics.
9969     break;
9970
9971   case Intrinsic::arm_neon_vabds:
9972     if (!N->getValueType(0).isInteger())
9973       return SDValue();
9974     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9975                        N->getOperand(1), N->getOperand(2));
9976   case Intrinsic::arm_neon_vabdu:
9977     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9978                        N->getOperand(1), N->getOperand(2));
9979
9980   // Vector shifts: check for immediate versions and lower them.
9981   // Note: This is done during DAG combining instead of DAG legalizing because
9982   // the build_vectors for 64-bit vector element shift counts are generally
9983   // not legal, and it is hard to see their values after they get legalized to
9984   // loads from a constant pool.
9985   case Intrinsic::arm_neon_vshifts:
9986   case Intrinsic::arm_neon_vshiftu:
9987   case Intrinsic::arm_neon_vrshifts:
9988   case Intrinsic::arm_neon_vrshiftu:
9989   case Intrinsic::arm_neon_vrshiftn:
9990   case Intrinsic::arm_neon_vqshifts:
9991   case Intrinsic::arm_neon_vqshiftu:
9992   case Intrinsic::arm_neon_vqshiftsu:
9993   case Intrinsic::arm_neon_vqshiftns:
9994   case Intrinsic::arm_neon_vqshiftnu:
9995   case Intrinsic::arm_neon_vqshiftnsu:
9996   case Intrinsic::arm_neon_vqrshiftns:
9997   case Intrinsic::arm_neon_vqrshiftnu:
9998   case Intrinsic::arm_neon_vqrshiftnsu: {
9999     EVT VT = N->getOperand(1).getValueType();
10000     int64_t Cnt;
10001     unsigned VShiftOpc = 0;
10002
10003     switch (IntNo) {
10004     case Intrinsic::arm_neon_vshifts:
10005     case Intrinsic::arm_neon_vshiftu:
10006       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10007         VShiftOpc = ARMISD::VSHL;
10008         break;
10009       }
10010       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10011         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10012                      ARMISD::VSHRs : ARMISD::VSHRu);
10013         break;
10014       }
10015       return SDValue();
10016
10017     case Intrinsic::arm_neon_vrshifts:
10018     case Intrinsic::arm_neon_vrshiftu:
10019       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10020         break;
10021       return SDValue();
10022
10023     case Intrinsic::arm_neon_vqshifts:
10024     case Intrinsic::arm_neon_vqshiftu:
10025       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10026         break;
10027       return SDValue();
10028
10029     case Intrinsic::arm_neon_vqshiftsu:
10030       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10031         break;
10032       llvm_unreachable("invalid shift count for vqshlu intrinsic");
10033
10034     case Intrinsic::arm_neon_vrshiftn:
10035     case Intrinsic::arm_neon_vqshiftns:
10036     case Intrinsic::arm_neon_vqshiftnu:
10037     case Intrinsic::arm_neon_vqshiftnsu:
10038     case Intrinsic::arm_neon_vqrshiftns:
10039     case Intrinsic::arm_neon_vqrshiftnu:
10040     case Intrinsic::arm_neon_vqrshiftnsu:
10041       // Narrowing shifts require an immediate right shift.
10042       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10043         break;
10044       llvm_unreachable("invalid shift count for narrowing vector shift "
10045                        "intrinsic");
10046
10047     default:
10048       llvm_unreachable("unhandled vector shift");
10049     }
10050
10051     switch (IntNo) {
10052     case Intrinsic::arm_neon_vshifts:
10053     case Intrinsic::arm_neon_vshiftu:
10054       // Opcode already set above.
10055       break;
10056     case Intrinsic::arm_neon_vrshifts:
10057       VShiftOpc = ARMISD::VRSHRs; break;
10058     case Intrinsic::arm_neon_vrshiftu:
10059       VShiftOpc = ARMISD::VRSHRu; break;
10060     case Intrinsic::arm_neon_vrshiftn:
10061       VShiftOpc = ARMISD::VRSHRN; break;
10062     case Intrinsic::arm_neon_vqshifts:
10063       VShiftOpc = ARMISD::VQSHLs; break;
10064     case Intrinsic::arm_neon_vqshiftu:
10065       VShiftOpc = ARMISD::VQSHLu; break;
10066     case Intrinsic::arm_neon_vqshiftsu:
10067       VShiftOpc = ARMISD::VQSHLsu; break;
10068     case Intrinsic::arm_neon_vqshiftns:
10069       VShiftOpc = ARMISD::VQSHRNs; break;
10070     case Intrinsic::arm_neon_vqshiftnu:
10071       VShiftOpc = ARMISD::VQSHRNu; break;
10072     case Intrinsic::arm_neon_vqshiftnsu:
10073       VShiftOpc = ARMISD::VQSHRNsu; break;
10074     case Intrinsic::arm_neon_vqrshiftns:
10075       VShiftOpc = ARMISD::VQRSHRNs; break;
10076     case Intrinsic::arm_neon_vqrshiftnu:
10077       VShiftOpc = ARMISD::VQRSHRNu; break;
10078     case Intrinsic::arm_neon_vqrshiftnsu:
10079       VShiftOpc = ARMISD::VQRSHRNsu; break;
10080     }
10081
10082     SDLoc dl(N);
10083     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10084                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10085   }
10086
10087   case Intrinsic::arm_neon_vshiftins: {
10088     EVT VT = N->getOperand(1).getValueType();
10089     int64_t Cnt;
10090     unsigned VShiftOpc = 0;
10091
10092     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10093       VShiftOpc = ARMISD::VSLI;
10094     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10095       VShiftOpc = ARMISD::VSRI;
10096     else {
10097       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10098     }
10099
10100     SDLoc dl(N);
10101     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10102                        N->getOperand(1), N->getOperand(2),
10103                        DAG.getConstant(Cnt, dl, MVT::i32));
10104   }
10105
10106   case Intrinsic::arm_neon_vqrshifts:
10107   case Intrinsic::arm_neon_vqrshiftu:
10108     // No immediate versions of these to check for.
10109     break;
10110   }
10111
10112   return SDValue();
10113 }
10114
10115 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10116 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
10117 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10118 /// vector element shift counts are generally not legal, and it is hard to see
10119 /// their values after they get legalized to loads from a constant pool.
10120 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10121                                    const ARMSubtarget *ST) {
10122   EVT VT = N->getValueType(0);
10123   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10124     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10125     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10126     SDValue N1 = N->getOperand(1);
10127     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10128       SDValue N0 = N->getOperand(0);
10129       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10130           DAG.MaskedValueIsZero(N0.getOperand(0),
10131                                 APInt::getHighBitsSet(32, 16)))
10132         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10133     }
10134   }
10135
10136   // Nothing to be done for scalar shifts.
10137   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10138   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10139     return SDValue();
10140
10141   assert(ST->hasNEON() && "unexpected vector shift");
10142   int64_t Cnt;
10143
10144   switch (N->getOpcode()) {
10145   default: llvm_unreachable("unexpected shift opcode");
10146
10147   case ISD::SHL:
10148     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10149       SDLoc dl(N);
10150       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10151                          DAG.getConstant(Cnt, dl, MVT::i32));
10152     }
10153     break;
10154
10155   case ISD::SRA:
10156   case ISD::SRL:
10157     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10158       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10159                             ARMISD::VSHRs : ARMISD::VSHRu);
10160       SDLoc dl(N);
10161       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10162                          DAG.getConstant(Cnt, dl, MVT::i32));
10163     }
10164   }
10165   return SDValue();
10166 }
10167
10168 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10169 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10170 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10171                                     const ARMSubtarget *ST) {
10172   SDValue N0 = N->getOperand(0);
10173
10174   // Check for sign- and zero-extensions of vector extract operations of 8-
10175   // and 16-bit vector elements.  NEON supports these directly.  They are
10176   // handled during DAG combining because type legalization will promote them
10177   // to 32-bit types and it is messy to recognize the operations after that.
10178   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10179     SDValue Vec = N0.getOperand(0);
10180     SDValue Lane = N0.getOperand(1);
10181     EVT VT = N->getValueType(0);
10182     EVT EltVT = N0.getValueType();
10183     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10184
10185     if (VT == MVT::i32 &&
10186         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10187         TLI.isTypeLegal(Vec.getValueType()) &&
10188         isa<ConstantSDNode>(Lane)) {
10189
10190       unsigned Opc = 0;
10191       switch (N->getOpcode()) {
10192       default: llvm_unreachable("unexpected opcode");
10193       case ISD::SIGN_EXTEND:
10194         Opc = ARMISD::VGETLANEs;
10195         break;
10196       case ISD::ZERO_EXTEND:
10197       case ISD::ANY_EXTEND:
10198         Opc = ARMISD::VGETLANEu;
10199         break;
10200       }
10201       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10202     }
10203   }
10204
10205   return SDValue();
10206 }
10207
10208 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10209 SDValue
10210 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10211   SDValue Cmp = N->getOperand(4);
10212   if (Cmp.getOpcode() != ARMISD::CMPZ)
10213     // Only looking at EQ and NE cases.
10214     return SDValue();
10215
10216   EVT VT = N->getValueType(0);
10217   SDLoc dl(N);
10218   SDValue LHS = Cmp.getOperand(0);
10219   SDValue RHS = Cmp.getOperand(1);
10220   SDValue FalseVal = N->getOperand(0);
10221   SDValue TrueVal = N->getOperand(1);
10222   SDValue ARMcc = N->getOperand(2);
10223   ARMCC::CondCodes CC =
10224     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10225
10226   // Simplify
10227   //   mov     r1, r0
10228   //   cmp     r1, x
10229   //   mov     r0, y
10230   //   moveq   r0, x
10231   // to
10232   //   cmp     r0, x
10233   //   movne   r0, y
10234   //
10235   //   mov     r1, r0
10236   //   cmp     r1, x
10237   //   mov     r0, x
10238   //   movne   r0, y
10239   // to
10240   //   cmp     r0, x
10241   //   movne   r0, y
10242   /// FIXME: Turn this into a target neutral optimization?
10243   SDValue Res;
10244   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10245     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10246                       N->getOperand(3), Cmp);
10247   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10248     SDValue ARMcc;
10249     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10250     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10251                       N->getOperand(3), NewCmp);
10252   }
10253
10254   if (Res.getNode()) {
10255     APInt KnownZero, KnownOne;
10256     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10257     // Capture demanded bits information that would be otherwise lost.
10258     if (KnownZero == 0xfffffffe)
10259       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10260                         DAG.getValueType(MVT::i1));
10261     else if (KnownZero == 0xffffff00)
10262       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10263                         DAG.getValueType(MVT::i8));
10264     else if (KnownZero == 0xffff0000)
10265       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10266                         DAG.getValueType(MVT::i16));
10267   }
10268
10269   return Res;
10270 }
10271
10272 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10273                                              DAGCombinerInfo &DCI) const {
10274   switch (N->getOpcode()) {
10275   default: break;
10276   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10277   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10278   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10279   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10280   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10281   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10282   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10283   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10284   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10285   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10286   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10287   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10288   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10289   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10290   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10291   case ISD::FP_TO_SINT:
10292   case ISD::FP_TO_UINT:
10293     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
10294   case ISD::FDIV:
10295     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
10296   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10297   case ISD::SHL:
10298   case ISD::SRA:
10299   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10300   case ISD::SIGN_EXTEND:
10301   case ISD::ZERO_EXTEND:
10302   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10303   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10304   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10305   case ARMISD::VLD2DUP:
10306   case ARMISD::VLD3DUP:
10307   case ARMISD::VLD4DUP:
10308     return PerformVLDCombine(N, DCI);
10309   case ARMISD::BUILD_VECTOR:
10310     return PerformARMBUILD_VECTORCombine(N, DCI);
10311   case ISD::INTRINSIC_VOID:
10312   case ISD::INTRINSIC_W_CHAIN:
10313     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10314     case Intrinsic::arm_neon_vld1:
10315     case Intrinsic::arm_neon_vld2:
10316     case Intrinsic::arm_neon_vld3:
10317     case Intrinsic::arm_neon_vld4:
10318     case Intrinsic::arm_neon_vld2lane:
10319     case Intrinsic::arm_neon_vld3lane:
10320     case Intrinsic::arm_neon_vld4lane:
10321     case Intrinsic::arm_neon_vst1:
10322     case Intrinsic::arm_neon_vst2:
10323     case Intrinsic::arm_neon_vst3:
10324     case Intrinsic::arm_neon_vst4:
10325     case Intrinsic::arm_neon_vst2lane:
10326     case Intrinsic::arm_neon_vst3lane:
10327     case Intrinsic::arm_neon_vst4lane:
10328       return PerformVLDCombine(N, DCI);
10329     default: break;
10330     }
10331     break;
10332   }
10333   return SDValue();
10334 }
10335
10336 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10337                                                           EVT VT) const {
10338   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10339 }
10340
10341 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10342                                                        unsigned,
10343                                                        unsigned,
10344                                                        bool *Fast) const {
10345   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10346   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10347
10348   switch (VT.getSimpleVT().SimpleTy) {
10349   default:
10350     return false;
10351   case MVT::i8:
10352   case MVT::i16:
10353   case MVT::i32: {
10354     // Unaligned access can use (for example) LRDB, LRDH, LDR
10355     if (AllowsUnaligned) {
10356       if (Fast)
10357         *Fast = Subtarget->hasV7Ops();
10358       return true;
10359     }
10360     return false;
10361   }
10362   case MVT::f64:
10363   case MVT::v2f64: {
10364     // For any little-endian targets with neon, we can support unaligned ld/st
10365     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10366     // A big-endian target may also explicitly support unaligned accesses
10367     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10368       if (Fast)
10369         *Fast = true;
10370       return true;
10371     }
10372     return false;
10373   }
10374   }
10375 }
10376
10377 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10378                        unsigned AlignCheck) {
10379   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10380           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10381 }
10382
10383 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10384                                            unsigned DstAlign, unsigned SrcAlign,
10385                                            bool IsMemset, bool ZeroMemset,
10386                                            bool MemcpyStrSrc,
10387                                            MachineFunction &MF) const {
10388   const Function *F = MF.getFunction();
10389
10390   // See if we can use NEON instructions for this...
10391   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10392       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10393     bool Fast;
10394     if (Size >= 16 &&
10395         (memOpAlign(SrcAlign, DstAlign, 16) ||
10396          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10397       return MVT::v2f64;
10398     } else if (Size >= 8 &&
10399                (memOpAlign(SrcAlign, DstAlign, 8) ||
10400                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10401                  Fast))) {
10402       return MVT::f64;
10403     }
10404   }
10405
10406   // Lowering to i32/i16 if the size permits.
10407   if (Size >= 4)
10408     return MVT::i32;
10409   else if (Size >= 2)
10410     return MVT::i16;
10411
10412   // Let the target-independent logic figure it out.
10413   return MVT::Other;
10414 }
10415
10416 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10417   if (Val.getOpcode() != ISD::LOAD)
10418     return false;
10419
10420   EVT VT1 = Val.getValueType();
10421   if (!VT1.isSimple() || !VT1.isInteger() ||
10422       !VT2.isSimple() || !VT2.isInteger())
10423     return false;
10424
10425   switch (VT1.getSimpleVT().SimpleTy) {
10426   default: break;
10427   case MVT::i1:
10428   case MVT::i8:
10429   case MVT::i16:
10430     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10431     return true;
10432   }
10433
10434   return false;
10435 }
10436
10437 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10438   EVT VT = ExtVal.getValueType();
10439
10440   if (!isTypeLegal(VT))
10441     return false;
10442
10443   // Don't create a loadext if we can fold the extension into a wide/long
10444   // instruction.
10445   // If there's more than one user instruction, the loadext is desirable no
10446   // matter what.  There can be two uses by the same instruction.
10447   if (ExtVal->use_empty() ||
10448       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10449     return true;
10450
10451   SDNode *U = *ExtVal->use_begin();
10452   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10453        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10454     return false;
10455
10456   return true;
10457 }
10458
10459 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10460   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10461     return false;
10462
10463   if (!isTypeLegal(EVT::getEVT(Ty1)))
10464     return false;
10465
10466   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10467
10468   // Assuming the caller doesn't have a zeroext or signext return parameter,
10469   // truncation all the way down to i1 is valid.
10470   return true;
10471 }
10472
10473
10474 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10475   if (V < 0)
10476     return false;
10477
10478   unsigned Scale = 1;
10479   switch (VT.getSimpleVT().SimpleTy) {
10480   default: return false;
10481   case MVT::i1:
10482   case MVT::i8:
10483     // Scale == 1;
10484     break;
10485   case MVT::i16:
10486     // Scale == 2;
10487     Scale = 2;
10488     break;
10489   case MVT::i32:
10490     // Scale == 4;
10491     Scale = 4;
10492     break;
10493   }
10494
10495   if ((V & (Scale - 1)) != 0)
10496     return false;
10497   V /= Scale;
10498   return V == (V & ((1LL << 5) - 1));
10499 }
10500
10501 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10502                                       const ARMSubtarget *Subtarget) {
10503   bool isNeg = false;
10504   if (V < 0) {
10505     isNeg = true;
10506     V = - V;
10507   }
10508
10509   switch (VT.getSimpleVT().SimpleTy) {
10510   default: return false;
10511   case MVT::i1:
10512   case MVT::i8:
10513   case MVT::i16:
10514   case MVT::i32:
10515     // + imm12 or - imm8
10516     if (isNeg)
10517       return V == (V & ((1LL << 8) - 1));
10518     return V == (V & ((1LL << 12) - 1));
10519   case MVT::f32:
10520   case MVT::f64:
10521     // Same as ARM mode. FIXME: NEON?
10522     if (!Subtarget->hasVFP2())
10523       return false;
10524     if ((V & 3) != 0)
10525       return false;
10526     V >>= 2;
10527     return V == (V & ((1LL << 8) - 1));
10528   }
10529 }
10530
10531 /// isLegalAddressImmediate - Return true if the integer value can be used
10532 /// as the offset of the target addressing mode for load / store of the
10533 /// given type.
10534 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10535                                     const ARMSubtarget *Subtarget) {
10536   if (V == 0)
10537     return true;
10538
10539   if (!VT.isSimple())
10540     return false;
10541
10542   if (Subtarget->isThumb1Only())
10543     return isLegalT1AddressImmediate(V, VT);
10544   else if (Subtarget->isThumb2())
10545     return isLegalT2AddressImmediate(V, VT, Subtarget);
10546
10547   // ARM mode.
10548   if (V < 0)
10549     V = - V;
10550   switch (VT.getSimpleVT().SimpleTy) {
10551   default: return false;
10552   case MVT::i1:
10553   case MVT::i8:
10554   case MVT::i32:
10555     // +- imm12
10556     return V == (V & ((1LL << 12) - 1));
10557   case MVT::i16:
10558     // +- imm8
10559     return V == (V & ((1LL << 8) - 1));
10560   case MVT::f32:
10561   case MVT::f64:
10562     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10563       return false;
10564     if ((V & 3) != 0)
10565       return false;
10566     V >>= 2;
10567     return V == (V & ((1LL << 8) - 1));
10568   }
10569 }
10570
10571 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10572                                                       EVT VT) const {
10573   int Scale = AM.Scale;
10574   if (Scale < 0)
10575     return false;
10576
10577   switch (VT.getSimpleVT().SimpleTy) {
10578   default: return false;
10579   case MVT::i1:
10580   case MVT::i8:
10581   case MVT::i16:
10582   case MVT::i32:
10583     if (Scale == 1)
10584       return true;
10585     // r + r << imm
10586     Scale = Scale & ~1;
10587     return Scale == 2 || Scale == 4 || Scale == 8;
10588   case MVT::i64:
10589     // r + r
10590     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10591       return true;
10592     return false;
10593   case MVT::isVoid:
10594     // Note, we allow "void" uses (basically, uses that aren't loads or
10595     // stores), because arm allows folding a scale into many arithmetic
10596     // operations.  This should be made more precise and revisited later.
10597
10598     // Allow r << imm, but the imm has to be a multiple of two.
10599     if (Scale & 1) return false;
10600     return isPowerOf2_32(Scale);
10601   }
10602 }
10603
10604 /// isLegalAddressingMode - Return true if the addressing mode represented
10605 /// by AM is legal for this target, for a load/store of the specified type.
10606 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10607                                               const AddrMode &AM, Type *Ty,
10608                                               unsigned AS) const {
10609   EVT VT = getValueType(DL, Ty, true);
10610   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10611     return false;
10612
10613   // Can never fold addr of global into load/store.
10614   if (AM.BaseGV)
10615     return false;
10616
10617   switch (AM.Scale) {
10618   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10619     break;
10620   case 1:
10621     if (Subtarget->isThumb1Only())
10622       return false;
10623     // FALL THROUGH.
10624   default:
10625     // ARM doesn't support any R+R*scale+imm addr modes.
10626     if (AM.BaseOffs)
10627       return false;
10628
10629     if (!VT.isSimple())
10630       return false;
10631
10632     if (Subtarget->isThumb2())
10633       return isLegalT2ScaledAddressingMode(AM, VT);
10634
10635     int Scale = AM.Scale;
10636     switch (VT.getSimpleVT().SimpleTy) {
10637     default: return false;
10638     case MVT::i1:
10639     case MVT::i8:
10640     case MVT::i32:
10641       if (Scale < 0) Scale = -Scale;
10642       if (Scale == 1)
10643         return true;
10644       // r + r << imm
10645       return isPowerOf2_32(Scale & ~1);
10646     case MVT::i16:
10647     case MVT::i64:
10648       // r + r
10649       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10650         return true;
10651       return false;
10652
10653     case MVT::isVoid:
10654       // Note, we allow "void" uses (basically, uses that aren't loads or
10655       // stores), because arm allows folding a scale into many arithmetic
10656       // operations.  This should be made more precise and revisited later.
10657
10658       // Allow r << imm, but the imm has to be a multiple of two.
10659       if (Scale & 1) return false;
10660       return isPowerOf2_32(Scale);
10661     }
10662   }
10663   return true;
10664 }
10665
10666 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10667 /// icmp immediate, that is the target has icmp instructions which can compare
10668 /// a register against the immediate without having to materialize the
10669 /// immediate into a register.
10670 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10671   // Thumb2 and ARM modes can use cmn for negative immediates.
10672   if (!Subtarget->isThumb())
10673     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10674   if (Subtarget->isThumb2())
10675     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10676   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10677   return Imm >= 0 && Imm <= 255;
10678 }
10679
10680 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10681 /// *or sub* immediate, that is the target has add or sub instructions which can
10682 /// add a register with the immediate without having to materialize the
10683 /// immediate into a register.
10684 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10685   // Same encoding for add/sub, just flip the sign.
10686   int64_t AbsImm = std::abs(Imm);
10687   if (!Subtarget->isThumb())
10688     return ARM_AM::getSOImmVal(AbsImm) != -1;
10689   if (Subtarget->isThumb2())
10690     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10691   // Thumb1 only has 8-bit unsigned immediate.
10692   return AbsImm >= 0 && AbsImm <= 255;
10693 }
10694
10695 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10696                                       bool isSEXTLoad, SDValue &Base,
10697                                       SDValue &Offset, bool &isInc,
10698                                       SelectionDAG &DAG) {
10699   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10700     return false;
10701
10702   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10703     // AddressingMode 3
10704     Base = Ptr->getOperand(0);
10705     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10706       int RHSC = (int)RHS->getZExtValue();
10707       if (RHSC < 0 && RHSC > -256) {
10708         assert(Ptr->getOpcode() == ISD::ADD);
10709         isInc = false;
10710         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10711         return true;
10712       }
10713     }
10714     isInc = (Ptr->getOpcode() == ISD::ADD);
10715     Offset = Ptr->getOperand(1);
10716     return true;
10717   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10718     // AddressingMode 2
10719     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10720       int RHSC = (int)RHS->getZExtValue();
10721       if (RHSC < 0 && RHSC > -0x1000) {
10722         assert(Ptr->getOpcode() == ISD::ADD);
10723         isInc = false;
10724         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10725         Base = Ptr->getOperand(0);
10726         return true;
10727       }
10728     }
10729
10730     if (Ptr->getOpcode() == ISD::ADD) {
10731       isInc = true;
10732       ARM_AM::ShiftOpc ShOpcVal=
10733         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10734       if (ShOpcVal != ARM_AM::no_shift) {
10735         Base = Ptr->getOperand(1);
10736         Offset = Ptr->getOperand(0);
10737       } else {
10738         Base = Ptr->getOperand(0);
10739         Offset = Ptr->getOperand(1);
10740       }
10741       return true;
10742     }
10743
10744     isInc = (Ptr->getOpcode() == ISD::ADD);
10745     Base = Ptr->getOperand(0);
10746     Offset = Ptr->getOperand(1);
10747     return true;
10748   }
10749
10750   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10751   return false;
10752 }
10753
10754 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10755                                      bool isSEXTLoad, SDValue &Base,
10756                                      SDValue &Offset, bool &isInc,
10757                                      SelectionDAG &DAG) {
10758   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10759     return false;
10760
10761   Base = Ptr->getOperand(0);
10762   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10763     int RHSC = (int)RHS->getZExtValue();
10764     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10765       assert(Ptr->getOpcode() == ISD::ADD);
10766       isInc = false;
10767       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10768       return true;
10769     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10770       isInc = Ptr->getOpcode() == ISD::ADD;
10771       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10772       return true;
10773     }
10774   }
10775
10776   return false;
10777 }
10778
10779 /// getPreIndexedAddressParts - returns true by value, base pointer and
10780 /// offset pointer and addressing mode by reference if the node's address
10781 /// can be legally represented as pre-indexed load / store address.
10782 bool
10783 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10784                                              SDValue &Offset,
10785                                              ISD::MemIndexedMode &AM,
10786                                              SelectionDAG &DAG) const {
10787   if (Subtarget->isThumb1Only())
10788     return false;
10789
10790   EVT VT;
10791   SDValue Ptr;
10792   bool isSEXTLoad = false;
10793   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10794     Ptr = LD->getBasePtr();
10795     VT  = LD->getMemoryVT();
10796     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10797   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10798     Ptr = ST->getBasePtr();
10799     VT  = ST->getMemoryVT();
10800   } else
10801     return false;
10802
10803   bool isInc;
10804   bool isLegal = false;
10805   if (Subtarget->isThumb2())
10806     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10807                                        Offset, isInc, DAG);
10808   else
10809     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10810                                         Offset, isInc, DAG);
10811   if (!isLegal)
10812     return false;
10813
10814   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10815   return true;
10816 }
10817
10818 /// getPostIndexedAddressParts - returns true by value, base pointer and
10819 /// offset pointer and addressing mode by reference if this node can be
10820 /// combined with a load / store to form a post-indexed load / store.
10821 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10822                                                    SDValue &Base,
10823                                                    SDValue &Offset,
10824                                                    ISD::MemIndexedMode &AM,
10825                                                    SelectionDAG &DAG) const {
10826   if (Subtarget->isThumb1Only())
10827     return false;
10828
10829   EVT VT;
10830   SDValue Ptr;
10831   bool isSEXTLoad = false;
10832   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10833     VT  = LD->getMemoryVT();
10834     Ptr = LD->getBasePtr();
10835     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10836   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10837     VT  = ST->getMemoryVT();
10838     Ptr = ST->getBasePtr();
10839   } else
10840     return false;
10841
10842   bool isInc;
10843   bool isLegal = false;
10844   if (Subtarget->isThumb2())
10845     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10846                                        isInc, DAG);
10847   else
10848     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10849                                         isInc, DAG);
10850   if (!isLegal)
10851     return false;
10852
10853   if (Ptr != Base) {
10854     // Swap base ptr and offset to catch more post-index load / store when
10855     // it's legal. In Thumb2 mode, offset must be an immediate.
10856     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10857         !Subtarget->isThumb2())
10858       std::swap(Base, Offset);
10859
10860     // Post-indexed load / store update the base pointer.
10861     if (Ptr != Base)
10862       return false;
10863   }
10864
10865   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10866   return true;
10867 }
10868
10869 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10870                                                       APInt &KnownZero,
10871                                                       APInt &KnownOne,
10872                                                       const SelectionDAG &DAG,
10873                                                       unsigned Depth) const {
10874   unsigned BitWidth = KnownOne.getBitWidth();
10875   KnownZero = KnownOne = APInt(BitWidth, 0);
10876   switch (Op.getOpcode()) {
10877   default: break;
10878   case ARMISD::ADDC:
10879   case ARMISD::ADDE:
10880   case ARMISD::SUBC:
10881   case ARMISD::SUBE:
10882     // These nodes' second result is a boolean
10883     if (Op.getResNo() == 0)
10884       break;
10885     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10886     break;
10887   case ARMISD::CMOV: {
10888     // Bits are known zero/one if known on the LHS and RHS.
10889     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10890     if (KnownZero == 0 && KnownOne == 0) return;
10891
10892     APInt KnownZeroRHS, KnownOneRHS;
10893     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10894     KnownZero &= KnownZeroRHS;
10895     KnownOne  &= KnownOneRHS;
10896     return;
10897   }
10898   case ISD::INTRINSIC_W_CHAIN: {
10899     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10900     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10901     switch (IntID) {
10902     default: return;
10903     case Intrinsic::arm_ldaex:
10904     case Intrinsic::arm_ldrex: {
10905       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10906       unsigned MemBits = VT.getScalarType().getSizeInBits();
10907       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10908       return;
10909     }
10910     }
10911   }
10912   }
10913 }
10914
10915 //===----------------------------------------------------------------------===//
10916 //                           ARM Inline Assembly Support
10917 //===----------------------------------------------------------------------===//
10918
10919 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10920   // Looking for "rev" which is V6+.
10921   if (!Subtarget->hasV6Ops())
10922     return false;
10923
10924   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10925   std::string AsmStr = IA->getAsmString();
10926   SmallVector<StringRef, 4> AsmPieces;
10927   SplitString(AsmStr, AsmPieces, ";\n");
10928
10929   switch (AsmPieces.size()) {
10930   default: return false;
10931   case 1:
10932     AsmStr = AsmPieces[0];
10933     AsmPieces.clear();
10934     SplitString(AsmStr, AsmPieces, " \t,");
10935
10936     // rev $0, $1
10937     if (AsmPieces.size() == 3 &&
10938         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10939         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10940       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10941       if (Ty && Ty->getBitWidth() == 32)
10942         return IntrinsicLowering::LowerToByteSwap(CI);
10943     }
10944     break;
10945   }
10946
10947   return false;
10948 }
10949
10950 /// getConstraintType - Given a constraint letter, return the type of
10951 /// constraint it is for this target.
10952 ARMTargetLowering::ConstraintType
10953 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10954   if (Constraint.size() == 1) {
10955     switch (Constraint[0]) {
10956     default:  break;
10957     case 'l': return C_RegisterClass;
10958     case 'w': return C_RegisterClass;
10959     case 'h': return C_RegisterClass;
10960     case 'x': return C_RegisterClass;
10961     case 't': return C_RegisterClass;
10962     case 'j': return C_Other; // Constant for movw.
10963       // An address with a single base register. Due to the way we
10964       // currently handle addresses it is the same as an 'r' memory constraint.
10965     case 'Q': return C_Memory;
10966     }
10967   } else if (Constraint.size() == 2) {
10968     switch (Constraint[0]) {
10969     default: break;
10970     // All 'U+' constraints are addresses.
10971     case 'U': return C_Memory;
10972     }
10973   }
10974   return TargetLowering::getConstraintType(Constraint);
10975 }
10976
10977 /// Examine constraint type and operand type and determine a weight value.
10978 /// This object must already have been set up with the operand type
10979 /// and the current alternative constraint selected.
10980 TargetLowering::ConstraintWeight
10981 ARMTargetLowering::getSingleConstraintMatchWeight(
10982     AsmOperandInfo &info, const char *constraint) const {
10983   ConstraintWeight weight = CW_Invalid;
10984   Value *CallOperandVal = info.CallOperandVal;
10985     // If we don't have a value, we can't do a match,
10986     // but allow it at the lowest weight.
10987   if (!CallOperandVal)
10988     return CW_Default;
10989   Type *type = CallOperandVal->getType();
10990   // Look at the constraint type.
10991   switch (*constraint) {
10992   default:
10993     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10994     break;
10995   case 'l':
10996     if (type->isIntegerTy()) {
10997       if (Subtarget->isThumb())
10998         weight = CW_SpecificReg;
10999       else
11000         weight = CW_Register;
11001     }
11002     break;
11003   case 'w':
11004     if (type->isFloatingPointTy())
11005       weight = CW_Register;
11006     break;
11007   }
11008   return weight;
11009 }
11010
11011 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11012 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11013     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11014   if (Constraint.size() == 1) {
11015     // GCC ARM Constraint Letters
11016     switch (Constraint[0]) {
11017     case 'l': // Low regs or general regs.
11018       if (Subtarget->isThumb())
11019         return RCPair(0U, &ARM::tGPRRegClass);
11020       return RCPair(0U, &ARM::GPRRegClass);
11021     case 'h': // High regs or no regs.
11022       if (Subtarget->isThumb())
11023         return RCPair(0U, &ARM::hGPRRegClass);
11024       break;
11025     case 'r':
11026       if (Subtarget->isThumb1Only())
11027         return RCPair(0U, &ARM::tGPRRegClass);
11028       return RCPair(0U, &ARM::GPRRegClass);
11029     case 'w':
11030       if (VT == MVT::Other)
11031         break;
11032       if (VT == MVT::f32)
11033         return RCPair(0U, &ARM::SPRRegClass);
11034       if (VT.getSizeInBits() == 64)
11035         return RCPair(0U, &ARM::DPRRegClass);
11036       if (VT.getSizeInBits() == 128)
11037         return RCPair(0U, &ARM::QPRRegClass);
11038       break;
11039     case 'x':
11040       if (VT == MVT::Other)
11041         break;
11042       if (VT == MVT::f32)
11043         return RCPair(0U, &ARM::SPR_8RegClass);
11044       if (VT.getSizeInBits() == 64)
11045         return RCPair(0U, &ARM::DPR_8RegClass);
11046       if (VT.getSizeInBits() == 128)
11047         return RCPair(0U, &ARM::QPR_8RegClass);
11048       break;
11049     case 't':
11050       if (VT == MVT::f32)
11051         return RCPair(0U, &ARM::SPRRegClass);
11052       break;
11053     }
11054   }
11055   if (StringRef("{cc}").equals_lower(Constraint))
11056     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11057
11058   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11059 }
11060
11061 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11062 /// vector.  If it is invalid, don't add anything to Ops.
11063 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11064                                                      std::string &Constraint,
11065                                                      std::vector<SDValue>&Ops,
11066                                                      SelectionDAG &DAG) const {
11067   SDValue Result;
11068
11069   // Currently only support length 1 constraints.
11070   if (Constraint.length() != 1) return;
11071
11072   char ConstraintLetter = Constraint[0];
11073   switch (ConstraintLetter) {
11074   default: break;
11075   case 'j':
11076   case 'I': case 'J': case 'K': case 'L':
11077   case 'M': case 'N': case 'O':
11078     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11079     if (!C)
11080       return;
11081
11082     int64_t CVal64 = C->getSExtValue();
11083     int CVal = (int) CVal64;
11084     // None of these constraints allow values larger than 32 bits.  Check
11085     // that the value fits in an int.
11086     if (CVal != CVal64)
11087       return;
11088
11089     switch (ConstraintLetter) {
11090       case 'j':
11091         // Constant suitable for movw, must be between 0 and
11092         // 65535.
11093         if (Subtarget->hasV6T2Ops())
11094           if (CVal >= 0 && CVal <= 65535)
11095             break;
11096         return;
11097       case 'I':
11098         if (Subtarget->isThumb1Only()) {
11099           // This must be a constant between 0 and 255, for ADD
11100           // immediates.
11101           if (CVal >= 0 && CVal <= 255)
11102             break;
11103         } else if (Subtarget->isThumb2()) {
11104           // A constant that can be used as an immediate value in a
11105           // data-processing instruction.
11106           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11107             break;
11108         } else {
11109           // A constant that can be used as an immediate value in a
11110           // data-processing instruction.
11111           if (ARM_AM::getSOImmVal(CVal) != -1)
11112             break;
11113         }
11114         return;
11115
11116       case 'J':
11117         if (Subtarget->isThumb()) {  // FIXME thumb2
11118           // This must be a constant between -255 and -1, for negated ADD
11119           // immediates. This can be used in GCC with an "n" modifier that
11120           // prints the negated value, for use with SUB instructions. It is
11121           // not useful otherwise but is implemented for compatibility.
11122           if (CVal >= -255 && CVal <= -1)
11123             break;
11124         } else {
11125           // This must be a constant between -4095 and 4095. It is not clear
11126           // what this constraint is intended for. Implemented for
11127           // compatibility with GCC.
11128           if (CVal >= -4095 && CVal <= 4095)
11129             break;
11130         }
11131         return;
11132
11133       case 'K':
11134         if (Subtarget->isThumb1Only()) {
11135           // A 32-bit value where only one byte has a nonzero value. Exclude
11136           // zero to match GCC. This constraint is used by GCC internally for
11137           // constants that can be loaded with a move/shift combination.
11138           // It is not useful otherwise but is implemented for compatibility.
11139           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11140             break;
11141         } else if (Subtarget->isThumb2()) {
11142           // A constant whose bitwise inverse can be used as an immediate
11143           // value in a data-processing instruction. This can be used in GCC
11144           // with a "B" modifier that prints the inverted value, for use with
11145           // BIC and MVN instructions. It is not useful otherwise but is
11146           // implemented for compatibility.
11147           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11148             break;
11149         } else {
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::getSOImmVal(~CVal) != -1)
11156             break;
11157         }
11158         return;
11159
11160       case 'L':
11161         if (Subtarget->isThumb1Only()) {
11162           // This must be a constant between -7 and 7,
11163           // for 3-operand ADD/SUB immediate instructions.
11164           if (CVal >= -7 && CVal < 7)
11165             break;
11166         } else if (Subtarget->isThumb2()) {
11167           // A constant whose negation can be used as an immediate value in a
11168           // data-processing instruction. This can be used in GCC with an "n"
11169           // modifier that prints the negated value, for use with SUB
11170           // instructions. It is not useful otherwise but is implemented for
11171           // compatibility.
11172           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11173             break;
11174         } else {
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::getSOImmVal(-CVal) != -1)
11181             break;
11182         }
11183         return;
11184
11185       case 'M':
11186         if (Subtarget->isThumb()) { // FIXME thumb2
11187           // This must be a multiple of 4 between 0 and 1020, for
11188           // ADD sp + immediate.
11189           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11190             break;
11191         } else {
11192           // A power of two or a constant between 0 and 32.  This is used in
11193           // GCC for the shift amount on shifted register operands, but it is
11194           // useful in general for any shift amounts.
11195           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11196             break;
11197         }
11198         return;
11199
11200       case 'N':
11201         if (Subtarget->isThumb()) {  // FIXME thumb2
11202           // This must be a constant between 0 and 31, for shift amounts.
11203           if (CVal >= 0 && CVal <= 31)
11204             break;
11205         }
11206         return;
11207
11208       case 'O':
11209         if (Subtarget->isThumb()) {  // FIXME thumb2
11210           // This must be a multiple of 4 between -508 and 508, for
11211           // ADD/SUB sp = sp + immediate.
11212           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11213             break;
11214         }
11215         return;
11216     }
11217     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11218     break;
11219   }
11220
11221   if (Result.getNode()) {
11222     Ops.push_back(Result);
11223     return;
11224   }
11225   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11226 }
11227
11228 static RTLIB::Libcall getDivRemLibcall(
11229     const SDNode *N, MVT::SimpleValueType SVT) {
11230   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11231           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11232          "Unhandled Opcode in getDivRemLibcall");
11233   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11234                   N->getOpcode() == ISD::SREM;
11235   RTLIB::Libcall LC;
11236   switch (SVT) {
11237   default: llvm_unreachable("Unexpected request for libcall!");
11238   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11239   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11240   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11241   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11242   }
11243   return LC;
11244 }
11245
11246 static TargetLowering::ArgListTy getDivRemArgList(
11247     const SDNode *N, LLVMContext *Context) {
11248   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11249           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11250          "Unhandled Opcode in getDivRemArgList");
11251   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11252                   N->getOpcode() == ISD::SREM;
11253   TargetLowering::ArgListTy Args;
11254   TargetLowering::ArgListEntry Entry;
11255   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11256     EVT ArgVT = N->getOperand(i).getValueType();
11257     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11258     Entry.Node = N->getOperand(i);
11259     Entry.Ty = ArgTy;
11260     Entry.isSExt = isSigned;
11261     Entry.isZExt = !isSigned;
11262     Args.push_back(Entry);
11263   }
11264   return Args;
11265 }
11266
11267 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11268   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11269          "Register-based DivRem lowering only");
11270   unsigned Opcode = Op->getOpcode();
11271   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11272          "Invalid opcode for Div/Rem lowering");
11273   bool isSigned = (Opcode == ISD::SDIVREM);
11274   EVT VT = Op->getValueType(0);
11275   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11276
11277   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11278                                        VT.getSimpleVT().SimpleTy);
11279   SDValue InChain = DAG.getEntryNode();
11280
11281   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11282                                                     DAG.getContext());
11283
11284   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11285                                          getPointerTy(DAG.getDataLayout()));
11286
11287   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11288
11289   SDLoc dl(Op);
11290   TargetLowering::CallLoweringInfo CLI(DAG);
11291   CLI.setDebugLoc(dl).setChain(InChain)
11292     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11293     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11294
11295   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11296   return CallInfo.first;
11297 }
11298
11299 // Lowers REM using divmod helpers
11300 // see RTABI section 4.2/4.3
11301 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11302   // Build return types (div and rem)
11303   std::vector<Type*> RetTyParams;
11304   Type *RetTyElement;
11305
11306   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11307   default: llvm_unreachable("Unexpected request for libcall!");
11308   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
11309   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11310   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11311   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11312   }
11313
11314   RetTyParams.push_back(RetTyElement);
11315   RetTyParams.push_back(RetTyElement);
11316   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11317   Type *RetTy = StructType::get(*DAG.getContext(), ret);
11318
11319   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11320                                                              SimpleTy);
11321   SDValue InChain = DAG.getEntryNode();
11322   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11323   bool isSigned = N->getOpcode() == ISD::SREM;
11324   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11325                                          getPointerTy(DAG.getDataLayout()));
11326
11327   // Lower call
11328   CallLoweringInfo CLI(DAG);
11329   CLI.setChain(InChain)
11330      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11331      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11332   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11333
11334   // Return second (rem) result operand (first contains div)
11335   SDNode *ResNode = CallResult.first.getNode();
11336   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11337   return ResNode->getOperand(1);
11338 }
11339
11340 SDValue
11341 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11342   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11343   SDLoc DL(Op);
11344
11345   // Get the inputs.
11346   SDValue Chain = Op.getOperand(0);
11347   SDValue Size  = Op.getOperand(1);
11348
11349   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11350                               DAG.getConstant(2, DL, MVT::i32));
11351
11352   SDValue Flag;
11353   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11354   Flag = Chain.getValue(1);
11355
11356   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11357   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11358
11359   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11360   Chain = NewSP.getValue(1);
11361
11362   SDValue Ops[2] = { NewSP, Chain };
11363   return DAG.getMergeValues(Ops, DL);
11364 }
11365
11366 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11367   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11368          "Unexpected type for custom-lowering FP_EXTEND");
11369
11370   RTLIB::Libcall LC;
11371   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11372
11373   SDValue SrcVal = Op.getOperand(0);
11374   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11375                      SDLoc(Op)).first;
11376 }
11377
11378 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11379   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11380          Subtarget->isFPOnlySP() &&
11381          "Unexpected type for custom-lowering FP_ROUND");
11382
11383   RTLIB::Libcall LC;
11384   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11385
11386   SDValue SrcVal = Op.getOperand(0);
11387   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11388                      SDLoc(Op)).first;
11389 }
11390
11391 bool
11392 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11393   // The ARM target isn't yet aware of offsets.
11394   return false;
11395 }
11396
11397 bool ARM::isBitFieldInvertedMask(unsigned v) {
11398   if (v == 0xffffffff)
11399     return false;
11400
11401   // there can be 1's on either or both "outsides", all the "inside"
11402   // bits must be 0's
11403   return isShiftedMask_32(~v);
11404 }
11405
11406 /// isFPImmLegal - Returns true if the target can instruction select the
11407 /// specified FP immediate natively. If false, the legalizer will
11408 /// materialize the FP immediate as a load from a constant pool.
11409 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11410   if (!Subtarget->hasVFP3())
11411     return false;
11412   if (VT == MVT::f32)
11413     return ARM_AM::getFP32Imm(Imm) != -1;
11414   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11415     return ARM_AM::getFP64Imm(Imm) != -1;
11416   return false;
11417 }
11418
11419 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11420 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11421 /// specified in the intrinsic calls.
11422 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11423                                            const CallInst &I,
11424                                            unsigned Intrinsic) const {
11425   switch (Intrinsic) {
11426   case Intrinsic::arm_neon_vld1:
11427   case Intrinsic::arm_neon_vld2:
11428   case Intrinsic::arm_neon_vld3:
11429   case Intrinsic::arm_neon_vld4:
11430   case Intrinsic::arm_neon_vld2lane:
11431   case Intrinsic::arm_neon_vld3lane:
11432   case Intrinsic::arm_neon_vld4lane: {
11433     Info.opc = ISD::INTRINSIC_W_CHAIN;
11434     // Conservatively set memVT to the entire set of vectors loaded.
11435     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11436     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11437     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11438     Info.ptrVal = I.getArgOperand(0);
11439     Info.offset = 0;
11440     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11441     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11442     Info.vol = false; // volatile loads with NEON intrinsics not supported
11443     Info.readMem = true;
11444     Info.writeMem = false;
11445     return true;
11446   }
11447   case Intrinsic::arm_neon_vst1:
11448   case Intrinsic::arm_neon_vst2:
11449   case Intrinsic::arm_neon_vst3:
11450   case Intrinsic::arm_neon_vst4:
11451   case Intrinsic::arm_neon_vst2lane:
11452   case Intrinsic::arm_neon_vst3lane:
11453   case Intrinsic::arm_neon_vst4lane: {
11454     Info.opc = ISD::INTRINSIC_VOID;
11455     // Conservatively set memVT to the entire set of vectors stored.
11456     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11457     unsigned NumElts = 0;
11458     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11459       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11460       if (!ArgTy->isVectorTy())
11461         break;
11462       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11463     }
11464     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11465     Info.ptrVal = I.getArgOperand(0);
11466     Info.offset = 0;
11467     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11468     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11469     Info.vol = false; // volatile stores with NEON intrinsics not supported
11470     Info.readMem = false;
11471     Info.writeMem = true;
11472     return true;
11473   }
11474   case Intrinsic::arm_ldaex:
11475   case Intrinsic::arm_ldrex: {
11476     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11477     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11478     Info.opc = ISD::INTRINSIC_W_CHAIN;
11479     Info.memVT = MVT::getVT(PtrTy->getElementType());
11480     Info.ptrVal = I.getArgOperand(0);
11481     Info.offset = 0;
11482     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11483     Info.vol = true;
11484     Info.readMem = true;
11485     Info.writeMem = false;
11486     return true;
11487   }
11488   case Intrinsic::arm_stlex:
11489   case Intrinsic::arm_strex: {
11490     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11491     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11492     Info.opc = ISD::INTRINSIC_W_CHAIN;
11493     Info.memVT = MVT::getVT(PtrTy->getElementType());
11494     Info.ptrVal = I.getArgOperand(1);
11495     Info.offset = 0;
11496     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11497     Info.vol = true;
11498     Info.readMem = false;
11499     Info.writeMem = true;
11500     return true;
11501   }
11502   case Intrinsic::arm_stlexd:
11503   case Intrinsic::arm_strexd: {
11504     Info.opc = ISD::INTRINSIC_W_CHAIN;
11505     Info.memVT = MVT::i64;
11506     Info.ptrVal = I.getArgOperand(2);
11507     Info.offset = 0;
11508     Info.align = 8;
11509     Info.vol = true;
11510     Info.readMem = false;
11511     Info.writeMem = true;
11512     return true;
11513   }
11514   case Intrinsic::arm_ldaexd:
11515   case Intrinsic::arm_ldrexd: {
11516     Info.opc = ISD::INTRINSIC_W_CHAIN;
11517     Info.memVT = MVT::i64;
11518     Info.ptrVal = I.getArgOperand(0);
11519     Info.offset = 0;
11520     Info.align = 8;
11521     Info.vol = true;
11522     Info.readMem = true;
11523     Info.writeMem = false;
11524     return true;
11525   }
11526   default:
11527     break;
11528   }
11529
11530   return false;
11531 }
11532
11533 /// \brief Returns true if it is beneficial to convert a load of a constant
11534 /// to just the constant itself.
11535 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11536                                                           Type *Ty) const {
11537   assert(Ty->isIntegerTy());
11538
11539   unsigned Bits = Ty->getPrimitiveSizeInBits();
11540   if (Bits == 0 || Bits > 32)
11541     return false;
11542   return true;
11543 }
11544
11545 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11546                                         ARM_MB::MemBOpt Domain) const {
11547   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11548
11549   // First, if the target has no DMB, see what fallback we can use.
11550   if (!Subtarget->hasDataBarrier()) {
11551     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11552     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11553     // here.
11554     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11555       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11556       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11557                         Builder.getInt32(0), Builder.getInt32(7),
11558                         Builder.getInt32(10), Builder.getInt32(5)};
11559       return Builder.CreateCall(MCR, args);
11560     } else {
11561       // Instead of using barriers, atomic accesses on these subtargets use
11562       // libcalls.
11563       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11564     }
11565   } else {
11566     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11567     // Only a full system barrier exists in the M-class architectures.
11568     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11569     Constant *CDomain = Builder.getInt32(Domain);
11570     return Builder.CreateCall(DMB, CDomain);
11571   }
11572 }
11573
11574 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11575 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11576                                          AtomicOrdering Ord, bool IsStore,
11577                                          bool IsLoad) const {
11578   if (!getInsertFencesForAtomic())
11579     return nullptr;
11580
11581   switch (Ord) {
11582   case NotAtomic:
11583   case Unordered:
11584     llvm_unreachable("Invalid fence: unordered/non-atomic");
11585   case Monotonic:
11586   case Acquire:
11587     return nullptr; // Nothing to do
11588   case SequentiallyConsistent:
11589     if (!IsStore)
11590       return nullptr; // Nothing to do
11591     /*FALLTHROUGH*/
11592   case Release:
11593   case AcquireRelease:
11594     if (Subtarget->isSwift())
11595       return makeDMB(Builder, ARM_MB::ISHST);
11596     // FIXME: add a comment with a link to documentation justifying this.
11597     else
11598       return makeDMB(Builder, ARM_MB::ISH);
11599   }
11600   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11601 }
11602
11603 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11604                                           AtomicOrdering Ord, bool IsStore,
11605                                           bool IsLoad) const {
11606   if (!getInsertFencesForAtomic())
11607     return nullptr;
11608
11609   switch (Ord) {
11610   case NotAtomic:
11611   case Unordered:
11612     llvm_unreachable("Invalid fence: unordered/not-atomic");
11613   case Monotonic:
11614   case Release:
11615     return nullptr; // Nothing to do
11616   case Acquire:
11617   case AcquireRelease:
11618   case SequentiallyConsistent:
11619     return makeDMB(Builder, ARM_MB::ISH);
11620   }
11621   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11622 }
11623
11624 // Loads and stores less than 64-bits are already atomic; ones above that
11625 // are doomed anyway, so defer to the default libcall and blame the OS when
11626 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11627 // anything for those.
11628 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11629   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11630   return (Size == 64) && !Subtarget->isMClass();
11631 }
11632
11633 // Loads and stores less than 64-bits are already atomic; ones above that
11634 // are doomed anyway, so defer to the default libcall and blame the OS when
11635 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11636 // anything for those.
11637 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11638 // guarantee, see DDI0406C ARM architecture reference manual,
11639 // sections A8.8.72-74 LDRD)
11640 TargetLowering::AtomicExpansionKind
11641 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11642   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11643   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLSC
11644                                                   : AtomicExpansionKind::None;
11645 }
11646
11647 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11648 // and up to 64 bits on the non-M profiles
11649 TargetLowering::AtomicExpansionKind
11650 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11651   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11652   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11653              ? AtomicExpansionKind::LLSC
11654              : AtomicExpansionKind::None;
11655 }
11656
11657 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
11658     AtomicCmpXchgInst *AI) const {
11659   return true;
11660 }
11661
11662 // This has so far only been implemented for MachO.
11663 bool ARMTargetLowering::useLoadStackGuardNode() const {
11664   return Subtarget->isTargetMachO();
11665 }
11666
11667 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11668                                                   unsigned &Cost) const {
11669   // If we do not have NEON, vector types are not natively supported.
11670   if (!Subtarget->hasNEON())
11671     return false;
11672
11673   // Floating point values and vector values map to the same register file.
11674   // Therefore, although we could do a store extract of a vector type, this is
11675   // better to leave at float as we have more freedom in the addressing mode for
11676   // those.
11677   if (VectorTy->isFPOrFPVectorTy())
11678     return false;
11679
11680   // If the index is unknown at compile time, this is very expensive to lower
11681   // and it is not possible to combine the store with the extract.
11682   if (!isa<ConstantInt>(Idx))
11683     return false;
11684
11685   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11686   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11687   // We can do a store + vector extract on any vector that fits perfectly in a D
11688   // or Q register.
11689   if (BitWidth == 64 || BitWidth == 128) {
11690     Cost = 0;
11691     return true;
11692   }
11693   return false;
11694 }
11695
11696 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11697                                          AtomicOrdering Ord) const {
11698   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11699   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11700   bool IsAcquire = isAtLeastAcquire(Ord);
11701
11702   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11703   // intrinsic must return {i32, i32} and we have to recombine them into a
11704   // single i64 here.
11705   if (ValTy->getPrimitiveSizeInBits() == 64) {
11706     Intrinsic::ID Int =
11707         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11708     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11709
11710     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11711     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11712
11713     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11714     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11715     if (!Subtarget->isLittle())
11716       std::swap (Lo, Hi);
11717     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11718     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11719     return Builder.CreateOr(
11720         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11721   }
11722
11723   Type *Tys[] = { Addr->getType() };
11724   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11725   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11726
11727   return Builder.CreateTruncOrBitCast(
11728       Builder.CreateCall(Ldrex, Addr),
11729       cast<PointerType>(Addr->getType())->getElementType());
11730 }
11731
11732 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11733     IRBuilder<> &Builder) const {
11734   if (!Subtarget->hasV7Ops())
11735     return;
11736   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11737   Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
11738 }
11739
11740 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11741                                                Value *Addr,
11742                                                AtomicOrdering Ord) const {
11743   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11744   bool IsRelease = isAtLeastRelease(Ord);
11745
11746   // Since the intrinsics must have legal type, the i64 intrinsics take two
11747   // parameters: "i32, i32". We must marshal Val into the appropriate form
11748   // before the call.
11749   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11750     Intrinsic::ID Int =
11751         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11752     Function *Strex = Intrinsic::getDeclaration(M, Int);
11753     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11754
11755     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11756     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11757     if (!Subtarget->isLittle())
11758       std::swap (Lo, Hi);
11759     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11760     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11761   }
11762
11763   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11764   Type *Tys[] = { Addr->getType() };
11765   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11766
11767   return Builder.CreateCall(
11768       Strex, {Builder.CreateZExtOrBitCast(
11769                   Val, Strex->getFunctionType()->getParamType(0)),
11770               Addr});
11771 }
11772
11773 /// \brief Lower an interleaved load into a vldN intrinsic.
11774 ///
11775 /// E.g. Lower an interleaved load (Factor = 2):
11776 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11777 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11778 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11779 ///
11780 ///      Into:
11781 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11782 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11783 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11784 bool ARMTargetLowering::lowerInterleavedLoad(
11785     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11786     ArrayRef<unsigned> Indices, unsigned Factor) const {
11787   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11788          "Invalid interleave factor");
11789   assert(!Shuffles.empty() && "Empty shufflevector input");
11790   assert(Shuffles.size() == Indices.size() &&
11791          "Unmatched number of shufflevectors and indices");
11792
11793   VectorType *VecTy = Shuffles[0]->getType();
11794   Type *EltTy = VecTy->getVectorElementType();
11795
11796   const DataLayout &DL = LI->getModule()->getDataLayout();
11797   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11798   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11799
11800   // Skip if we do not have NEON and skip illegal vector types and vector types
11801   // with i64/f64 elements (vldN doesn't support i64/f64 elements).
11802   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
11803     return false;
11804
11805   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11806   // load integer vectors first and then convert to pointer vectors.
11807   if (EltTy->isPointerTy())
11808     VecTy =
11809         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11810
11811   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11812                                             Intrinsic::arm_neon_vld3,
11813                                             Intrinsic::arm_neon_vld4};
11814
11815   IRBuilder<> Builder(LI);
11816   SmallVector<Value *, 2> Ops;
11817
11818   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11819   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11820   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11821
11822   Type *Tys[] = { VecTy, Int8Ptr };
11823   Function *VldnFunc =
11824       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
11825   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11826
11827   // Replace uses of each shufflevector with the corresponding vector loaded
11828   // by ldN.
11829   for (unsigned i = 0; i < Shuffles.size(); i++) {
11830     ShuffleVectorInst *SV = Shuffles[i];
11831     unsigned Index = Indices[i];
11832
11833     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11834
11835     // Convert the integer vector to pointer vector if the element is pointer.
11836     if (EltTy->isPointerTy())
11837       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11838
11839     SV->replaceAllUsesWith(SubVec);
11840   }
11841
11842   return true;
11843 }
11844
11845 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11846 ///
11847 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11848 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11849                                    unsigned NumElts) {
11850   SmallVector<Constant *, 16> Mask;
11851   for (unsigned i = 0; i < NumElts; i++)
11852     Mask.push_back(Builder.getInt32(Start + i));
11853
11854   return ConstantVector::get(Mask);
11855 }
11856
11857 /// \brief Lower an interleaved store into a vstN intrinsic.
11858 ///
11859 /// E.g. Lower an interleaved store (Factor = 3):
11860 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11861 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11862 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11863 ///
11864 ///      Into:
11865 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11866 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11867 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11868 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11869 ///
11870 /// Note that the new shufflevectors will be removed and we'll only generate one
11871 /// vst3 instruction in CodeGen.
11872 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11873                                               ShuffleVectorInst *SVI,
11874                                               unsigned Factor) const {
11875   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11876          "Invalid interleave factor");
11877
11878   VectorType *VecTy = SVI->getType();
11879   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11880          "Invalid interleaved store");
11881
11882   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11883   Type *EltTy = VecTy->getVectorElementType();
11884   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11885
11886   const DataLayout &DL = SI->getModule()->getDataLayout();
11887   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11888   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11889
11890   // Skip if we do not have NEON and skip illegal vector types and vector types
11891   // with i64/f64 elements (vstN doesn't support i64/f64 elements).
11892   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
11893       EltIs64Bits)
11894     return false;
11895
11896   Value *Op0 = SVI->getOperand(0);
11897   Value *Op1 = SVI->getOperand(1);
11898   IRBuilder<> Builder(SI);
11899
11900   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11901   // vectors to integer vectors.
11902   if (EltTy->isPointerTy()) {
11903     Type *IntTy = DL.getIntPtrType(EltTy);
11904
11905     // Convert to the corresponding integer vector.
11906     Type *IntVecTy =
11907         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11908     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11909     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11910
11911     SubVecTy = VectorType::get(IntTy, NumSubElts);
11912   }
11913
11914   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11915                                              Intrinsic::arm_neon_vst3,
11916                                              Intrinsic::arm_neon_vst4};
11917   SmallVector<Value *, 6> Ops;
11918
11919   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11920   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11921
11922   Type *Tys[] = { Int8Ptr, SubVecTy };
11923   Function *VstNFunc = Intrinsic::getDeclaration(
11924       SI->getModule(), StoreInts[Factor - 2], Tys);
11925
11926   // Split the shufflevector operands into sub vectors for the new vstN call.
11927   for (unsigned i = 0; i < Factor; i++)
11928     Ops.push_back(Builder.CreateShuffleVector(
11929         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11930
11931   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11932   Builder.CreateCall(VstNFunc, Ops);
11933   return true;
11934 }
11935
11936 enum HABaseType {
11937   HA_UNKNOWN = 0,
11938   HA_FLOAT,
11939   HA_DOUBLE,
11940   HA_VECT64,
11941   HA_VECT128
11942 };
11943
11944 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11945                                    uint64_t &Members) {
11946   if (auto *ST = dyn_cast<StructType>(Ty)) {
11947     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11948       uint64_t SubMembers = 0;
11949       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11950         return false;
11951       Members += SubMembers;
11952     }
11953   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11954     uint64_t SubMembers = 0;
11955     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11956       return false;
11957     Members += SubMembers * AT->getNumElements();
11958   } else if (Ty->isFloatTy()) {
11959     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11960       return false;
11961     Members = 1;
11962     Base = HA_FLOAT;
11963   } else if (Ty->isDoubleTy()) {
11964     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11965       return false;
11966     Members = 1;
11967     Base = HA_DOUBLE;
11968   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11969     Members = 1;
11970     switch (Base) {
11971     case HA_FLOAT:
11972     case HA_DOUBLE:
11973       return false;
11974     case HA_VECT64:
11975       return VT->getBitWidth() == 64;
11976     case HA_VECT128:
11977       return VT->getBitWidth() == 128;
11978     case HA_UNKNOWN:
11979       switch (VT->getBitWidth()) {
11980       case 64:
11981         Base = HA_VECT64;
11982         return true;
11983       case 128:
11984         Base = HA_VECT128;
11985         return true;
11986       default:
11987         return false;
11988       }
11989     }
11990   }
11991
11992   return (Members > 0 && Members <= 4);
11993 }
11994
11995 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11996 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11997 /// passing according to AAPCS rules.
11998 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11999     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12000   if (getEffectiveCallingConv(CallConv, isVarArg) !=
12001       CallingConv::ARM_AAPCS_VFP)
12002     return false;
12003
12004   HABaseType Base = HA_UNKNOWN;
12005   uint64_t Members = 0;
12006   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12007   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12008
12009   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12010   return IsHA || IsIntArray;
12011 }